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