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