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