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