1use super::{
2 display_map::{BlockContext, ToDisplayPoint},
3 Anchor, DisplayPoint, Editor, EditorMode, EditorSnapshot, Select, SelectPhase, SoftWrap,
4 ToPoint, MAX_LINE_LEN,
5};
6use crate::{
7 display_map::{BlockStyle, DisplaySnapshot, FoldStatus, TransformBlock},
8 git::{diff_hunk_to_display, DisplayDiffHunk},
9 hover_popover::{
10 HideHover, HoverAt, HOVER_POPOVER_GAP, MIN_POPOVER_CHARACTER_WIDTH, MIN_POPOVER_LINE_HEIGHT,
11 },
12 link_go_to_definition::{
13 GoToFetchedDefinition, GoToFetchedTypeDefinition, UpdateGoToDefinitionLink,
14 },
15 mouse_context_menu::DeployMouseContextMenu,
16 scroll::actions::Scroll,
17 EditorStyle,
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 for (line, fold_indicator) in layout.fold_indicators.iter_mut() {
580 let mut x = bounds.width() - layout.gutter_padding;
581 let mut y = *line as f32 * line_height - scroll_top;
582
583 x += ((layout.gutter_padding + layout.gutter_margin) - fold_indicator.size().x()) / 2.;
584 y += (line_height - fold_indicator.size().y()) / 2.;
585
586 fold_indicator.paint(bounds.origin() + vec2f(x, y), visible_bounds, cx);
587 }
588 }
589
590 fn paint_diff_hunks(bounds: RectF, layout: &mut LayoutState, cx: &mut PaintContext) {
591 let diff_style = &cx.global::<Settings>().theme.editor.diff.clone();
592 let line_height = layout.position_map.line_height;
593
594 let scroll_position = layout.position_map.snapshot.scroll_position();
595 let scroll_top = scroll_position.y() * line_height;
596
597 for hunk in &layout.display_hunks {
598 let (display_row_range, status) = match hunk {
599 //TODO: This rendering is entirely a horrible hack
600 &DisplayDiffHunk::Folded { display_row: row } => {
601 let start_y = row as f32 * line_height - scroll_top;
602 let end_y = start_y + line_height;
603
604 let width = diff_style.removed_width_em * line_height;
605 let highlight_origin = bounds.origin() + vec2f(-width, start_y);
606 let highlight_size = vec2f(width * 2., end_y - start_y);
607 let highlight_bounds = RectF::new(highlight_origin, highlight_size);
608
609 cx.scene.push_quad(Quad {
610 bounds: highlight_bounds,
611 background: Some(diff_style.modified),
612 border: Border::new(0., Color::transparent_black()),
613 corner_radius: 1. * line_height,
614 });
615
616 continue;
617 }
618
619 DisplayDiffHunk::Unfolded {
620 display_row_range,
621 status,
622 } => (display_row_range, status),
623 };
624
625 let color = match status {
626 DiffHunkStatus::Added => diff_style.inserted,
627 DiffHunkStatus::Modified => diff_style.modified,
628
629 //TODO: This rendering is entirely a horrible hack
630 DiffHunkStatus::Removed => {
631 let row = *display_row_range.start();
632
633 let offset = line_height / 2.;
634 let start_y = row as f32 * line_height - offset - scroll_top;
635 let end_y = start_y + line_height;
636
637 let width = diff_style.removed_width_em * line_height;
638 let highlight_origin = bounds.origin() + vec2f(-width, start_y);
639 let highlight_size = vec2f(width * 2., end_y - start_y);
640 let highlight_bounds = RectF::new(highlight_origin, highlight_size);
641
642 cx.scene.push_quad(Quad {
643 bounds: highlight_bounds,
644 background: Some(diff_style.deleted),
645 border: Border::new(0., Color::transparent_black()),
646 corner_radius: 1. * line_height,
647 });
648
649 continue;
650 }
651 };
652
653 let start_row = *display_row_range.start();
654 let end_row = *display_row_range.end();
655
656 let start_y = start_row as f32 * line_height - scroll_top;
657 let end_y = end_row as f32 * line_height - scroll_top + line_height;
658
659 let width = diff_style.width_em * line_height;
660 let highlight_origin = bounds.origin() + vec2f(-width, start_y);
661 let highlight_size = vec2f(width * 2., end_y - start_y);
662 let highlight_bounds = RectF::new(highlight_origin, highlight_size);
663
664 cx.scene.push_quad(Quad {
665 bounds: highlight_bounds,
666 background: Some(color),
667 border: Border::new(0., Color::transparent_black()),
668 corner_radius: diff_style.corner_radius * line_height,
669 });
670 }
671 }
672
673 fn paint_text(
674 &mut self,
675 bounds: RectF,
676 visible_bounds: RectF,
677 layout: &mut LayoutState,
678 cx: &mut PaintContext,
679 ) {
680 let view = self.view(cx.app);
681 let style = &self.style;
682 let local_replica_id = view.replica_id(cx);
683 let scroll_position = layout.position_map.snapshot.scroll_position();
684 let start_row = layout.visible_display_row_range.start;
685 let scroll_top = scroll_position.y() * layout.position_map.line_height;
686 let max_glyph_width = layout.position_map.em_width;
687 let scroll_left = scroll_position.x() * max_glyph_width;
688 let content_origin = bounds.origin() + vec2f(layout.gutter_margin, 0.);
689
690 cx.scene.push_layer(Some(bounds));
691
692 cx.scene.push_cursor_region(CursorRegion {
693 bounds,
694 style: if !view.link_go_to_definition_state.definitions.is_empty() {
695 CursorStyle::PointingHand
696 } else {
697 CursorStyle::IBeam
698 },
699 });
700
701 for (range, color) in &layout.highlighted_ranges {
702 self.paint_highlighted_range(
703 range.clone(),
704 *color,
705 0.,
706 0.15 * layout.position_map.line_height,
707 layout,
708 content_origin,
709 scroll_top,
710 scroll_left,
711 bounds,
712 cx,
713 );
714 }
715
716 let mut cursors = SmallVec::<[Cursor; 32]>::new();
717 for (replica_id, selections) in &layout.selections {
718 let selection_style = style.replica_selection_style(*replica_id);
719 let corner_radius = 0.15 * layout.position_map.line_height;
720
721 for selection in selections {
722 self.paint_highlighted_range(
723 selection.range.clone(),
724 selection_style.selection,
725 corner_radius,
726 corner_radius * 2.,
727 layout,
728 content_origin,
729 scroll_top,
730 scroll_left,
731 bounds,
732 cx,
733 );
734
735 if view.show_local_cursors(cx) || *replica_id != local_replica_id {
736 let cursor_position = selection.head;
737 if layout
738 .visible_display_row_range
739 .contains(&cursor_position.row())
740 {
741 let cursor_row_layout = &layout.position_map.line_layouts
742 [(cursor_position.row() - start_row) as usize];
743 let cursor_column = cursor_position.column() as usize;
744
745 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
746 let mut block_width =
747 cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
748 if block_width == 0.0 {
749 block_width = layout.position_map.em_width;
750 }
751 let block_text = if let CursorShape::Block = selection.cursor_shape {
752 layout
753 .position_map
754 .snapshot
755 .chars_at(cursor_position)
756 .next()
757 .and_then(|(character, _)| {
758 let font_id =
759 cursor_row_layout.font_for_index(cursor_column)?;
760 let text = character.to_string();
761
762 Some(cx.text_layout_cache.layout_str(
763 &text,
764 cursor_row_layout.font_size(),
765 &[(
766 text.len(),
767 RunStyle {
768 font_id,
769 color: style.background,
770 underline: Default::default(),
771 },
772 )],
773 ))
774 })
775 } else {
776 None
777 };
778
779 let x = cursor_character_x - scroll_left;
780 let y = cursor_position.row() as f32 * layout.position_map.line_height
781 - scroll_top;
782 cursors.push(Cursor {
783 color: selection_style.cursor,
784 block_width,
785 origin: vec2f(x, y),
786 line_height: layout.position_map.line_height,
787 shape: selection.cursor_shape,
788 block_text,
789 });
790 }
791 }
792 }
793 }
794
795 if let Some(visible_text_bounds) = bounds.intersection(visible_bounds) {
796 // Draw glyphs
797 for (ix, line) in layout.position_map.line_layouts.iter().enumerate() {
798 let row = start_row + ix as u32;
799 line.paint(
800 content_origin
801 + vec2f(
802 -scroll_left,
803 row as f32 * layout.position_map.line_height - scroll_top,
804 ),
805 visible_text_bounds,
806 layout.position_map.line_height,
807 cx,
808 );
809 }
810 }
811
812 cx.scene.push_layer(Some(bounds));
813 for cursor in cursors {
814 cursor.paint(content_origin, cx);
815 }
816 cx.scene.pop_layer();
817
818 if let Some((position, context_menu)) = layout.context_menu.as_mut() {
819 cx.scene.push_stacking_context(None, None);
820 let cursor_row_layout =
821 &layout.position_map.line_layouts[(position.row() - start_row) as usize];
822 let x = cursor_row_layout.x_for_index(position.column() as usize) - scroll_left;
823 let y = (position.row() + 1) as f32 * layout.position_map.line_height - scroll_top;
824 let mut list_origin = content_origin + vec2f(x, y);
825 let list_width = context_menu.size().x();
826 let list_height = context_menu.size().y();
827
828 // Snap the right edge of the list to the right edge of the window if
829 // its horizontal bounds overflow.
830 if list_origin.x() + list_width > cx.window_size.x() {
831 list_origin.set_x((cx.window_size.x() - list_width).max(0.));
832 }
833
834 if list_origin.y() + list_height > bounds.max_y() {
835 list_origin.set_y(list_origin.y() - layout.position_map.line_height - list_height);
836 }
837
838 context_menu.paint(
839 list_origin,
840 RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
841 cx,
842 );
843
844 cx.scene.pop_stacking_context();
845 }
846
847 if let Some((position, hover_popovers)) = layout.hover_popovers.as_mut() {
848 cx.scene.push_stacking_context(None, None);
849
850 // This is safe because we check on layout whether the required row is available
851 let hovered_row_layout =
852 &layout.position_map.line_layouts[(position.row() - start_row) as usize];
853
854 // Minimum required size: Take the first popover, and add 1.5 times the minimum popover
855 // height. This is the size we will use to decide whether to render popovers above or below
856 // the hovered line.
857 let first_size = hover_popovers[0].size();
858 let height_to_reserve = first_size.y()
859 + 1.5 * MIN_POPOVER_LINE_HEIGHT as f32 * layout.position_map.line_height;
860
861 // Compute Hovered Point
862 let x = hovered_row_layout.x_for_index(position.column() as usize) - scroll_left;
863 let y = position.row() as f32 * layout.position_map.line_height - scroll_top;
864 let hovered_point = content_origin + vec2f(x, y);
865
866 if hovered_point.y() - height_to_reserve > 0.0 {
867 // There is enough space above. Render popovers above the hovered point
868 let mut current_y = hovered_point.y();
869 for hover_popover in hover_popovers {
870 let size = hover_popover.size();
871 let mut popover_origin = vec2f(hovered_point.x(), current_y - size.y());
872
873 let x_out_of_bounds = bounds.max_x() - (popover_origin.x() + size.x());
874 if x_out_of_bounds < 0.0 {
875 popover_origin.set_x(popover_origin.x() + x_out_of_bounds);
876 }
877
878 hover_popover.paint(
879 popover_origin,
880 RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
881 cx,
882 );
883
884 current_y = popover_origin.y() - HOVER_POPOVER_GAP;
885 }
886 } else {
887 // There is not enough space above. Render popovers below the hovered point
888 let mut current_y = hovered_point.y() + layout.position_map.line_height;
889 for hover_popover in hover_popovers {
890 let size = hover_popover.size();
891 let mut popover_origin = vec2f(hovered_point.x(), current_y);
892
893 let x_out_of_bounds = bounds.max_x() - (popover_origin.x() + size.x());
894 if x_out_of_bounds < 0.0 {
895 popover_origin.set_x(popover_origin.x() + x_out_of_bounds);
896 }
897
898 hover_popover.paint(
899 popover_origin,
900 RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
901 cx,
902 );
903
904 current_y = popover_origin.y() + size.y() + HOVER_POPOVER_GAP;
905 }
906 }
907
908 cx.scene.pop_stacking_context();
909 }
910
911 cx.scene.pop_layer();
912 }
913
914 fn paint_scrollbar(&mut self, bounds: RectF, layout: &mut LayoutState, cx: &mut PaintContext) {
915 enum ScrollbarMouseHandlers {}
916 if layout.mode != EditorMode::Full {
917 return;
918 }
919
920 let view = self.view.clone();
921 let style = &self.style.theme.scrollbar;
922
923 let top = bounds.min_y();
924 let bottom = bounds.max_y();
925 let right = bounds.max_x();
926 let left = right - style.width;
927 let row_range = &layout.scrollbar_row_range;
928 let max_row = layout.max_row as f32 + (row_range.end - row_range.start);
929
930 let mut height = bounds.height();
931 let mut first_row_y_offset = 0.0;
932
933 // Impose a minimum height on the scrollbar thumb
934 let min_thumb_height =
935 style.min_height_factor * cx.font_cache.line_height(self.style.text.font_size);
936 let thumb_height = (row_range.end - row_range.start) * height / max_row;
937 if thumb_height < min_thumb_height {
938 first_row_y_offset = (min_thumb_height - thumb_height) / 2.0;
939 height -= min_thumb_height - thumb_height;
940 }
941
942 let y_for_row = |row: f32| -> f32 { top + first_row_y_offset + row * height / max_row };
943
944 let thumb_top = y_for_row(row_range.start) - first_row_y_offset;
945 let thumb_bottom = y_for_row(row_range.end) + first_row_y_offset;
946 let track_bounds = RectF::from_points(vec2f(left, top), vec2f(right, bottom));
947 let thumb_bounds = RectF::from_points(vec2f(left, thumb_top), vec2f(right, thumb_bottom));
948
949 if layout.show_scrollbars {
950 cx.scene.push_quad(Quad {
951 bounds: track_bounds,
952 border: style.track.border,
953 background: style.track.background_color,
954 ..Default::default()
955 });
956 cx.scene.push_quad(Quad {
957 bounds: thumb_bounds,
958 border: style.thumb.border,
959 background: style.thumb.background_color,
960 corner_radius: style.thumb.corner_radius,
961 });
962 }
963
964 cx.scene.push_cursor_region(CursorRegion {
965 bounds: track_bounds,
966 style: CursorStyle::Arrow,
967 });
968 cx.scene.push_mouse_region(
969 MouseRegion::new::<ScrollbarMouseHandlers>(view.id(), view.id(), track_bounds)
970 .on_move({
971 let view = view.clone();
972 move |_, cx| {
973 if let Some(view) = view.upgrade(cx.deref_mut()) {
974 view.update(cx.deref_mut(), |view, cx| {
975 view.scroll_manager.show_scrollbar(cx);
976 });
977 }
978 }
979 })
980 .on_down(MouseButton::Left, {
981 let view = view.clone();
982 let row_range = row_range.clone();
983 move |e, cx| {
984 let y = e.position.y();
985 if let Some(view) = view.upgrade(cx.deref_mut()) {
986 view.update(cx.deref_mut(), |view, cx| {
987 if y < thumb_top || thumb_bottom < y {
988 let center_row =
989 ((y - top) * max_row as f32 / height).round() as u32;
990 let top_row = center_row.saturating_sub(
991 (row_range.end - row_range.start) as u32 / 2,
992 );
993 let mut position = view.scroll_position(cx);
994 position.set_y(top_row as f32);
995 view.set_scroll_position(position, cx);
996 } else {
997 view.scroll_manager.show_scrollbar(cx);
998 }
999 });
1000 }
1001 }
1002 })
1003 .on_drag(MouseButton::Left, {
1004 let view = view.clone();
1005 move |e, cx| {
1006 let y = e.prev_mouse_position.y();
1007 let new_y = e.position.y();
1008 if thumb_top < y && y < thumb_bottom {
1009 if let Some(view) = view.upgrade(cx.deref_mut()) {
1010 view.update(cx.deref_mut(), |view, cx| {
1011 let mut position = view.scroll_position(cx);
1012 position.set_y(
1013 position.y() + (new_y - y) * (max_row as f32) / height,
1014 );
1015 if position.y() < 0.0 {
1016 position.set_y(0.);
1017 }
1018 view.set_scroll_position(position, cx);
1019 });
1020 }
1021 }
1022 }
1023 }),
1024 );
1025 }
1026
1027 #[allow(clippy::too_many_arguments)]
1028 fn paint_highlighted_range(
1029 &self,
1030 range: Range<DisplayPoint>,
1031 color: Color,
1032 corner_radius: f32,
1033 line_end_overshoot: f32,
1034 layout: &LayoutState,
1035 content_origin: Vector2F,
1036 scroll_top: f32,
1037 scroll_left: f32,
1038 bounds: RectF,
1039 cx: &mut PaintContext,
1040 ) {
1041 let start_row = layout.visible_display_row_range.start;
1042 let end_row = layout.visible_display_row_range.end;
1043 if range.start != range.end {
1044 let row_range = if range.end.column() == 0 {
1045 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
1046 } else {
1047 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
1048 };
1049
1050 let highlighted_range = HighlightedRange {
1051 color,
1052 line_height: layout.position_map.line_height,
1053 corner_radius,
1054 start_y: content_origin.y()
1055 + row_range.start as f32 * layout.position_map.line_height
1056 - scroll_top,
1057 lines: row_range
1058 .into_iter()
1059 .map(|row| {
1060 let line_layout =
1061 &layout.position_map.line_layouts[(row - start_row) as usize];
1062 HighlightedRangeLine {
1063 start_x: if row == range.start.row() {
1064 content_origin.x()
1065 + line_layout.x_for_index(range.start.column() as usize)
1066 - scroll_left
1067 } else {
1068 content_origin.x() - scroll_left
1069 },
1070 end_x: if row == range.end.row() {
1071 content_origin.x()
1072 + line_layout.x_for_index(range.end.column() as usize)
1073 - scroll_left
1074 } else {
1075 content_origin.x() + line_layout.width() + line_end_overshoot
1076 - scroll_left
1077 },
1078 }
1079 })
1080 .collect(),
1081 };
1082
1083 highlighted_range.paint(bounds, cx.scene);
1084 }
1085 }
1086
1087 fn paint_blocks(
1088 &mut self,
1089 bounds: RectF,
1090 visible_bounds: RectF,
1091 layout: &mut LayoutState,
1092 cx: &mut PaintContext,
1093 ) {
1094 let scroll_position = layout.position_map.snapshot.scroll_position();
1095 let scroll_left = scroll_position.x() * layout.position_map.em_width;
1096 let scroll_top = scroll_position.y() * layout.position_map.line_height;
1097
1098 for block in &mut layout.blocks {
1099 let mut origin = bounds.origin()
1100 + vec2f(
1101 0.,
1102 block.row as f32 * layout.position_map.line_height - scroll_top,
1103 );
1104 if !matches!(block.style, BlockStyle::Sticky) {
1105 origin += vec2f(-scroll_left, 0.);
1106 }
1107 block.element.paint(origin, visible_bounds, cx);
1108 }
1109 }
1110
1111 fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &LayoutContext) -> f32 {
1112 let digit_count = (snapshot.max_buffer_row() as f32).log10().floor() as usize + 1;
1113 let style = &self.style;
1114
1115 cx.text_layout_cache
1116 .layout_str(
1117 "1".repeat(digit_count).as_str(),
1118 style.text.font_size,
1119 &[(
1120 digit_count,
1121 RunStyle {
1122 font_id: style.text.font_id,
1123 color: Color::black(),
1124 underline: Default::default(),
1125 },
1126 )],
1127 )
1128 .width()
1129 }
1130
1131 fn get_fold_indicators(
1132 &self,
1133 display_rows: Range<u32>,
1134 snapshot: &EditorSnapshot,
1135 ) -> Vec<(u32, FoldStatus)> {
1136 display_rows
1137 .into_iter()
1138 .filter_map(|display_row| {
1139 snapshot
1140 .fold_for_line(display_row)
1141 .map(|fold_status| (display_row, fold_status))
1142 })
1143 .collect()
1144 }
1145
1146 //Folds contained in a hunk are ignored apart from shrinking visual size
1147 //If a fold contains any hunks then that fold line is marked as modified
1148 fn layout_git_gutters(
1149 &self,
1150 display_rows: Range<u32>,
1151 snapshot: &EditorSnapshot,
1152 ) -> Vec<DisplayDiffHunk> {
1153 let buffer_snapshot = &snapshot.buffer_snapshot;
1154
1155 let buffer_start_row = DisplayPoint::new(display_rows.start, 0)
1156 .to_point(snapshot)
1157 .row;
1158 let buffer_end_row = DisplayPoint::new(display_rows.end, 0)
1159 .to_point(snapshot)
1160 .row;
1161
1162 buffer_snapshot
1163 .git_diff_hunks_in_range(buffer_start_row..buffer_end_row, false)
1164 .map(|hunk| diff_hunk_to_display(hunk, snapshot))
1165 .dedup()
1166 .collect()
1167 }
1168
1169 fn layout_line_numbers(
1170 &self,
1171 rows: Range<u32>,
1172 active_rows: &BTreeMap<u32, bool>,
1173 snapshot: &EditorSnapshot,
1174 cx: &LayoutContext,
1175 ) -> Vec<Option<text_layout::Line>> {
1176 let style = &self.style;
1177 let include_line_numbers = snapshot.mode == EditorMode::Full;
1178 let mut line_number_layouts = Vec::with_capacity(rows.len());
1179 let mut line_number = String::new();
1180 for (ix, row) in snapshot
1181 .buffer_rows(rows.start)
1182 .take((rows.end - rows.start) as usize)
1183 .enumerate()
1184 {
1185 let display_row = rows.start + ix as u32;
1186 let color = if active_rows.contains_key(&display_row) {
1187 style.line_number_active
1188 } else {
1189 style.line_number
1190 };
1191 if let Some(buffer_row) = row {
1192 if include_line_numbers {
1193 line_number.clear();
1194 write!(&mut line_number, "{}", buffer_row + 1).unwrap();
1195 line_number_layouts.push(Some(cx.text_layout_cache.layout_str(
1196 &line_number,
1197 style.text.font_size,
1198 &[(
1199 line_number.len(),
1200 RunStyle {
1201 font_id: style.text.font_id,
1202 color,
1203 underline: Default::default(),
1204 },
1205 )],
1206 )));
1207 }
1208 } else {
1209 line_number_layouts.push(None);
1210 }
1211 }
1212
1213 line_number_layouts
1214 }
1215
1216 fn layout_lines(
1217 &mut self,
1218 rows: Range<u32>,
1219 snapshot: &EditorSnapshot,
1220 cx: &LayoutContext,
1221 ) -> Vec<text_layout::Line> {
1222 if rows.start >= rows.end {
1223 return Vec::new();
1224 }
1225
1226 // When the editor is empty and unfocused, then show the placeholder.
1227 if snapshot.is_empty() {
1228 let placeholder_style = self
1229 .style
1230 .placeholder_text
1231 .as_ref()
1232 .unwrap_or(&self.style.text);
1233 let placeholder_text = snapshot.placeholder_text();
1234 let placeholder_lines = placeholder_text
1235 .as_ref()
1236 .map_or("", AsRef::as_ref)
1237 .split('\n')
1238 .skip(rows.start as usize)
1239 .chain(iter::repeat(""))
1240 .take(rows.len());
1241 placeholder_lines
1242 .map(|line| {
1243 cx.text_layout_cache.layout_str(
1244 line,
1245 placeholder_style.font_size,
1246 &[(
1247 line.len(),
1248 RunStyle {
1249 font_id: placeholder_style.font_id,
1250 color: placeholder_style.color,
1251 underline: Default::default(),
1252 },
1253 )],
1254 )
1255 })
1256 .collect()
1257 } else {
1258 let style = &self.style;
1259 let chunks = snapshot.chunks(rows.clone(), true).map(|chunk| {
1260 let mut highlight_style = chunk
1261 .syntax_highlight_id
1262 .and_then(|id| id.style(&style.syntax));
1263
1264 if let Some(chunk_highlight) = chunk.highlight_style {
1265 if let Some(highlight_style) = highlight_style.as_mut() {
1266 highlight_style.highlight(chunk_highlight);
1267 } else {
1268 highlight_style = Some(chunk_highlight);
1269 }
1270 }
1271
1272 let mut diagnostic_highlight = HighlightStyle::default();
1273
1274 if chunk.is_unnecessary {
1275 diagnostic_highlight.fade_out = Some(style.unnecessary_code_fade);
1276 }
1277
1278 if let Some(severity) = chunk.diagnostic_severity {
1279 // Omit underlines for HINT/INFO diagnostics on 'unnecessary' code.
1280 if severity <= DiagnosticSeverity::WARNING || !chunk.is_unnecessary {
1281 let diagnostic_style = super::diagnostic_style(severity, true, style);
1282 diagnostic_highlight.underline = Some(Underline {
1283 color: Some(diagnostic_style.message.text.color),
1284 thickness: 1.0.into(),
1285 squiggly: true,
1286 });
1287 }
1288 }
1289
1290 if let Some(highlight_style) = highlight_style.as_mut() {
1291 highlight_style.highlight(diagnostic_highlight);
1292 } else {
1293 highlight_style = Some(diagnostic_highlight);
1294 }
1295
1296 (chunk.text, highlight_style)
1297 });
1298 layout_highlighted_chunks(
1299 chunks,
1300 &style.text,
1301 cx.text_layout_cache,
1302 cx.font_cache,
1303 MAX_LINE_LEN,
1304 rows.len() as usize,
1305 )
1306 }
1307 }
1308
1309 #[allow(clippy::too_many_arguments)]
1310 fn layout_blocks(
1311 &mut self,
1312 rows: Range<u32>,
1313 snapshot: &EditorSnapshot,
1314 editor_width: f32,
1315 scroll_width: f32,
1316 gutter_padding: f32,
1317 gutter_width: f32,
1318 em_width: f32,
1319 text_x: f32,
1320 line_height: f32,
1321 style: &EditorStyle,
1322 line_layouts: &[text_layout::Line],
1323 include_root: bool,
1324 cx: &mut LayoutContext,
1325 ) -> (f32, Vec<BlockLayout>) {
1326 let editor = if let Some(editor) = self.view.upgrade(cx) {
1327 editor
1328 } else {
1329 return Default::default();
1330 };
1331
1332 let tooltip_style = cx.global::<Settings>().theme.tooltip.clone();
1333 let scroll_x = snapshot.scroll_anchor.offset.x();
1334 let (fixed_blocks, non_fixed_blocks) = snapshot
1335 .blocks_in_range(rows.clone())
1336 .partition::<Vec<_>, _>(|(_, block)| match block {
1337 TransformBlock::ExcerptHeader { .. } => false,
1338 TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
1339 });
1340 let mut render_block = |block: &TransformBlock, width: f32| {
1341 let mut element = match block {
1342 TransformBlock::Custom(block) => {
1343 let align_to = block
1344 .position()
1345 .to_point(&snapshot.buffer_snapshot)
1346 .to_display_point(snapshot);
1347 let anchor_x = text_x
1348 + if rows.contains(&align_to.row()) {
1349 line_layouts[(align_to.row() - rows.start) as usize]
1350 .x_for_index(align_to.column() as usize)
1351 } else {
1352 layout_line(align_to.row(), snapshot, style, cx.text_layout_cache)
1353 .x_for_index(align_to.column() as usize)
1354 };
1355
1356 cx.render(&editor, |_, cx| {
1357 block.render(&mut BlockContext {
1358 cx,
1359 anchor_x,
1360 gutter_padding,
1361 line_height,
1362 scroll_x,
1363 gutter_width,
1364 em_width,
1365 })
1366 })
1367 }
1368 TransformBlock::ExcerptHeader {
1369 id,
1370 buffer,
1371 range,
1372 starts_new_buffer,
1373 ..
1374 } => {
1375 let id = *id;
1376 let jump_icon = project::File::from_dyn(buffer.file()).map(|file| {
1377 let jump_position = range
1378 .primary
1379 .as_ref()
1380 .map_or(range.context.start, |primary| primary.start);
1381 let jump_action = crate::Jump {
1382 path: ProjectPath {
1383 worktree_id: file.worktree_id(cx),
1384 path: file.path.clone(),
1385 },
1386 position: language::ToPoint::to_point(&jump_position, buffer),
1387 anchor: jump_position,
1388 };
1389
1390 enum JumpIcon {}
1391 cx.render(&editor, |_, cx| {
1392 MouseEventHandler::<JumpIcon>::new(id.into(), cx, |state, _| {
1393 let style = style.jump_icon.style_for(state, false);
1394 Svg::new("icons/arrow_up_right_8.svg")
1395 .with_color(style.color)
1396 .constrained()
1397 .with_width(style.icon_width)
1398 .aligned()
1399 .contained()
1400 .with_style(style.container)
1401 .constrained()
1402 .with_width(style.button_width)
1403 .with_height(style.button_width)
1404 .boxed()
1405 })
1406 .with_cursor_style(CursorStyle::PointingHand)
1407 .on_click(MouseButton::Left, move |_, cx| {
1408 cx.dispatch_action(jump_action.clone())
1409 })
1410 .with_tooltip::<JumpIcon, _>(
1411 id.into(),
1412 "Jump to Buffer".to_string(),
1413 Some(Box::new(crate::OpenExcerpts)),
1414 tooltip_style.clone(),
1415 cx,
1416 )
1417 .aligned()
1418 .flex_float()
1419 .boxed()
1420 })
1421 });
1422
1423 if *starts_new_buffer {
1424 let style = &self.style.diagnostic_path_header;
1425 let font_size =
1426 (style.text_scale_factor * self.style.text.font_size).round();
1427
1428 let path = buffer.resolve_file_path(cx, include_root);
1429 let mut filename = None;
1430 let mut parent_path = None;
1431 // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
1432 if let Some(path) = path {
1433 filename = path.file_name().map(|f| f.to_string_lossy().to_string());
1434 parent_path =
1435 path.parent().map(|p| p.to_string_lossy().to_string() + "/");
1436 }
1437
1438 Flex::row()
1439 .with_child(
1440 Label::new(
1441 filename.unwrap_or_else(|| "untitled".to_string()),
1442 style.filename.text.clone().with_font_size(font_size),
1443 )
1444 .contained()
1445 .with_style(style.filename.container)
1446 .aligned()
1447 .boxed(),
1448 )
1449 .with_children(parent_path.map(|path| {
1450 Label::new(path, style.path.text.clone().with_font_size(font_size))
1451 .contained()
1452 .with_style(style.path.container)
1453 .aligned()
1454 .boxed()
1455 }))
1456 .with_children(jump_icon)
1457 .contained()
1458 .with_style(style.container)
1459 .with_padding_left(gutter_padding)
1460 .with_padding_right(gutter_padding)
1461 .expanded()
1462 .named("path header block")
1463 } else {
1464 let text_style = self.style.text.clone();
1465 Flex::row()
1466 .with_child(Label::new("…", text_style).boxed())
1467 .with_children(jump_icon)
1468 .contained()
1469 .with_padding_left(gutter_padding)
1470 .with_padding_right(gutter_padding)
1471 .expanded()
1472 .named("collapsed context")
1473 }
1474 }
1475 };
1476
1477 element.layout(
1478 SizeConstraint {
1479 min: Vector2F::zero(),
1480 max: vec2f(width, block.height() as f32 * line_height),
1481 },
1482 cx,
1483 );
1484 element
1485 };
1486
1487 let mut fixed_block_max_width = 0f32;
1488 let mut blocks = Vec::new();
1489 for (row, block) in fixed_blocks {
1490 let element = render_block(block, f32::INFINITY);
1491 fixed_block_max_width = fixed_block_max_width.max(element.size().x() + em_width);
1492 blocks.push(BlockLayout {
1493 row,
1494 element,
1495 style: BlockStyle::Fixed,
1496 });
1497 }
1498 for (row, block) in non_fixed_blocks {
1499 let style = match block {
1500 TransformBlock::Custom(block) => block.style(),
1501 TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
1502 };
1503 let width = match style {
1504 BlockStyle::Sticky => editor_width,
1505 BlockStyle::Flex => editor_width
1506 .max(fixed_block_max_width)
1507 .max(gutter_width + scroll_width),
1508 BlockStyle::Fixed => unreachable!(),
1509 };
1510 let element = render_block(block, width);
1511 blocks.push(BlockLayout {
1512 row,
1513 element,
1514 style,
1515 });
1516 }
1517 (
1518 scroll_width.max(fixed_block_max_width - gutter_width),
1519 blocks,
1520 )
1521 }
1522}
1523
1524impl Element for EditorElement {
1525 type LayoutState = LayoutState;
1526 type PaintState = ();
1527
1528 fn layout(
1529 &mut self,
1530 constraint: SizeConstraint,
1531 cx: &mut LayoutContext,
1532 ) -> (Vector2F, Self::LayoutState) {
1533 let mut size = constraint.max;
1534 if size.x().is_infinite() {
1535 unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
1536 }
1537
1538 let snapshot = self.snapshot(cx.app);
1539 let style = self.style.clone();
1540 let line_height = style.text.line_height(cx.font_cache);
1541
1542 let gutter_padding;
1543 let gutter_width;
1544 let gutter_margin;
1545 if snapshot.mode == EditorMode::Full {
1546 gutter_padding = style.text.em_width(cx.font_cache) * style.gutter_padding_factor;
1547 gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
1548 gutter_margin = -style.text.descent(cx.font_cache);
1549 } else {
1550 gutter_padding = 0.0;
1551 gutter_width = 0.0;
1552 gutter_margin = 0.0;
1553 };
1554
1555 let text_width = size.x() - gutter_width;
1556 let em_width = style.text.em_width(cx.font_cache);
1557 let em_advance = style.text.em_advance(cx.font_cache);
1558 let overscroll = vec2f(em_width, 0.);
1559 let snapshot = self.update_view(cx.app, |view, cx| {
1560 view.set_visible_line_count(size.y() / line_height);
1561
1562 let editor_width = text_width - gutter_margin - overscroll.x() - em_width;
1563 let wrap_width = match view.soft_wrap_mode(cx) {
1564 SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
1565 SoftWrap::EditorWidth => editor_width,
1566 SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
1567 };
1568
1569 if view.set_wrap_width(Some(wrap_width), cx) {
1570 view.snapshot(cx)
1571 } else {
1572 snapshot
1573 }
1574 });
1575
1576 let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
1577 if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
1578 size.set_y(
1579 scroll_height
1580 .min(constraint.max_along(Axis::Vertical))
1581 .max(constraint.min_along(Axis::Vertical))
1582 .min(line_height * max_lines as f32),
1583 )
1584 } else if let EditorMode::SingleLine = snapshot.mode {
1585 size.set_y(
1586 line_height
1587 .min(constraint.max_along(Axis::Vertical))
1588 .max(constraint.min_along(Axis::Vertical)),
1589 )
1590 } else if size.y().is_infinite() {
1591 size.set_y(scroll_height);
1592 }
1593 let gutter_size = vec2f(gutter_width, size.y());
1594 let text_size = vec2f(text_width, size.y());
1595
1596 let (autoscroll_horizontally, mut snapshot) = self.update_view(cx.app, |view, cx| {
1597 let autoscroll_horizontally = view.autoscroll_vertically(size.y(), line_height, cx);
1598 let snapshot = view.snapshot(cx);
1599 (autoscroll_horizontally, snapshot)
1600 });
1601
1602 let scroll_position = snapshot.scroll_position();
1603 // The scroll position is a fractional point, the whole number of which represents
1604 // the top of the window in terms of display rows.
1605 let start_row = scroll_position.y() as u32;
1606 let height_in_lines = size.y() / line_height;
1607 let max_row = snapshot.max_point().row();
1608
1609 // Add 1 to ensure selections bleed off screen
1610 let end_row = 1 + cmp::min(
1611 (scroll_position.y() + height_in_lines).ceil() as u32,
1612 max_row,
1613 );
1614
1615 let start_anchor = if start_row == 0 {
1616 Anchor::min()
1617 } else {
1618 snapshot
1619 .buffer_snapshot
1620 .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
1621 };
1622 let end_anchor = if end_row > max_row {
1623 Anchor::max()
1624 } else {
1625 snapshot
1626 .buffer_snapshot
1627 .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
1628 };
1629
1630 let mut selections: Vec<(ReplicaId, Vec<SelectionLayout>)> = Vec::new();
1631 let mut active_rows = BTreeMap::new();
1632 let mut highlighted_rows = None;
1633 let mut highlighted_ranges = Vec::new();
1634 let mut show_scrollbars = false;
1635 let mut include_root = false;
1636 self.update_view(cx.app, |view, cx| {
1637 let display_map = view.display_map.update(cx, |map, cx| map.snapshot(cx));
1638
1639 highlighted_rows = view.highlighted_rows();
1640 let theme = cx.global::<Settings>().theme.as_ref();
1641 highlighted_ranges =
1642 view.background_highlights_in_range(start_anchor..end_anchor, &display_map, theme);
1643
1644 let mut remote_selections = HashMap::default();
1645 for (replica_id, line_mode, cursor_shape, selection) in display_map
1646 .buffer_snapshot
1647 .remote_selections_in_range(&(start_anchor..end_anchor))
1648 {
1649 // The local selections match the leader's selections.
1650 if Some(replica_id) == view.leader_replica_id {
1651 continue;
1652 }
1653 remote_selections
1654 .entry(replica_id)
1655 .or_insert(Vec::new())
1656 .push(SelectionLayout::new(
1657 selection,
1658 line_mode,
1659 cursor_shape,
1660 &display_map,
1661 ));
1662 }
1663 selections.extend(remote_selections);
1664
1665 if view.show_local_selections {
1666 let mut local_selections = view
1667 .selections
1668 .disjoint_in_range(start_anchor..end_anchor, cx);
1669 local_selections.extend(view.selections.pending(cx));
1670 for selection in &local_selections {
1671 let is_empty = selection.start == selection.end;
1672 let selection_start = snapshot.prev_line_boundary(selection.start).1;
1673 let selection_end = snapshot.next_line_boundary(selection.end).1;
1674 for row in cmp::max(selection_start.row(), start_row)
1675 ..=cmp::min(selection_end.row(), end_row)
1676 {
1677 let contains_non_empty_selection =
1678 active_rows.entry(row).or_insert(!is_empty);
1679 *contains_non_empty_selection |= !is_empty;
1680 }
1681 }
1682
1683 // Render the local selections in the leader's color when following.
1684 let local_replica_id = view
1685 .leader_replica_id
1686 .unwrap_or_else(|| view.replica_id(cx));
1687
1688 selections.push((
1689 local_replica_id,
1690 local_selections
1691 .into_iter()
1692 .map(|selection| {
1693 SelectionLayout::new(
1694 selection,
1695 view.selections.line_mode,
1696 view.cursor_shape,
1697 &display_map,
1698 )
1699 })
1700 .collect(),
1701 ));
1702 }
1703
1704 show_scrollbars = view.scroll_manager.scrollbars_visible();
1705 include_root = view
1706 .project
1707 .as_ref()
1708 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
1709 .unwrap_or_default()
1710 });
1711
1712 let line_number_layouts =
1713 self.layout_line_numbers(start_row..end_row, &active_rows, &snapshot, cx);
1714
1715 let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
1716
1717 let folds = self.get_fold_indicators(start_row..end_row, &snapshot);
1718
1719 let scrollbar_row_range = scroll_position.y()..(scroll_position.y() + height_in_lines);
1720
1721 let mut max_visible_line_width = 0.0;
1722 let line_layouts = self.layout_lines(start_row..end_row, &snapshot, cx);
1723 for line in &line_layouts {
1724 if line.width() > max_visible_line_width {
1725 max_visible_line_width = line.width();
1726 }
1727 }
1728
1729 let style = self.style.clone();
1730 let longest_line_width = layout_line(
1731 snapshot.longest_row(),
1732 &snapshot,
1733 &style,
1734 cx.text_layout_cache,
1735 )
1736 .width();
1737 let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
1738 let em_width = style.text.em_width(cx.font_cache);
1739 let (scroll_width, blocks) = self.layout_blocks(
1740 start_row..end_row,
1741 &snapshot,
1742 size.x(),
1743 scroll_width,
1744 gutter_padding,
1745 gutter_width,
1746 em_width,
1747 gutter_width + gutter_margin,
1748 line_height,
1749 &style,
1750 &line_layouts,
1751 include_root,
1752 cx,
1753 );
1754
1755 let scroll_max = vec2f(
1756 ((scroll_width - text_size.x()) / em_width).max(0.0),
1757 max_row as f32,
1758 );
1759
1760 self.update_view(cx.app, |view, cx| {
1761 let clamped = view.scroll_manager.clamp_scroll_left(scroll_max.x());
1762
1763 let autoscrolled = if autoscroll_horizontally {
1764 view.autoscroll_horizontally(
1765 start_row,
1766 text_size.x(),
1767 scroll_width,
1768 em_width,
1769 &line_layouts,
1770 cx,
1771 )
1772 } else {
1773 false
1774 };
1775
1776 if clamped || autoscrolled {
1777 snapshot = view.snapshot(cx);
1778 }
1779 });
1780
1781 let mut fold_indicators = Vec::with_capacity(folds.len());
1782 let mut context_menu = None;
1783 let mut code_actions_indicator = None;
1784 let mut hover = None;
1785 let mut mode = EditorMode::Full;
1786 cx.render(&self.view.upgrade(cx).unwrap(), |view, cx| {
1787 let newest_selection_head = view
1788 .selections
1789 .newest::<usize>(cx)
1790 .head()
1791 .to_display_point(&snapshot);
1792
1793 let style = view.style(cx);
1794 if (start_row..end_row).contains(&newest_selection_head.row()) {
1795 if view.context_menu_visible() {
1796 context_menu =
1797 view.render_context_menu(newest_selection_head, style.clone(), cx);
1798 }
1799
1800 code_actions_indicator = view
1801 .render_code_actions_indicator(&style, cx)
1802 .map(|indicator| (newest_selection_head.row(), indicator));
1803 }
1804
1805 view.render_fold_indicators(folds, &mut fold_indicators, &style, cx);
1806
1807 let visible_rows = start_row..start_row + line_layouts.len() as u32;
1808 hover = view.hover_state.render(&snapshot, &style, visible_rows, cx);
1809 mode = view.mode;
1810 });
1811
1812 if let Some((_, context_menu)) = context_menu.as_mut() {
1813 context_menu.layout(
1814 SizeConstraint {
1815 min: Vector2F::zero(),
1816 max: vec2f(
1817 cx.window_size.x() * 0.7,
1818 (12. * line_height).min((size.y() - line_height) / 2.),
1819 ),
1820 },
1821 cx,
1822 );
1823 }
1824
1825 if let Some((_, indicator)) = code_actions_indicator.as_mut() {
1826 indicator.layout(
1827 SizeConstraint::strict_along(
1828 Axis::Vertical,
1829 line_height * style.code_actions.vertical_scale,
1830 ),
1831 cx,
1832 );
1833 }
1834
1835 for (_, indicator) in fold_indicators.iter_mut() {
1836 indicator.layout(
1837 SizeConstraint::strict_along(
1838 Axis::Vertical,
1839 line_height * style.code_actions.vertical_scale,
1840 ),
1841 cx,
1842 );
1843 }
1844
1845 if let Some((_, hover_popovers)) = hover.as_mut() {
1846 for hover_popover in hover_popovers.iter_mut() {
1847 hover_popover.layout(
1848 SizeConstraint {
1849 min: Vector2F::zero(),
1850 max: vec2f(
1851 (120. * em_width) // Default size
1852 .min(size.x() / 2.) // Shrink to half of the editor width
1853 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
1854 (16. * line_height) // Default size
1855 .min(size.y() / 2.) // Shrink to half of the editor height
1856 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
1857 ),
1858 },
1859 cx,
1860 );
1861 }
1862 }
1863
1864 (
1865 size,
1866 LayoutState {
1867 mode,
1868 position_map: Arc::new(PositionMap {
1869 size,
1870 scroll_max,
1871 line_layouts,
1872 line_height,
1873 em_width,
1874 em_advance,
1875 snapshot,
1876 }),
1877 visible_display_row_range: start_row..end_row,
1878 gutter_size,
1879 gutter_padding,
1880 text_size,
1881 scrollbar_row_range,
1882 show_scrollbars,
1883 max_row,
1884 gutter_margin,
1885 active_rows,
1886 highlighted_rows,
1887 highlighted_ranges,
1888 line_number_layouts,
1889 display_hunks,
1890 blocks,
1891 selections,
1892 context_menu,
1893 code_actions_indicator,
1894 fold_indicators,
1895 hover_popovers: hover,
1896 },
1897 )
1898 }
1899
1900 fn paint(
1901 &mut self,
1902 bounds: RectF,
1903 visible_bounds: RectF,
1904 layout: &mut Self::LayoutState,
1905 cx: &mut PaintContext,
1906 ) -> Self::PaintState {
1907 let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
1908 cx.scene.push_layer(Some(visible_bounds));
1909
1910 let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
1911 let text_bounds = RectF::new(
1912 bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
1913 layout.text_size,
1914 );
1915
1916 Self::attach_mouse_handlers(
1917 &self.view,
1918 &layout.position_map,
1919 layout.hover_popovers.is_some(),
1920 visible_bounds,
1921 text_bounds,
1922 gutter_bounds,
1923 bounds,
1924 cx,
1925 );
1926
1927 self.paint_background(gutter_bounds, text_bounds, layout, cx);
1928 if layout.gutter_size.x() > 0. {
1929 self.paint_gutter(gutter_bounds, visible_bounds, layout, cx);
1930 }
1931 self.paint_text(text_bounds, visible_bounds, layout, cx);
1932
1933 cx.scene.push_layer(Some(bounds));
1934 if !layout.blocks.is_empty() {
1935 self.paint_blocks(bounds, visible_bounds, layout, cx);
1936 }
1937 self.paint_scrollbar(bounds, layout, cx);
1938 cx.scene.pop_layer();
1939
1940 cx.scene.pop_layer();
1941 }
1942
1943 fn rect_for_text_range(
1944 &self,
1945 range_utf16: Range<usize>,
1946 bounds: RectF,
1947 _: RectF,
1948 layout: &Self::LayoutState,
1949 _: &Self::PaintState,
1950 _: &gpui::MeasurementContext,
1951 ) -> Option<RectF> {
1952 let text_bounds = RectF::new(
1953 bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
1954 layout.text_size,
1955 );
1956 let content_origin = text_bounds.origin() + vec2f(layout.gutter_margin, 0.);
1957 let scroll_position = layout.position_map.snapshot.scroll_position();
1958 let start_row = scroll_position.y() as u32;
1959 let scroll_top = scroll_position.y() * layout.position_map.line_height;
1960 let scroll_left = scroll_position.x() * layout.position_map.em_width;
1961
1962 let range_start = OffsetUtf16(range_utf16.start)
1963 .to_display_point(&layout.position_map.snapshot.display_snapshot);
1964 if range_start.row() < start_row {
1965 return None;
1966 }
1967
1968 let line = layout
1969 .position_map
1970 .line_layouts
1971 .get((range_start.row() - start_row) as usize)?;
1972 let range_start_x = line.x_for_index(range_start.column() as usize);
1973 let range_start_y = range_start.row() as f32 * layout.position_map.line_height;
1974 Some(RectF::new(
1975 content_origin
1976 + vec2f(
1977 range_start_x,
1978 range_start_y + layout.position_map.line_height,
1979 )
1980 - vec2f(scroll_left, scroll_top),
1981 vec2f(
1982 layout.position_map.em_width,
1983 layout.position_map.line_height,
1984 ),
1985 ))
1986 }
1987
1988 fn debug(
1989 &self,
1990 bounds: RectF,
1991 _: &Self::LayoutState,
1992 _: &Self::PaintState,
1993 _: &gpui::DebugContext,
1994 ) -> json::Value {
1995 json!({
1996 "type": "BufferElement",
1997 "bounds": bounds.to_json()
1998 })
1999 }
2000}
2001
2002pub struct LayoutState {
2003 position_map: Arc<PositionMap>,
2004 gutter_size: Vector2F,
2005 gutter_padding: f32,
2006 gutter_margin: f32,
2007 text_size: Vector2F,
2008 mode: EditorMode,
2009 visible_display_row_range: Range<u32>,
2010 active_rows: BTreeMap<u32, bool>,
2011 highlighted_rows: Option<Range<u32>>,
2012 line_number_layouts: Vec<Option<text_layout::Line>>,
2013 display_hunks: Vec<DisplayDiffHunk>,
2014 blocks: Vec<BlockLayout>,
2015 highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
2016 selections: Vec<(ReplicaId, Vec<SelectionLayout>)>,
2017 scrollbar_row_range: Range<f32>,
2018 show_scrollbars: bool,
2019 max_row: u32,
2020 context_menu: Option<(DisplayPoint, ElementBox)>,
2021 code_actions_indicator: Option<(u32, ElementBox)>,
2022 hover_popovers: Option<(DisplayPoint, Vec<ElementBox>)>,
2023 fold_indicators: Vec<(u32, ElementBox)>,
2024}
2025
2026pub struct PositionMap {
2027 size: Vector2F,
2028 line_height: f32,
2029 scroll_max: Vector2F,
2030 em_width: f32,
2031 em_advance: f32,
2032 line_layouts: Vec<text_layout::Line>,
2033 snapshot: EditorSnapshot,
2034}
2035
2036impl PositionMap {
2037 /// Returns two display points:
2038 /// 1. The nearest *valid* position in the editor
2039 /// 2. An unclipped, potentially *invalid* position that maps directly to
2040 /// the given pixel position.
2041 fn point_for_position(
2042 &self,
2043 text_bounds: RectF,
2044 position: Vector2F,
2045 ) -> (DisplayPoint, DisplayPoint) {
2046 let scroll_position = self.snapshot.scroll_position();
2047 let position = position - text_bounds.origin();
2048 let y = position.y().max(0.0).min(self.size.y());
2049 let x = position.x() + (scroll_position.x() * self.em_width);
2050 let row = (y / self.line_height + scroll_position.y()) as u32;
2051 let (column, x_overshoot) = if let Some(line) = self
2052 .line_layouts
2053 .get(row as usize - scroll_position.y() as usize)
2054 {
2055 if let Some(ix) = line.index_for_x(x) {
2056 (ix as u32, 0.0)
2057 } else {
2058 (line.len() as u32, 0f32.max(x - line.width()))
2059 }
2060 } else {
2061 (0, x)
2062 };
2063
2064 let mut target_point = DisplayPoint::new(row, column);
2065 let point = self.snapshot.clip_point(target_point, Bias::Left);
2066 *target_point.column_mut() += (x_overshoot / self.em_advance) as u32;
2067
2068 (point, target_point)
2069 }
2070}
2071
2072struct BlockLayout {
2073 row: u32,
2074 element: ElementBox,
2075 style: BlockStyle,
2076}
2077
2078fn layout_line(
2079 row: u32,
2080 snapshot: &EditorSnapshot,
2081 style: &EditorStyle,
2082 layout_cache: &TextLayoutCache,
2083) -> text_layout::Line {
2084 let mut line = snapshot.line(row);
2085
2086 if line.len() > MAX_LINE_LEN {
2087 let mut len = MAX_LINE_LEN;
2088 while !line.is_char_boundary(len) {
2089 len -= 1;
2090 }
2091
2092 line.truncate(len);
2093 }
2094
2095 layout_cache.layout_str(
2096 &line,
2097 style.text.font_size,
2098 &[(
2099 snapshot.line_len(row) as usize,
2100 RunStyle {
2101 font_id: style.text.font_id,
2102 color: Color::black(),
2103 underline: Default::default(),
2104 },
2105 )],
2106 )
2107}
2108
2109#[derive(Debug)]
2110pub struct Cursor {
2111 origin: Vector2F,
2112 block_width: f32,
2113 line_height: f32,
2114 color: Color,
2115 shape: CursorShape,
2116 block_text: Option<Line>,
2117}
2118
2119impl Cursor {
2120 pub fn new(
2121 origin: Vector2F,
2122 block_width: f32,
2123 line_height: f32,
2124 color: Color,
2125 shape: CursorShape,
2126 block_text: Option<Line>,
2127 ) -> Cursor {
2128 Cursor {
2129 origin,
2130 block_width,
2131 line_height,
2132 color,
2133 shape,
2134 block_text,
2135 }
2136 }
2137
2138 pub fn bounding_rect(&self, origin: Vector2F) -> RectF {
2139 RectF::new(
2140 self.origin + origin,
2141 vec2f(self.block_width, self.line_height),
2142 )
2143 }
2144
2145 pub fn paint(&self, origin: Vector2F, cx: &mut PaintContext) {
2146 let bounds = match self.shape {
2147 CursorShape::Bar => RectF::new(self.origin + origin, vec2f(2.0, self.line_height)),
2148 CursorShape::Block | CursorShape::Hollow => RectF::new(
2149 self.origin + origin,
2150 vec2f(self.block_width, self.line_height),
2151 ),
2152 CursorShape::Underscore => RectF::new(
2153 self.origin + origin + Vector2F::new(0.0, self.line_height - 2.0),
2154 vec2f(self.block_width, 2.0),
2155 ),
2156 };
2157
2158 //Draw background or border quad
2159 if matches!(self.shape, CursorShape::Hollow) {
2160 cx.scene.push_quad(Quad {
2161 bounds,
2162 background: None,
2163 border: Border::all(1., self.color),
2164 corner_radius: 0.,
2165 });
2166 } else {
2167 cx.scene.push_quad(Quad {
2168 bounds,
2169 background: Some(self.color),
2170 border: Default::default(),
2171 corner_radius: 0.,
2172 });
2173 }
2174
2175 if let Some(block_text) = &self.block_text {
2176 block_text.paint(self.origin + origin, bounds, self.line_height, cx);
2177 }
2178 }
2179
2180 pub fn shape(&self) -> CursorShape {
2181 self.shape
2182 }
2183}
2184
2185#[derive(Debug)]
2186pub struct HighlightedRange {
2187 pub start_y: f32,
2188 pub line_height: f32,
2189 pub lines: Vec<HighlightedRangeLine>,
2190 pub color: Color,
2191 pub corner_radius: f32,
2192}
2193
2194#[derive(Debug)]
2195pub struct HighlightedRangeLine {
2196 pub start_x: f32,
2197 pub end_x: f32,
2198}
2199
2200impl HighlightedRange {
2201 pub fn paint(&self, bounds: RectF, scene: &mut SceneBuilder) {
2202 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
2203 self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
2204 self.paint_lines(
2205 self.start_y + self.line_height,
2206 &self.lines[1..],
2207 bounds,
2208 scene,
2209 );
2210 } else {
2211 self.paint_lines(self.start_y, &self.lines, bounds, scene);
2212 }
2213 }
2214
2215 fn paint_lines(
2216 &self,
2217 start_y: f32,
2218 lines: &[HighlightedRangeLine],
2219 bounds: RectF,
2220 scene: &mut SceneBuilder,
2221 ) {
2222 if lines.is_empty() {
2223 return;
2224 }
2225
2226 let mut path = PathBuilder::new();
2227 let first_line = lines.first().unwrap();
2228 let last_line = lines.last().unwrap();
2229
2230 let first_top_left = vec2f(first_line.start_x, start_y);
2231 let first_top_right = vec2f(first_line.end_x, start_y);
2232
2233 let curve_height = vec2f(0., self.corner_radius);
2234 let curve_width = |start_x: f32, end_x: f32| {
2235 let max = (end_x - start_x) / 2.;
2236 let width = if max < self.corner_radius {
2237 max
2238 } else {
2239 self.corner_radius
2240 };
2241
2242 vec2f(width, 0.)
2243 };
2244
2245 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
2246 path.reset(first_top_right - top_curve_width);
2247 path.curve_to(first_top_right + curve_height, first_top_right);
2248
2249 let mut iter = lines.iter().enumerate().peekable();
2250 while let Some((ix, line)) = iter.next() {
2251 let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
2252
2253 if let Some((_, next_line)) = iter.peek() {
2254 let next_top_right = vec2f(next_line.end_x, bottom_right.y());
2255
2256 match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
2257 Ordering::Equal => {
2258 path.line_to(bottom_right);
2259 }
2260 Ordering::Less => {
2261 let curve_width = curve_width(next_top_right.x(), bottom_right.x());
2262 path.line_to(bottom_right - curve_height);
2263 if self.corner_radius > 0. {
2264 path.curve_to(bottom_right - curve_width, bottom_right);
2265 }
2266 path.line_to(next_top_right + curve_width);
2267 if self.corner_radius > 0. {
2268 path.curve_to(next_top_right + curve_height, next_top_right);
2269 }
2270 }
2271 Ordering::Greater => {
2272 let curve_width = curve_width(bottom_right.x(), next_top_right.x());
2273 path.line_to(bottom_right - curve_height);
2274 if self.corner_radius > 0. {
2275 path.curve_to(bottom_right + curve_width, bottom_right);
2276 }
2277 path.line_to(next_top_right - curve_width);
2278 if self.corner_radius > 0. {
2279 path.curve_to(next_top_right + curve_height, next_top_right);
2280 }
2281 }
2282 }
2283 } else {
2284 let curve_width = curve_width(line.start_x, line.end_x);
2285 path.line_to(bottom_right - curve_height);
2286 if self.corner_radius > 0. {
2287 path.curve_to(bottom_right - curve_width, bottom_right);
2288 }
2289
2290 let bottom_left = vec2f(line.start_x, bottom_right.y());
2291 path.line_to(bottom_left + curve_width);
2292 if self.corner_radius > 0. {
2293 path.curve_to(bottom_left - curve_height, bottom_left);
2294 }
2295 }
2296 }
2297
2298 if first_line.start_x > last_line.start_x {
2299 let curve_width = curve_width(last_line.start_x, first_line.start_x);
2300 let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
2301 path.line_to(second_top_left + curve_height);
2302 if self.corner_radius > 0. {
2303 path.curve_to(second_top_left + curve_width, second_top_left);
2304 }
2305 let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
2306 path.line_to(first_bottom_left - curve_width);
2307 if self.corner_radius > 0. {
2308 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
2309 }
2310 }
2311
2312 path.line_to(first_top_left + curve_height);
2313 if self.corner_radius > 0. {
2314 path.curve_to(first_top_left + top_curve_width, first_top_left);
2315 }
2316 path.line_to(first_top_right - top_curve_width);
2317
2318 scene.push_path(path.build(self.color, Some(bounds)));
2319 }
2320}
2321
2322pub fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
2323 delta.powf(1.5) / 100.0
2324}
2325
2326fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
2327 delta.powf(1.2) / 300.0
2328}
2329
2330#[cfg(test)]
2331mod tests {
2332 use std::sync::Arc;
2333
2334 use super::*;
2335 use crate::{
2336 display_map::{BlockDisposition, BlockProperties},
2337 Editor, MultiBuffer,
2338 };
2339 use settings::Settings;
2340 use util::test::sample_text;
2341
2342 #[gpui::test]
2343 fn test_layout_line_numbers(cx: &mut gpui::MutableAppContext) {
2344 cx.set_global(Settings::test(cx));
2345 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
2346 let (window_id, editor) = cx.add_window(Default::default(), |cx| {
2347 Editor::new(EditorMode::Full, buffer, None, None, cx)
2348 });
2349 let element = EditorElement::new(editor.downgrade(), editor.read(cx).style(cx));
2350
2351 let layouts = editor.update(cx, |editor, cx| {
2352 let snapshot = editor.snapshot(cx);
2353 let mut presenter = cx.build_presenter(window_id, 30., Default::default());
2354 let layout_cx = presenter.build_layout_context(Vector2F::zero(), false, cx);
2355 element.layout_line_numbers(0..6, &Default::default(), &snapshot, &layout_cx)
2356 });
2357 assert_eq!(layouts.len(), 6);
2358 }
2359
2360 #[gpui::test]
2361 fn test_layout_with_placeholder_text_and_blocks(cx: &mut gpui::MutableAppContext) {
2362 cx.set_global(Settings::test(cx));
2363 let buffer = MultiBuffer::build_simple("", cx);
2364 let (window_id, editor) = cx.add_window(Default::default(), |cx| {
2365 Editor::new(EditorMode::Full, buffer, None, None, cx)
2366 });
2367
2368 editor.update(cx, |editor, cx| {
2369 editor.set_placeholder_text("hello", cx);
2370 editor.insert_blocks(
2371 [BlockProperties {
2372 style: BlockStyle::Fixed,
2373 disposition: BlockDisposition::Above,
2374 height: 3,
2375 position: Anchor::min(),
2376 render: Arc::new(|_| Empty::new().boxed()),
2377 }],
2378 cx,
2379 );
2380
2381 // Blur the editor so that it displays placeholder text.
2382 cx.blur();
2383 });
2384
2385 let mut element = EditorElement::new(editor.downgrade(), editor.read(cx).style(cx));
2386
2387 let mut scene = SceneBuilder::new(1.0);
2388 let mut presenter = cx.build_presenter(window_id, 30., Default::default());
2389 let mut layout_cx = presenter.build_layout_context(Vector2F::zero(), false, cx);
2390 let (size, mut state) = element.layout(
2391 SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
2392 &mut layout_cx,
2393 );
2394
2395 assert_eq!(state.position_map.line_layouts.len(), 4);
2396 assert_eq!(
2397 state
2398 .line_number_layouts
2399 .iter()
2400 .map(Option::is_some)
2401 .collect::<Vec<_>>(),
2402 &[false, false, false, true]
2403 );
2404
2405 // Don't panic.
2406 let bounds = RectF::new(Default::default(), size);
2407 let mut paint_cx = presenter.build_paint_context(&mut scene, bounds.size(), cx);
2408 element.paint(bounds, bounds, &mut state, &mut paint_cx);
2409 }
2410}