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