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