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