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