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("…".to_string(), 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 wrap_width = match view.soft_wrap_mode(cx) {
1538 SoftWrap::None => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
1539 SoftWrap::EditorWidth => {
1540 Some(text_width - gutter_margin - overscroll.x() - em_width)
1541 }
1542 SoftWrap::Column(column) => Some(column as f32 * em_advance),
1543 };
1544
1545 if view.set_wrap_width(wrap_width, cx) {
1546 view.snapshot(cx)
1547 } else {
1548 snapshot
1549 }
1550 });
1551
1552 let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
1553 if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
1554 size.set_y(
1555 scroll_height
1556 .min(constraint.max_along(Axis::Vertical))
1557 .max(constraint.min_along(Axis::Vertical))
1558 .min(line_height * max_lines as f32),
1559 )
1560 } else if let EditorMode::SingleLine = snapshot.mode {
1561 size.set_y(
1562 line_height
1563 .min(constraint.max_along(Axis::Vertical))
1564 .max(constraint.min_along(Axis::Vertical)),
1565 )
1566 } else if size.y().is_infinite() {
1567 size.set_y(scroll_height);
1568 }
1569 let gutter_size = vec2f(gutter_width, size.y());
1570 let text_size = vec2f(text_width, size.y());
1571
1572 let (autoscroll_horizontally, mut snapshot) = self.update_view(cx.app, |view, cx| {
1573 let autoscroll_horizontally = view.autoscroll_vertically(size.y(), line_height, cx);
1574 let snapshot = view.snapshot(cx);
1575 (autoscroll_horizontally, snapshot)
1576 });
1577
1578 let scroll_position = snapshot.scroll_position();
1579 // The scroll position is a fractional point, the whole number of which represents
1580 // the top of the window in terms of display rows.
1581 let start_row = scroll_position.y() as u32;
1582 let height_in_lines = size.y() / line_height;
1583 let max_row = snapshot.max_point().row();
1584
1585 // Add 1 to ensure selections bleed off screen
1586 let end_row = 1 + cmp::min(
1587 (scroll_position.y() + height_in_lines).ceil() as u32,
1588 max_row,
1589 );
1590
1591 let start_anchor = if start_row == 0 {
1592 Anchor::min()
1593 } else {
1594 snapshot
1595 .buffer_snapshot
1596 .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
1597 };
1598 let end_anchor = if end_row > max_row {
1599 Anchor::max()
1600 } else {
1601 snapshot
1602 .buffer_snapshot
1603 .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
1604 };
1605
1606 let mut selections: Vec<(ReplicaId, Vec<SelectionLayout>)> = Vec::new();
1607 let mut active_rows = BTreeMap::new();
1608 let mut highlighted_rows = None;
1609 let mut highlighted_ranges = Vec::new();
1610 let mut show_scrollbars = false;
1611 let mut include_root = false;
1612 self.update_view(cx.app, |view, cx| {
1613 let display_map = view.display_map.update(cx, |map, cx| map.snapshot(cx));
1614
1615 highlighted_rows = view.highlighted_rows();
1616 let theme = cx.global::<Settings>().theme.as_ref();
1617 highlighted_ranges =
1618 view.background_highlights_in_range(start_anchor..end_anchor, &display_map, theme);
1619
1620 let mut remote_selections = HashMap::default();
1621 for (replica_id, line_mode, cursor_shape, selection) in display_map
1622 .buffer_snapshot
1623 .remote_selections_in_range(&(start_anchor..end_anchor))
1624 {
1625 // The local selections match the leader's selections.
1626 if Some(replica_id) == view.leader_replica_id {
1627 continue;
1628 }
1629 remote_selections
1630 .entry(replica_id)
1631 .or_insert(Vec::new())
1632 .push(SelectionLayout::new(
1633 selection,
1634 line_mode,
1635 cursor_shape,
1636 &display_map,
1637 ));
1638 }
1639 selections.extend(remote_selections);
1640
1641 if view.show_local_selections {
1642 let mut local_selections = view
1643 .selections
1644 .disjoint_in_range(start_anchor..end_anchor, cx);
1645 local_selections.extend(view.selections.pending(cx));
1646 for selection in &local_selections {
1647 let is_empty = selection.start == selection.end;
1648 let selection_start = snapshot.prev_line_boundary(selection.start).1;
1649 let selection_end = snapshot.next_line_boundary(selection.end).1;
1650 for row in cmp::max(selection_start.row(), start_row)
1651 ..=cmp::min(selection_end.row(), end_row)
1652 {
1653 let contains_non_empty_selection =
1654 active_rows.entry(row).or_insert(!is_empty);
1655 *contains_non_empty_selection |= !is_empty;
1656 }
1657 }
1658
1659 // Render the local selections in the leader's color when following.
1660 let local_replica_id = view
1661 .leader_replica_id
1662 .unwrap_or_else(|| view.replica_id(cx));
1663
1664 selections.push((
1665 local_replica_id,
1666 local_selections
1667 .into_iter()
1668 .map(|selection| {
1669 SelectionLayout::new(
1670 selection,
1671 view.selections.line_mode,
1672 view.cursor_shape,
1673 &display_map,
1674 )
1675 })
1676 .collect(),
1677 ));
1678 }
1679
1680 show_scrollbars = view.scroll_manager.scrollbars_visible();
1681 include_root = view
1682 .project
1683 .as_ref()
1684 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
1685 .unwrap_or_default()
1686 });
1687
1688 let line_number_layouts =
1689 self.layout_line_numbers(start_row..end_row, &active_rows, &snapshot, cx);
1690
1691 let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
1692
1693 let scrollbar_row_range = scroll_position.y()..(scroll_position.y() + height_in_lines);
1694
1695 let mut max_visible_line_width = 0.0;
1696 let line_layouts = self.layout_lines(start_row..end_row, &snapshot, cx);
1697 for line in &line_layouts {
1698 if line.width() > max_visible_line_width {
1699 max_visible_line_width = line.width();
1700 }
1701 }
1702
1703 let style = self.style.clone();
1704 let longest_line_width = layout_line(
1705 snapshot.longest_row(),
1706 &snapshot,
1707 &style,
1708 cx.text_layout_cache,
1709 )
1710 .width();
1711 let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
1712 let em_width = style.text.em_width(cx.font_cache);
1713 let (scroll_width, blocks) = self.layout_blocks(
1714 start_row..end_row,
1715 &snapshot,
1716 size.x(),
1717 scroll_width,
1718 gutter_padding,
1719 gutter_width,
1720 em_width,
1721 gutter_width + gutter_margin,
1722 line_height,
1723 &style,
1724 &line_layouts,
1725 include_root,
1726 cx,
1727 );
1728
1729 let scroll_max = vec2f(
1730 ((scroll_width - text_size.x()) / em_width).max(0.0),
1731 max_row as f32,
1732 );
1733
1734 self.update_view(cx.app, |view, cx| {
1735 let clamped = view.scroll_manager.clamp_scroll_left(scroll_max.x());
1736
1737 let autoscrolled = if autoscroll_horizontally {
1738 view.autoscroll_horizontally(
1739 start_row,
1740 text_size.x(),
1741 scroll_width,
1742 em_width,
1743 &line_layouts,
1744 cx,
1745 )
1746 } else {
1747 false
1748 };
1749
1750 if clamped || autoscrolled {
1751 snapshot = view.snapshot(cx);
1752 }
1753 });
1754
1755 let mut context_menu = None;
1756 let mut code_actions_indicator = None;
1757 let mut hover = None;
1758 let mut mode = EditorMode::Full;
1759 cx.render(&self.view.upgrade(cx).unwrap(), |view, cx| {
1760 let newest_selection_head = view
1761 .selections
1762 .newest::<usize>(cx)
1763 .head()
1764 .to_display_point(&snapshot);
1765
1766 let style = view.style(cx);
1767 if (start_row..end_row).contains(&newest_selection_head.row()) {
1768 if view.context_menu_visible() {
1769 context_menu =
1770 view.render_context_menu(newest_selection_head, style.clone(), cx);
1771 }
1772
1773 code_actions_indicator = view
1774 .render_code_actions_indicator(&style, cx)
1775 .map(|indicator| (newest_selection_head.row(), indicator));
1776 }
1777
1778 let visible_rows = start_row..start_row + line_layouts.len() as u32;
1779 hover = view.hover_state.render(&snapshot, &style, visible_rows, cx);
1780 mode = view.mode;
1781 });
1782
1783 if let Some((_, context_menu)) = context_menu.as_mut() {
1784 context_menu.layout(
1785 SizeConstraint {
1786 min: Vector2F::zero(),
1787 max: vec2f(
1788 cx.window_size.x() * 0.7,
1789 (12. * line_height).min((size.y() - line_height) / 2.),
1790 ),
1791 },
1792 cx,
1793 );
1794 }
1795
1796 if let Some((_, indicator)) = code_actions_indicator.as_mut() {
1797 indicator.layout(
1798 SizeConstraint::strict_along(
1799 Axis::Vertical,
1800 line_height * style.code_actions.vertical_scale,
1801 ),
1802 cx,
1803 );
1804 }
1805
1806 if let Some((_, hover_popovers)) = hover.as_mut() {
1807 for hover_popover in hover_popovers.iter_mut() {
1808 hover_popover.layout(
1809 SizeConstraint {
1810 min: Vector2F::zero(),
1811 max: vec2f(
1812 (120. * em_width) // Default size
1813 .min(size.x() / 2.) // Shrink to half of the editor width
1814 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
1815 (16. * line_height) // Default size
1816 .min(size.y() / 2.) // Shrink to half of the editor height
1817 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
1818 ),
1819 },
1820 cx,
1821 );
1822 }
1823 }
1824
1825 (
1826 size,
1827 LayoutState {
1828 mode,
1829 position_map: Arc::new(PositionMap {
1830 size,
1831 scroll_max,
1832 line_layouts,
1833 line_height,
1834 em_width,
1835 em_advance,
1836 snapshot,
1837 }),
1838 visible_display_row_range: start_row..end_row,
1839 gutter_size,
1840 gutter_padding,
1841 text_size,
1842 scrollbar_row_range,
1843 show_scrollbars,
1844 max_row,
1845 gutter_margin,
1846 active_rows,
1847 highlighted_rows,
1848 highlighted_ranges,
1849 line_number_layouts,
1850 display_hunks,
1851 blocks,
1852 selections,
1853 context_menu,
1854 code_actions_indicator,
1855 hover_popovers: hover,
1856 },
1857 )
1858 }
1859
1860 fn paint(
1861 &mut self,
1862 bounds: RectF,
1863 visible_bounds: RectF,
1864 layout: &mut Self::LayoutState,
1865 cx: &mut PaintContext,
1866 ) -> Self::PaintState {
1867 let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
1868 cx.scene.push_layer(Some(visible_bounds));
1869
1870 let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
1871 let text_bounds = RectF::new(
1872 bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
1873 layout.text_size,
1874 );
1875
1876 Self::attach_mouse_handlers(
1877 &self.view,
1878 &layout.position_map,
1879 layout.hover_popovers.is_some(),
1880 visible_bounds,
1881 text_bounds,
1882 gutter_bounds,
1883 bounds,
1884 cx,
1885 );
1886
1887 self.paint_background(gutter_bounds, text_bounds, layout, cx);
1888 if layout.gutter_size.x() > 0. {
1889 self.paint_gutter(gutter_bounds, visible_bounds, layout, cx);
1890 }
1891 self.paint_text(text_bounds, visible_bounds, layout, cx);
1892
1893 cx.scene.push_layer(Some(bounds));
1894 if !layout.blocks.is_empty() {
1895 self.paint_blocks(bounds, visible_bounds, layout, cx);
1896 }
1897 self.paint_scrollbar(bounds, layout, cx);
1898 cx.scene.pop_layer();
1899
1900 cx.scene.pop_layer();
1901 }
1902
1903 fn rect_for_text_range(
1904 &self,
1905 range_utf16: Range<usize>,
1906 bounds: RectF,
1907 _: RectF,
1908 layout: &Self::LayoutState,
1909 _: &Self::PaintState,
1910 _: &gpui::MeasurementContext,
1911 ) -> Option<RectF> {
1912 let text_bounds = RectF::new(
1913 bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
1914 layout.text_size,
1915 );
1916 let content_origin = text_bounds.origin() + vec2f(layout.gutter_margin, 0.);
1917 let scroll_position = layout.position_map.snapshot.scroll_position();
1918 let start_row = scroll_position.y() as u32;
1919 let scroll_top = scroll_position.y() * layout.position_map.line_height;
1920 let scroll_left = scroll_position.x() * layout.position_map.em_width;
1921
1922 let range_start = OffsetUtf16(range_utf16.start)
1923 .to_display_point(&layout.position_map.snapshot.display_snapshot);
1924 if range_start.row() < start_row {
1925 return None;
1926 }
1927
1928 let line = layout
1929 .position_map
1930 .line_layouts
1931 .get((range_start.row() - start_row) as usize)?;
1932 let range_start_x = line.x_for_index(range_start.column() as usize);
1933 let range_start_y = range_start.row() as f32 * layout.position_map.line_height;
1934 Some(RectF::new(
1935 content_origin
1936 + vec2f(
1937 range_start_x,
1938 range_start_y + layout.position_map.line_height,
1939 )
1940 - vec2f(scroll_left, scroll_top),
1941 vec2f(
1942 layout.position_map.em_width,
1943 layout.position_map.line_height,
1944 ),
1945 ))
1946 }
1947
1948 fn debug(
1949 &self,
1950 bounds: RectF,
1951 _: &Self::LayoutState,
1952 _: &Self::PaintState,
1953 _: &gpui::DebugContext,
1954 ) -> json::Value {
1955 json!({
1956 "type": "BufferElement",
1957 "bounds": bounds.to_json()
1958 })
1959 }
1960}
1961
1962pub struct LayoutState {
1963 position_map: Arc<PositionMap>,
1964 gutter_size: Vector2F,
1965 gutter_padding: f32,
1966 gutter_margin: f32,
1967 text_size: Vector2F,
1968 mode: EditorMode,
1969 visible_display_row_range: Range<u32>,
1970 active_rows: BTreeMap<u32, bool>,
1971 highlighted_rows: Option<Range<u32>>,
1972 line_number_layouts: Vec<Option<text_layout::Line>>,
1973 display_hunks: Vec<DisplayDiffHunk>,
1974 blocks: Vec<BlockLayout>,
1975 highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
1976 selections: Vec<(ReplicaId, Vec<SelectionLayout>)>,
1977 scrollbar_row_range: Range<f32>,
1978 show_scrollbars: bool,
1979 max_row: u32,
1980 context_menu: Option<(DisplayPoint, ElementBox)>,
1981 code_actions_indicator: Option<(u32, ElementBox)>,
1982 hover_popovers: Option<(DisplayPoint, Vec<ElementBox>)>,
1983}
1984
1985pub struct PositionMap {
1986 size: Vector2F,
1987 line_height: f32,
1988 scroll_max: Vector2F,
1989 em_width: f32,
1990 em_advance: f32,
1991 line_layouts: Vec<text_layout::Line>,
1992 snapshot: EditorSnapshot,
1993}
1994
1995impl PositionMap {
1996 /// Returns two display points:
1997 /// 1. The nearest *valid* position in the editor
1998 /// 2. An unclipped, potentially *invalid* position that maps directly to
1999 /// the given pixel position.
2000 fn point_for_position(
2001 &self,
2002 text_bounds: RectF,
2003 position: Vector2F,
2004 ) -> (DisplayPoint, DisplayPoint) {
2005 let scroll_position = self.snapshot.scroll_position();
2006 let position = position - text_bounds.origin();
2007 let y = position.y().max(0.0).min(self.size.y());
2008 let x = position.x() + (scroll_position.x() * self.em_width);
2009 let row = (y / self.line_height + scroll_position.y()) as u32;
2010 let (column, x_overshoot) = if let Some(line) = self
2011 .line_layouts
2012 .get(row as usize - scroll_position.y() as usize)
2013 {
2014 if let Some(ix) = line.index_for_x(x) {
2015 (ix as u32, 0.0)
2016 } else {
2017 (line.len() as u32, 0f32.max(x - line.width()))
2018 }
2019 } else {
2020 (0, x)
2021 };
2022
2023 let mut target_point = DisplayPoint::new(row, column);
2024 let point = self.snapshot.clip_point(target_point, Bias::Left);
2025 *target_point.column_mut() += (x_overshoot / self.em_advance) as u32;
2026
2027 (point, target_point)
2028 }
2029}
2030
2031struct BlockLayout {
2032 row: u32,
2033 element: ElementBox,
2034 style: BlockStyle,
2035}
2036
2037fn layout_line(
2038 row: u32,
2039 snapshot: &EditorSnapshot,
2040 style: &EditorStyle,
2041 layout_cache: &TextLayoutCache,
2042) -> text_layout::Line {
2043 let mut line = snapshot.line(row);
2044
2045 if line.len() > MAX_LINE_LEN {
2046 let mut len = MAX_LINE_LEN;
2047 while !line.is_char_boundary(len) {
2048 len -= 1;
2049 }
2050
2051 line.truncate(len);
2052 }
2053
2054 layout_cache.layout_str(
2055 &line,
2056 style.text.font_size,
2057 &[(
2058 snapshot.line_len(row) as usize,
2059 RunStyle {
2060 font_id: style.text.font_id,
2061 color: Color::black(),
2062 underline: Default::default(),
2063 },
2064 )],
2065 )
2066}
2067
2068#[derive(Debug)]
2069pub struct Cursor {
2070 origin: Vector2F,
2071 block_width: f32,
2072 line_height: f32,
2073 color: Color,
2074 shape: CursorShape,
2075 block_text: Option<Line>,
2076}
2077
2078impl Cursor {
2079 pub fn new(
2080 origin: Vector2F,
2081 block_width: f32,
2082 line_height: f32,
2083 color: Color,
2084 shape: CursorShape,
2085 block_text: Option<Line>,
2086 ) -> Cursor {
2087 Cursor {
2088 origin,
2089 block_width,
2090 line_height,
2091 color,
2092 shape,
2093 block_text,
2094 }
2095 }
2096
2097 pub fn bounding_rect(&self, origin: Vector2F) -> RectF {
2098 RectF::new(
2099 self.origin + origin,
2100 vec2f(self.block_width, self.line_height),
2101 )
2102 }
2103
2104 pub fn paint(&self, origin: Vector2F, cx: &mut PaintContext) {
2105 let bounds = match self.shape {
2106 CursorShape::Bar => RectF::new(self.origin + origin, vec2f(2.0, self.line_height)),
2107 CursorShape::Block | CursorShape::Hollow => RectF::new(
2108 self.origin + origin,
2109 vec2f(self.block_width, self.line_height),
2110 ),
2111 CursorShape::Underscore => RectF::new(
2112 self.origin + origin + Vector2F::new(0.0, self.line_height - 2.0),
2113 vec2f(self.block_width, 2.0),
2114 ),
2115 };
2116
2117 //Draw background or border quad
2118 if matches!(self.shape, CursorShape::Hollow) {
2119 cx.scene.push_quad(Quad {
2120 bounds,
2121 background: None,
2122 border: Border::all(1., self.color),
2123 corner_radius: 0.,
2124 });
2125 } else {
2126 cx.scene.push_quad(Quad {
2127 bounds,
2128 background: Some(self.color),
2129 border: Default::default(),
2130 corner_radius: 0.,
2131 });
2132 }
2133
2134 if let Some(block_text) = &self.block_text {
2135 block_text.paint(self.origin + origin, bounds, self.line_height, cx);
2136 }
2137 }
2138
2139 pub fn shape(&self) -> CursorShape {
2140 self.shape
2141 }
2142}
2143
2144#[derive(Debug)]
2145pub struct HighlightedRange {
2146 pub start_y: f32,
2147 pub line_height: f32,
2148 pub lines: Vec<HighlightedRangeLine>,
2149 pub color: Color,
2150 pub corner_radius: f32,
2151}
2152
2153#[derive(Debug)]
2154pub struct HighlightedRangeLine {
2155 pub start_x: f32,
2156 pub end_x: f32,
2157}
2158
2159impl HighlightedRange {
2160 pub fn paint(&self, bounds: RectF, scene: &mut SceneBuilder) {
2161 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
2162 self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
2163 self.paint_lines(
2164 self.start_y + self.line_height,
2165 &self.lines[1..],
2166 bounds,
2167 scene,
2168 );
2169 } else {
2170 self.paint_lines(self.start_y, &self.lines, bounds, scene);
2171 }
2172 }
2173
2174 fn paint_lines(
2175 &self,
2176 start_y: f32,
2177 lines: &[HighlightedRangeLine],
2178 bounds: RectF,
2179 scene: &mut SceneBuilder,
2180 ) {
2181 if lines.is_empty() {
2182 return;
2183 }
2184
2185 let mut path = PathBuilder::new();
2186 let first_line = lines.first().unwrap();
2187 let last_line = lines.last().unwrap();
2188
2189 let first_top_left = vec2f(first_line.start_x, start_y);
2190 let first_top_right = vec2f(first_line.end_x, start_y);
2191
2192 let curve_height = vec2f(0., self.corner_radius);
2193 let curve_width = |start_x: f32, end_x: f32| {
2194 let max = (end_x - start_x) / 2.;
2195 let width = if max < self.corner_radius {
2196 max
2197 } else {
2198 self.corner_radius
2199 };
2200
2201 vec2f(width, 0.)
2202 };
2203
2204 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
2205 path.reset(first_top_right - top_curve_width);
2206 path.curve_to(first_top_right + curve_height, first_top_right);
2207
2208 let mut iter = lines.iter().enumerate().peekable();
2209 while let Some((ix, line)) = iter.next() {
2210 let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
2211
2212 if let Some((_, next_line)) = iter.peek() {
2213 let next_top_right = vec2f(next_line.end_x, bottom_right.y());
2214
2215 match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
2216 Ordering::Equal => {
2217 path.line_to(bottom_right);
2218 }
2219 Ordering::Less => {
2220 let curve_width = curve_width(next_top_right.x(), bottom_right.x());
2221 path.line_to(bottom_right - curve_height);
2222 if self.corner_radius > 0. {
2223 path.curve_to(bottom_right - curve_width, bottom_right);
2224 }
2225 path.line_to(next_top_right + curve_width);
2226 if self.corner_radius > 0. {
2227 path.curve_to(next_top_right + curve_height, next_top_right);
2228 }
2229 }
2230 Ordering::Greater => {
2231 let curve_width = curve_width(bottom_right.x(), next_top_right.x());
2232 path.line_to(bottom_right - curve_height);
2233 if self.corner_radius > 0. {
2234 path.curve_to(bottom_right + curve_width, bottom_right);
2235 }
2236 path.line_to(next_top_right - curve_width);
2237 if self.corner_radius > 0. {
2238 path.curve_to(next_top_right + curve_height, next_top_right);
2239 }
2240 }
2241 }
2242 } else {
2243 let curve_width = curve_width(line.start_x, line.end_x);
2244 path.line_to(bottom_right - curve_height);
2245 if self.corner_radius > 0. {
2246 path.curve_to(bottom_right - curve_width, bottom_right);
2247 }
2248
2249 let bottom_left = vec2f(line.start_x, bottom_right.y());
2250 path.line_to(bottom_left + curve_width);
2251 if self.corner_radius > 0. {
2252 path.curve_to(bottom_left - curve_height, bottom_left);
2253 }
2254 }
2255 }
2256
2257 if first_line.start_x > last_line.start_x {
2258 let curve_width = curve_width(last_line.start_x, first_line.start_x);
2259 let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
2260 path.line_to(second_top_left + curve_height);
2261 if self.corner_radius > 0. {
2262 path.curve_to(second_top_left + curve_width, second_top_left);
2263 }
2264 let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
2265 path.line_to(first_bottom_left - curve_width);
2266 if self.corner_radius > 0. {
2267 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
2268 }
2269 }
2270
2271 path.line_to(first_top_left + curve_height);
2272 if self.corner_radius > 0. {
2273 path.curve_to(first_top_left + top_curve_width, first_top_left);
2274 }
2275 path.line_to(first_top_right - top_curve_width);
2276
2277 scene.push_path(path.build(self.color, Some(bounds)));
2278 }
2279}
2280
2281pub fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
2282 delta.powf(1.5) / 100.0
2283}
2284
2285fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
2286 delta.powf(1.2) / 300.0
2287}
2288
2289#[cfg(test)]
2290mod tests {
2291 use std::sync::Arc;
2292
2293 use super::*;
2294 use crate::{
2295 display_map::{BlockDisposition, BlockProperties},
2296 Editor, MultiBuffer,
2297 };
2298 use settings::Settings;
2299 use util::test::sample_text;
2300
2301 #[gpui::test]
2302 fn test_layout_line_numbers(cx: &mut gpui::MutableAppContext) {
2303 cx.set_global(Settings::test(cx));
2304 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
2305 let (window_id, editor) = cx.add_window(Default::default(), |cx| {
2306 Editor::new(EditorMode::Full, buffer, None, None, cx)
2307 });
2308 let element = EditorElement::new(editor.downgrade(), editor.read(cx).style(cx));
2309
2310 let layouts = editor.update(cx, |editor, cx| {
2311 let snapshot = editor.snapshot(cx);
2312 let mut presenter = cx.build_presenter(window_id, 30., Default::default());
2313 let layout_cx = presenter.build_layout_context(Vector2F::zero(), false, cx);
2314 element.layout_line_numbers(0..6, &Default::default(), &snapshot, &layout_cx)
2315 });
2316 assert_eq!(layouts.len(), 6);
2317 }
2318
2319 #[gpui::test]
2320 fn test_layout_with_placeholder_text_and_blocks(cx: &mut gpui::MutableAppContext) {
2321 cx.set_global(Settings::test(cx));
2322 let buffer = MultiBuffer::build_simple("", cx);
2323 let (window_id, editor) = cx.add_window(Default::default(), |cx| {
2324 Editor::new(EditorMode::Full, buffer, None, None, cx)
2325 });
2326
2327 editor.update(cx, |editor, cx| {
2328 editor.set_placeholder_text("hello", cx);
2329 editor.insert_blocks(
2330 [BlockProperties {
2331 style: BlockStyle::Fixed,
2332 disposition: BlockDisposition::Above,
2333 height: 3,
2334 position: Anchor::min(),
2335 render: Arc::new(|_| Empty::new().boxed()),
2336 }],
2337 cx,
2338 );
2339
2340 // Blur the editor so that it displays placeholder text.
2341 cx.blur();
2342 });
2343
2344 let mut element = EditorElement::new(editor.downgrade(), editor.read(cx).style(cx));
2345
2346 let mut scene = SceneBuilder::new(1.0);
2347 let mut presenter = cx.build_presenter(window_id, 30., Default::default());
2348 let mut layout_cx = presenter.build_layout_context(Vector2F::zero(), false, cx);
2349 let (size, mut state) = element.layout(
2350 SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
2351 &mut layout_cx,
2352 );
2353
2354 assert_eq!(state.position_map.line_layouts.len(), 4);
2355 assert_eq!(
2356 state
2357 .line_number_layouts
2358 .iter()
2359 .map(Option::is_some)
2360 .collect::<Vec<_>>(),
2361 &[false, false, false, true]
2362 );
2363
2364 // Don't panic.
2365 let bounds = RectF::new(Default::default(), size);
2366 let mut paint_cx = presenter.build_paint_context(&mut scene, bounds.size(), cx);
2367 element.paint(bounds, bounds, &mut state, &mut paint_cx);
2368 }
2369}