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