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