1use super::{
2 display_map::{BlockContext, ToDisplayPoint},
3 Anchor, DisplayPoint, Editor, EditorMode, EditorSnapshot, Input, Scroll, Select, SelectPhase,
4 SoftWrap, ToPoint, MAX_LINE_LEN,
5};
6use crate::{display_map::TransformBlock, EditorStyle};
7use clock::ReplicaId;
8use collections::{BTreeMap, HashMap};
9use gpui::{
10 color::Color,
11 elements::*,
12 fonts::{HighlightStyle, Underline},
13 geometry::{
14 rect::RectF,
15 vector::{vec2f, Vector2F},
16 PathBuilder,
17 },
18 json::{self, ToJson},
19 text_layout::{self, Line, RunStyle, TextLayoutCache},
20 AppContext, Axis, Border, Element, ElementBox, Event, EventContext, LayoutContext,
21 MutableAppContext, PaintContext, Quad, Scene, SizeConstraint, ViewContext, WeakViewHandle,
22};
23use json::json;
24use language::{Bias, DiagnosticSeverity};
25use smallvec::SmallVec;
26use std::{
27 cmp::{self, Ordering},
28 fmt::Write,
29 iter,
30 ops::Range,
31};
32
33pub struct EditorElement {
34 view: WeakViewHandle<Editor>,
35 style: EditorStyle,
36 cursor_shape: CursorShape,
37}
38
39impl EditorElement {
40 pub fn new(
41 view: WeakViewHandle<Editor>,
42 style: EditorStyle,
43 cursor_shape: CursorShape,
44 ) -> Self {
45 Self {
46 view,
47 style,
48 cursor_shape,
49 }
50 }
51
52 fn view<'a>(&self, cx: &'a AppContext) -> &'a Editor {
53 self.view.upgrade(cx).unwrap().read(cx)
54 }
55
56 fn update_view<F, T>(&self, cx: &mut MutableAppContext, f: F) -> T
57 where
58 F: FnOnce(&mut Editor, &mut ViewContext<Editor>) -> T,
59 {
60 self.view.upgrade(cx).unwrap().update(cx, f)
61 }
62
63 fn snapshot(&self, cx: &mut MutableAppContext) -> EditorSnapshot {
64 self.update_view(cx, |view, cx| view.snapshot(cx))
65 }
66
67 fn mouse_down(
68 &self,
69 position: Vector2F,
70 alt: bool,
71 shift: bool,
72 mut click_count: usize,
73 layout: &mut LayoutState,
74 paint: &mut PaintState,
75 cx: &mut EventContext,
76 ) -> bool {
77 if paint.gutter_bounds.contains_point(position) {
78 click_count = 3; // Simulate triple-click when clicking the gutter to select lines
79 } else if !paint.text_bounds.contains_point(position) {
80 return false;
81 }
82
83 let snapshot = self.snapshot(cx.app);
84 let (position, overshoot) = paint.point_for_position(&snapshot, layout, position);
85
86 if shift && alt {
87 cx.dispatch_action(Select(SelectPhase::BeginColumnar {
88 position,
89 overshoot,
90 }));
91 } else if shift {
92 cx.dispatch_action(Select(SelectPhase::Extend {
93 position,
94 click_count,
95 }));
96 } else {
97 cx.dispatch_action(Select(SelectPhase::Begin {
98 position,
99 add: alt,
100 click_count,
101 }));
102 }
103
104 true
105 }
106
107 fn mouse_up(&self, _position: Vector2F, cx: &mut EventContext) -> bool {
108 if self.view(cx.app.as_ref()).is_selecting() {
109 cx.dispatch_action(Select(SelectPhase::End));
110 true
111 } else {
112 false
113 }
114 }
115
116 fn mouse_dragged(
117 &self,
118 position: Vector2F,
119 layout: &mut LayoutState,
120 paint: &mut PaintState,
121 cx: &mut EventContext,
122 ) -> bool {
123 let view = self.view(cx.app.as_ref());
124
125 if view.is_selecting() {
126 let rect = paint.text_bounds;
127 let mut scroll_delta = Vector2F::zero();
128
129 let vertical_margin = layout.line_height.min(rect.height() / 3.0);
130 let top = rect.origin_y() + vertical_margin;
131 let bottom = rect.lower_left().y() - vertical_margin;
132 if position.y() < top {
133 scroll_delta.set_y(-scale_vertical_mouse_autoscroll_delta(top - position.y()))
134 }
135 if position.y() > bottom {
136 scroll_delta.set_y(scale_vertical_mouse_autoscroll_delta(position.y() - bottom))
137 }
138
139 let horizontal_margin = layout.line_height.min(rect.width() / 3.0);
140 let left = rect.origin_x() + horizontal_margin;
141 let right = rect.upper_right().x() - horizontal_margin;
142 if position.x() < left {
143 scroll_delta.set_x(-scale_horizontal_mouse_autoscroll_delta(
144 left - position.x(),
145 ))
146 }
147 if position.x() > right {
148 scroll_delta.set_x(scale_horizontal_mouse_autoscroll_delta(
149 position.x() - right,
150 ))
151 }
152
153 let snapshot = self.snapshot(cx.app);
154 let (position, overshoot) = paint.point_for_position(&snapshot, layout, position);
155
156 cx.dispatch_action(Select(SelectPhase::Update {
157 position,
158 overshoot,
159 scroll_position: (snapshot.scroll_position() + scroll_delta)
160 .clamp(Vector2F::zero(), layout.scroll_max),
161 }));
162 true
163 } else {
164 false
165 }
166 }
167
168 fn key_down(&self, input: Option<&str>, cx: &mut EventContext) -> bool {
169 let view = self.view.upgrade(cx.app).unwrap();
170
171 if view.is_focused(cx.app) {
172 if let Some(input) = input {
173 cx.dispatch_action(Input(input.to_string()));
174 true
175 } else {
176 false
177 }
178 } else {
179 false
180 }
181 }
182
183 fn scroll(
184 &self,
185 position: Vector2F,
186 mut delta: Vector2F,
187 precise: bool,
188 layout: &mut LayoutState,
189 paint: &mut PaintState,
190 cx: &mut EventContext,
191 ) -> bool {
192 if !paint.bounds.contains_point(position) {
193 return false;
194 }
195
196 let snapshot = self.snapshot(cx.app);
197 let max_glyph_width = layout.em_width;
198 if !precise {
199 delta *= vec2f(max_glyph_width, layout.line_height);
200 }
201
202 let scroll_position = snapshot.scroll_position();
203 let x = (scroll_position.x() * max_glyph_width - delta.x()) / max_glyph_width;
204 let y = (scroll_position.y() * layout.line_height - delta.y()) / layout.line_height;
205 let scroll_position = vec2f(x, y).clamp(Vector2F::zero(), layout.scroll_max);
206
207 cx.dispatch_action(Scroll(scroll_position));
208
209 true
210 }
211
212 fn paint_background(
213 &self,
214 gutter_bounds: RectF,
215 text_bounds: RectF,
216 layout: &LayoutState,
217 cx: &mut PaintContext,
218 ) {
219 let bounds = gutter_bounds.union_rect(text_bounds);
220 let scroll_top = layout.snapshot.scroll_position().y() * layout.line_height;
221 let editor = self.view(cx.app);
222 cx.scene.push_quad(Quad {
223 bounds: gutter_bounds,
224 background: Some(self.style.gutter_background),
225 border: Border::new(0., Color::transparent_black()),
226 corner_radius: 0.,
227 });
228 cx.scene.push_quad(Quad {
229 bounds: text_bounds,
230 background: Some(self.style.background),
231 border: Border::new(0., Color::transparent_black()),
232 corner_radius: 0.,
233 });
234
235 if let EditorMode::Full = editor.mode {
236 let mut active_rows = layout.active_rows.iter().peekable();
237 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
238 let mut end_row = *start_row;
239 while active_rows.peek().map_or(false, |r| {
240 *r.0 == end_row + 1 && r.1 == contains_non_empty_selection
241 }) {
242 active_rows.next().unwrap();
243 end_row += 1;
244 }
245
246 if !contains_non_empty_selection {
247 let origin = vec2f(
248 bounds.origin_x(),
249 bounds.origin_y() + (layout.line_height * *start_row as f32) - scroll_top,
250 );
251 let size = vec2f(
252 bounds.width(),
253 layout.line_height * (end_row - start_row + 1) as f32,
254 );
255 cx.scene.push_quad(Quad {
256 bounds: RectF::new(origin, size),
257 background: Some(self.style.active_line_background),
258 border: Border::default(),
259 corner_radius: 0.,
260 });
261 }
262 }
263
264 if let Some(highlighted_rows) = &layout.highlighted_rows {
265 let origin = vec2f(
266 bounds.origin_x(),
267 bounds.origin_y() + (layout.line_height * highlighted_rows.start as f32)
268 - scroll_top,
269 );
270 let size = vec2f(
271 bounds.width(),
272 layout.line_height * highlighted_rows.len() as f32,
273 );
274 cx.scene.push_quad(Quad {
275 bounds: RectF::new(origin, size),
276 background: Some(self.style.highlighted_line_background),
277 border: Border::default(),
278 corner_radius: 0.,
279 });
280 }
281 }
282 }
283
284 fn paint_gutter(
285 &mut self,
286 bounds: RectF,
287 visible_bounds: RectF,
288 layout: &mut LayoutState,
289 cx: &mut PaintContext,
290 ) {
291 let scroll_top = layout.snapshot.scroll_position().y() * layout.line_height;
292 for (ix, line) in layout.line_number_layouts.iter().enumerate() {
293 if let Some(line) = line {
294 let line_origin = bounds.origin()
295 + vec2f(
296 bounds.width() - line.width() - layout.gutter_padding,
297 ix as f32 * layout.line_height - (scroll_top % layout.line_height),
298 );
299 line.paint(line_origin, visible_bounds, layout.line_height, cx);
300 }
301 }
302
303 if let Some((row, indicator)) = layout.code_actions_indicator.as_mut() {
304 let mut x = bounds.width() - layout.gutter_padding;
305 let mut y = *row as f32 * layout.line_height - scroll_top;
306 x += ((layout.gutter_padding + layout.gutter_margin) - indicator.size().x()) / 2.;
307 y += (layout.line_height - indicator.size().y()) / 2.;
308 indicator.paint(bounds.origin() + vec2f(x, y), visible_bounds, cx);
309 }
310 }
311
312 fn paint_text(
313 &mut self,
314 bounds: RectF,
315 visible_bounds: RectF,
316 layout: &mut LayoutState,
317 cx: &mut PaintContext,
318 ) {
319 let view = self.view(cx.app);
320 let style = &self.style;
321 let local_replica_id = view.replica_id(cx);
322 let scroll_position = layout.snapshot.scroll_position();
323 let start_row = scroll_position.y() as u32;
324 let scroll_top = scroll_position.y() * layout.line_height;
325 let end_row = ((scroll_top + bounds.height()) / layout.line_height).ceil() as u32 + 1; // Add 1 to ensure selections bleed off screen
326 let max_glyph_width = layout.em_width;
327 let scroll_left = scroll_position.x() * max_glyph_width;
328 let content_origin = bounds.origin() + vec2f(layout.gutter_margin, 0.);
329
330 cx.scene.push_layer(Some(bounds));
331
332 for (range, color) in &layout.highlighted_ranges {
333 self.paint_highlighted_range(
334 range.clone(),
335 start_row,
336 end_row,
337 *color,
338 0.,
339 0.15 * layout.line_height,
340 layout,
341 content_origin,
342 scroll_top,
343 scroll_left,
344 bounds,
345 cx,
346 );
347 }
348
349 let mut cursors = SmallVec::<[Cursor; 32]>::new();
350 for (replica_id, selections) in &layout.selections {
351 let selection_style = style.replica_selection_style(*replica_id);
352 let corner_radius = 0.15 * layout.line_height;
353
354 for selection in selections {
355 self.paint_highlighted_range(
356 selection.start..selection.end,
357 start_row,
358 end_row,
359 selection_style.selection,
360 corner_radius,
361 corner_radius * 2.,
362 layout,
363 content_origin,
364 scroll_top,
365 scroll_left,
366 bounds,
367 cx,
368 );
369
370 if view.show_local_cursors() || *replica_id != local_replica_id {
371 let cursor_position = selection.head();
372 if (start_row..end_row).contains(&cursor_position.row()) {
373 let cursor_row_layout =
374 &layout.line_layouts[(cursor_position.row() - start_row) as usize];
375 let cursor_column = cursor_position.column() as usize;
376
377 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
378 let mut block_width =
379 cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
380 if block_width == 0.0 {
381 block_width = layout.em_width;
382 }
383
384 let block_text =
385 if matches!(self.cursor_shape, CursorShape::Block) {
386 layout.snapshot.chars_at(cursor_position).next().and_then(
387 |character| {
388 let font_id =
389 cursor_row_layout.font_for_index(cursor_column)?;
390 let text = character.to_string();
391
392 Some(cx.text_layout_cache.layout_str(
393 &text,
394 cursor_row_layout.font_size(),
395 &[(
396 text.len(),
397 RunStyle {
398 font_id,
399 color: style.background,
400 underline: Default::default(),
401 },
402 )],
403 ))
404 },
405 )
406 } else {
407 None
408 };
409
410 let x = cursor_character_x - scroll_left;
411 let y = cursor_position.row() as f32 * layout.line_height - scroll_top;
412 cursors.push(Cursor {
413 color: selection_style.cursor,
414 block_width,
415 origin: content_origin + vec2f(x, y),
416 line_height: layout.line_height,
417 shape: self.cursor_shape,
418 block_text,
419 });
420 }
421 }
422 }
423 }
424
425 if let Some(visible_text_bounds) = bounds.intersection(visible_bounds) {
426 // Draw glyphs
427 for (ix, line) in layout.line_layouts.iter().enumerate() {
428 let row = start_row + ix as u32;
429 line.paint(
430 content_origin
431 + vec2f(-scroll_left, row as f32 * layout.line_height - scroll_top),
432 visible_text_bounds,
433 layout.line_height,
434 cx,
435 );
436 }
437 }
438
439 cx.scene.push_layer(Some(bounds));
440 for cursor in cursors {
441 cursor.paint(cx);
442 }
443 cx.scene.pop_layer();
444
445 if let Some((position, context_menu)) = layout.context_menu.as_mut() {
446 cx.scene.push_stacking_context(None);
447
448 let cursor_row_layout = &layout.line_layouts[(position.row() - start_row) as usize];
449 let x = cursor_row_layout.x_for_index(position.column() as usize) - scroll_left;
450 let y = (position.row() + 1) as f32 * layout.line_height - scroll_top;
451 let mut list_origin = content_origin + vec2f(x, y);
452 let list_height = context_menu.size().y();
453
454 if list_origin.y() + list_height > bounds.lower_left().y() {
455 list_origin.set_y(list_origin.y() - layout.line_height - list_height);
456 }
457
458 context_menu.paint(
459 list_origin,
460 RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
461 cx,
462 );
463
464 cx.scene.pop_stacking_context();
465 }
466
467 cx.scene.pop_layer();
468 }
469
470 fn paint_highlighted_range(
471 &self,
472 range: Range<DisplayPoint>,
473 start_row: u32,
474 end_row: u32,
475 color: Color,
476 corner_radius: f32,
477 line_end_overshoot: f32,
478 layout: &LayoutState,
479 content_origin: Vector2F,
480 scroll_top: f32,
481 scroll_left: f32,
482 bounds: RectF,
483 cx: &mut PaintContext,
484 ) {
485 if range.start != range.end {
486 let row_range = if range.end.column() == 0 {
487 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
488 } else {
489 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
490 };
491
492 let highlighted_range = HighlightedRange {
493 color,
494 line_height: layout.line_height,
495 corner_radius,
496 start_y: content_origin.y() + row_range.start as f32 * layout.line_height
497 - scroll_top,
498 lines: row_range
499 .into_iter()
500 .map(|row| {
501 let line_layout = &layout.line_layouts[(row - start_row) as usize];
502 HighlightedRangeLine {
503 start_x: if row == range.start.row() {
504 content_origin.x()
505 + line_layout.x_for_index(range.start.column() as usize)
506 - scroll_left
507 } else {
508 content_origin.x() - scroll_left
509 },
510 end_x: if row == range.end.row() {
511 content_origin.x()
512 + line_layout.x_for_index(range.end.column() as usize)
513 - scroll_left
514 } else {
515 content_origin.x() + line_layout.width() + line_end_overshoot
516 - scroll_left
517 },
518 }
519 })
520 .collect(),
521 };
522
523 highlighted_range.paint(bounds, cx.scene);
524 }
525 }
526
527 fn paint_blocks(
528 &mut self,
529 bounds: RectF,
530 visible_bounds: RectF,
531 layout: &mut LayoutState,
532 cx: &mut PaintContext,
533 ) {
534 let scroll_position = layout.snapshot.scroll_position();
535 let scroll_left = scroll_position.x() * layout.em_width;
536 let scroll_top = scroll_position.y() * layout.line_height;
537
538 for (row, element) in &mut layout.blocks {
539 let origin = bounds.origin()
540 + vec2f(-scroll_left, *row as f32 * layout.line_height - scroll_top);
541 element.paint(origin, visible_bounds, cx);
542 }
543 }
544
545 fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &LayoutContext) -> f32 {
546 let digit_count = (snapshot.max_buffer_row() as f32).log10().floor() as usize + 1;
547 let style = &self.style;
548
549 cx.text_layout_cache
550 .layout_str(
551 "1".repeat(digit_count).as_str(),
552 style.text.font_size,
553 &[(
554 digit_count,
555 RunStyle {
556 font_id: style.text.font_id,
557 color: Color::black(),
558 underline: Default::default(),
559 },
560 )],
561 )
562 .width()
563 }
564
565 fn layout_line_numbers(
566 &self,
567 rows: Range<u32>,
568 active_rows: &BTreeMap<u32, bool>,
569 snapshot: &EditorSnapshot,
570 cx: &LayoutContext,
571 ) -> Vec<Option<text_layout::Line>> {
572 let style = &self.style;
573 let include_line_numbers = snapshot.mode == EditorMode::Full;
574 let mut line_number_layouts = Vec::with_capacity(rows.len());
575 let mut line_number = String::new();
576 for (ix, row) in snapshot
577 .buffer_rows(rows.start)
578 .take((rows.end - rows.start) as usize)
579 .enumerate()
580 {
581 let display_row = rows.start + ix as u32;
582 let color = if active_rows.contains_key(&display_row) {
583 style.line_number_active
584 } else {
585 style.line_number
586 };
587 if let Some(buffer_row) = row {
588 if include_line_numbers {
589 line_number.clear();
590 write!(&mut line_number, "{}", buffer_row + 1).unwrap();
591 line_number_layouts.push(Some(cx.text_layout_cache.layout_str(
592 &line_number,
593 style.text.font_size,
594 &[(
595 line_number.len(),
596 RunStyle {
597 font_id: style.text.font_id,
598 color,
599 underline: Default::default(),
600 },
601 )],
602 )));
603 }
604 } else {
605 line_number_layouts.push(None);
606 }
607 }
608
609 line_number_layouts
610 }
611
612 fn layout_lines(
613 &mut self,
614 rows: Range<u32>,
615 snapshot: &EditorSnapshot,
616 cx: &LayoutContext,
617 ) -> Vec<text_layout::Line> {
618 if rows.start >= rows.end {
619 return Vec::new();
620 }
621
622 // When the editor is empty and unfocused, then show the placeholder.
623 if snapshot.is_empty() && !snapshot.is_focused() {
624 let placeholder_style = self
625 .style
626 .placeholder_text
627 .as_ref()
628 .unwrap_or_else(|| &self.style.text);
629 let placeholder_text = snapshot.placeholder_text();
630 let placeholder_lines = placeholder_text
631 .as_ref()
632 .map_or("", AsRef::as_ref)
633 .split('\n')
634 .skip(rows.start as usize)
635 .chain(iter::repeat(""))
636 .take(rows.len());
637 return placeholder_lines
638 .map(|line| {
639 cx.text_layout_cache.layout_str(
640 line,
641 placeholder_style.font_size,
642 &[(
643 line.len(),
644 RunStyle {
645 font_id: placeholder_style.font_id,
646 color: placeholder_style.color,
647 underline: Default::default(),
648 },
649 )],
650 )
651 })
652 .collect();
653 } else {
654 let style = &self.style;
655 let chunks = snapshot.chunks(rows.clone(), true).map(|chunk| {
656 let mut highlight_style = chunk
657 .syntax_highlight_id
658 .and_then(|id| id.style(&style.syntax));
659
660 if let Some(chunk_highlight) = chunk.highlight_style {
661 if let Some(highlight_style) = highlight_style.as_mut() {
662 highlight_style.highlight(chunk_highlight);
663 } else {
664 highlight_style = Some(chunk_highlight);
665 }
666 }
667
668 let mut diagnostic_highlight = HighlightStyle::default();
669
670 if chunk.is_unnecessary {
671 diagnostic_highlight.fade_out = Some(style.unnecessary_code_fade);
672 }
673
674 if let Some(severity) = chunk.diagnostic_severity {
675 // Omit underlines for HINT/INFO diagnostics on 'unnecessary' code.
676 if severity <= DiagnosticSeverity::WARNING || !chunk.is_unnecessary {
677 let diagnostic_style = super::diagnostic_style(severity, true, style);
678 diagnostic_highlight.underline = Some(Underline {
679 color: Some(diagnostic_style.message.text.color),
680 thickness: 1.0.into(),
681 squiggly: true,
682 });
683 }
684 }
685
686 if let Some(highlight_style) = highlight_style.as_mut() {
687 highlight_style.highlight(diagnostic_highlight);
688 } else {
689 highlight_style = Some(diagnostic_highlight);
690 }
691
692 (chunk.text, highlight_style)
693 });
694 layout_highlighted_chunks(
695 chunks,
696 &style.text,
697 &cx.text_layout_cache,
698 &cx.font_cache,
699 MAX_LINE_LEN,
700 rows.len() as usize,
701 )
702 }
703 }
704
705 fn layout_blocks(
706 &mut self,
707 rows: Range<u32>,
708 snapshot: &EditorSnapshot,
709 width: f32,
710 gutter_padding: f32,
711 gutter_width: f32,
712 em_width: f32,
713 text_x: f32,
714 line_height: f32,
715 style: &EditorStyle,
716 line_layouts: &[text_layout::Line],
717 cx: &mut LayoutContext,
718 ) -> Vec<(u32, ElementBox)> {
719 let scroll_x = snapshot.scroll_position.x();
720 snapshot
721 .blocks_in_range(rows.clone())
722 .map(|(block_row, block)| {
723 let mut element = match block {
724 TransformBlock::Custom(block) => {
725 let align_to = block
726 .position()
727 .to_point(&snapshot.buffer_snapshot)
728 .to_display_point(snapshot);
729 let anchor_x = text_x
730 + if rows.contains(&align_to.row()) {
731 line_layouts[(align_to.row() - rows.start) as usize]
732 .x_for_index(align_to.column() as usize)
733 } else {
734 layout_line(align_to.row(), snapshot, style, cx.text_layout_cache)
735 .x_for_index(align_to.column() as usize)
736 };
737
738 block.render(&BlockContext {
739 cx,
740 anchor_x,
741 gutter_padding,
742 line_height,
743 scroll_x,
744 gutter_width,
745 em_width,
746 })
747 }
748 TransformBlock::ExcerptHeader {
749 buffer,
750 starts_new_buffer,
751 ..
752 } => {
753 if *starts_new_buffer {
754 let style = &self.style.diagnostic_path_header;
755 let font_size =
756 (style.text_scale_factor * self.style.text.font_size).round();
757
758 let mut filename = None;
759 let mut parent_path = None;
760 if let Some(path) = buffer.path() {
761 filename =
762 path.file_name().map(|f| f.to_string_lossy().to_string());
763 parent_path =
764 path.parent().map(|p| p.to_string_lossy().to_string() + "/");
765 }
766
767 Flex::row()
768 .with_child(
769 Label::new(
770 filename.unwrap_or_else(|| "untitled".to_string()),
771 style.filename.text.clone().with_font_size(font_size),
772 )
773 .contained()
774 .with_style(style.filename.container)
775 .boxed(),
776 )
777 .with_children(parent_path.map(|path| {
778 Label::new(
779 path,
780 style.path.text.clone().with_font_size(font_size),
781 )
782 .contained()
783 .with_style(style.path.container)
784 .boxed()
785 }))
786 .aligned()
787 .left()
788 .contained()
789 .with_style(style.container)
790 .with_padding_left(gutter_padding + scroll_x * em_width)
791 .expanded()
792 .named("path header block")
793 } else {
794 let text_style = self.style.text.clone();
795 Label::new("…".to_string(), text_style)
796 .contained()
797 .with_padding_left(gutter_padding + scroll_x * em_width)
798 .named("collapsed context")
799 }
800 }
801 };
802
803 element.layout(
804 SizeConstraint {
805 min: Vector2F::zero(),
806 max: vec2f(width, block.height() as f32 * line_height),
807 },
808 cx,
809 );
810 (block_row, element)
811 })
812 .collect()
813 }
814}
815
816impl Element for EditorElement {
817 type LayoutState = LayoutState;
818 type PaintState = PaintState;
819
820 fn layout(
821 &mut self,
822 constraint: SizeConstraint,
823 cx: &mut LayoutContext,
824 ) -> (Vector2F, Self::LayoutState) {
825 let mut size = constraint.max;
826 if size.x().is_infinite() {
827 unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
828 }
829
830 let snapshot = self.snapshot(cx.app);
831 let style = self.style.clone();
832 let line_height = style.text.line_height(cx.font_cache);
833
834 let gutter_padding;
835 let gutter_width;
836 let gutter_margin;
837 if snapshot.mode == EditorMode::Full {
838 gutter_padding = style.text.em_width(cx.font_cache) * style.gutter_padding_factor;
839 gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
840 gutter_margin = -style.text.descent(cx.font_cache);
841 } else {
842 gutter_padding = 0.0;
843 gutter_width = 0.0;
844 gutter_margin = 0.0;
845 };
846
847 let text_width = size.x() - gutter_width;
848 let em_width = style.text.em_width(cx.font_cache);
849 let em_advance = style.text.em_advance(cx.font_cache);
850 let overscroll = vec2f(em_width, 0.);
851 let snapshot = self.update_view(cx.app, |view, cx| {
852 let wrap_width = match view.soft_wrap_mode(cx) {
853 SoftWrap::None => None,
854 SoftWrap::EditorWidth => {
855 Some(text_width - gutter_margin - overscroll.x() - em_width)
856 }
857 SoftWrap::Column(column) => Some(column as f32 * em_advance),
858 };
859
860 if view.set_wrap_width(wrap_width, cx) {
861 view.snapshot(cx)
862 } else {
863 snapshot
864 }
865 });
866
867 let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
868 if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
869 size.set_y(
870 scroll_height
871 .min(constraint.max_along(Axis::Vertical))
872 .max(constraint.min_along(Axis::Vertical))
873 .min(line_height * max_lines as f32),
874 )
875 } else if size.y().is_infinite() {
876 size.set_y(scroll_height);
877 }
878 let gutter_size = vec2f(gutter_width, size.y());
879 let text_size = vec2f(text_width, size.y());
880
881 let (autoscroll_horizontally, mut snapshot) = self.update_view(cx.app, |view, cx| {
882 let autoscroll_horizontally = view.autoscroll_vertically(size.y(), line_height, cx);
883 let snapshot = view.snapshot(cx);
884 (autoscroll_horizontally, snapshot)
885 });
886
887 let scroll_position = snapshot.scroll_position();
888 let start_row = scroll_position.y() as u32;
889 let scroll_top = scroll_position.y() * line_height;
890
891 // Add 1 to ensure selections bleed off screen
892 let end_row = 1 + cmp::min(
893 ((scroll_top + size.y()) / line_height).ceil() as u32,
894 snapshot.max_point().row(),
895 );
896
897 let start_anchor = if start_row == 0 {
898 Anchor::min()
899 } else {
900 snapshot
901 .buffer_snapshot
902 .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
903 };
904 let end_anchor = if end_row > snapshot.max_point().row() {
905 Anchor::max()
906 } else {
907 snapshot
908 .buffer_snapshot
909 .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
910 };
911
912 let mut selections = Vec::new();
913 let mut active_rows = BTreeMap::new();
914 let mut highlighted_rows = None;
915 let mut highlighted_ranges = Vec::new();
916 self.update_view(cx.app, |view, cx| {
917 let display_map = view.display_map.update(cx, |map, cx| map.snapshot(cx));
918
919 highlighted_rows = view.highlighted_rows();
920 highlighted_ranges = view.background_highlights_in_range(
921 start_anchor.clone()..end_anchor.clone(),
922 &display_map,
923 );
924
925 let mut remote_selections = HashMap::default();
926 for (replica_id, selection) in display_map
927 .buffer_snapshot
928 .remote_selections_in_range(&(start_anchor.clone()..end_anchor.clone()))
929 {
930 // The local selections match the leader's selections.
931 if Some(replica_id) == view.leader_replica_id {
932 continue;
933 }
934
935 remote_selections
936 .entry(replica_id)
937 .or_insert(Vec::new())
938 .push(crate::Selection {
939 id: selection.id,
940 goal: selection.goal,
941 reversed: selection.reversed,
942 start: selection.start.to_display_point(&display_map),
943 end: selection.end.to_display_point(&display_map),
944 });
945 }
946 selections.extend(remote_selections);
947
948 if view.show_local_selections {
949 let local_selections =
950 view.local_selections_in_range(start_anchor..end_anchor, &display_map);
951 for selection in &local_selections {
952 let is_empty = selection.start == selection.end;
953 let selection_start = snapshot.prev_line_boundary(selection.start).1;
954 let selection_end = snapshot.next_line_boundary(selection.end).1;
955 for row in cmp::max(selection_start.row(), start_row)
956 ..=cmp::min(selection_end.row(), end_row)
957 {
958 let contains_non_empty_selection =
959 active_rows.entry(row).or_insert(!is_empty);
960 *contains_non_empty_selection |= !is_empty;
961 }
962 }
963
964 // Render the local selections in the leader's color when following.
965 let local_replica_id = view.leader_replica_id.unwrap_or(view.replica_id(cx));
966
967 selections.push((
968 local_replica_id,
969 local_selections
970 .into_iter()
971 .map(|selection| crate::Selection {
972 id: selection.id,
973 goal: selection.goal,
974 reversed: selection.reversed,
975 start: selection.start.to_display_point(&display_map),
976 end: selection.end.to_display_point(&display_map),
977 })
978 .collect(),
979 ));
980 }
981 });
982
983 let line_number_layouts =
984 self.layout_line_numbers(start_row..end_row, &active_rows, &snapshot, cx);
985
986 let mut max_visible_line_width = 0.0;
987 let line_layouts = self.layout_lines(start_row..end_row, &snapshot, cx);
988 for line in &line_layouts {
989 if line.width() > max_visible_line_width {
990 max_visible_line_width = line.width();
991 }
992 }
993
994 let style = self.style.clone();
995 let longest_line_width = layout_line(
996 snapshot.longest_row(),
997 &snapshot,
998 &style,
999 cx.text_layout_cache,
1000 )
1001 .width();
1002 let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
1003 let em_width = style.text.em_width(cx.font_cache);
1004 let max_row = snapshot.max_point().row();
1005 let scroll_max = vec2f(
1006 ((scroll_width - text_size.x()) / em_width).max(0.0),
1007 max_row.saturating_sub(1) as f32,
1008 );
1009
1010 let mut context_menu = None;
1011 let mut code_actions_indicator = None;
1012 self.update_view(cx.app, |view, cx| {
1013 let clamped = view.clamp_scroll_left(scroll_max.x());
1014 let autoscrolled;
1015 if autoscroll_horizontally {
1016 autoscrolled = view.autoscroll_horizontally(
1017 start_row,
1018 text_size.x(),
1019 scroll_width,
1020 em_width,
1021 &line_layouts,
1022 cx,
1023 );
1024 } else {
1025 autoscrolled = false;
1026 }
1027
1028 if clamped || autoscrolled {
1029 snapshot = view.snapshot(cx);
1030 }
1031
1032 let newest_selection_head = view
1033 .newest_selection_with_snapshot::<usize>(&snapshot.buffer_snapshot)
1034 .head()
1035 .to_display_point(&snapshot);
1036
1037 if (start_row..end_row).contains(&newest_selection_head.row()) {
1038 let style = view.style(cx);
1039 if view.context_menu_visible() {
1040 context_menu =
1041 view.render_context_menu(newest_selection_head, style.clone(), cx);
1042 }
1043
1044 code_actions_indicator = view
1045 .render_code_actions_indicator(&style, cx)
1046 .map(|indicator| (newest_selection_head.row(), indicator));
1047 }
1048 });
1049
1050 if let Some((_, context_menu)) = context_menu.as_mut() {
1051 context_menu.layout(
1052 SizeConstraint {
1053 min: Vector2F::zero(),
1054 max: vec2f(
1055 f32::INFINITY,
1056 (12. * line_height).min((size.y() - line_height) / 2.),
1057 ),
1058 },
1059 cx,
1060 );
1061 }
1062
1063 if let Some((_, indicator)) = code_actions_indicator.as_mut() {
1064 indicator.layout(
1065 SizeConstraint::strict_along(Axis::Vertical, line_height * 0.618),
1066 cx,
1067 );
1068 }
1069
1070 let blocks = self.layout_blocks(
1071 start_row..end_row,
1072 &snapshot,
1073 size.x().max(scroll_width + gutter_width),
1074 gutter_padding,
1075 gutter_width,
1076 em_width,
1077 gutter_width + gutter_margin,
1078 line_height,
1079 &style,
1080 &line_layouts,
1081 cx,
1082 );
1083
1084 (
1085 size,
1086 LayoutState {
1087 size,
1088 scroll_max,
1089 gutter_size,
1090 gutter_padding,
1091 text_size,
1092 gutter_margin,
1093 snapshot,
1094 active_rows,
1095 highlighted_rows,
1096 highlighted_ranges,
1097 line_layouts,
1098 line_number_layouts,
1099 blocks,
1100 line_height,
1101 em_width,
1102 em_advance,
1103 selections,
1104 context_menu,
1105 code_actions_indicator,
1106 },
1107 )
1108 }
1109
1110 fn paint(
1111 &mut self,
1112 bounds: RectF,
1113 visible_bounds: RectF,
1114 layout: &mut Self::LayoutState,
1115 cx: &mut PaintContext,
1116 ) -> Self::PaintState {
1117 cx.scene.push_layer(Some(bounds));
1118
1119 let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
1120 let text_bounds = RectF::new(
1121 bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
1122 layout.text_size,
1123 );
1124
1125 self.paint_background(gutter_bounds, text_bounds, layout, cx);
1126 if layout.gutter_size.x() > 0. {
1127 self.paint_gutter(gutter_bounds, visible_bounds, layout, cx);
1128 }
1129 self.paint_text(text_bounds, visible_bounds, layout, cx);
1130
1131 if !layout.blocks.is_empty() {
1132 cx.scene.push_layer(Some(bounds));
1133 self.paint_blocks(bounds, visible_bounds, layout, cx);
1134 cx.scene.pop_layer();
1135 }
1136
1137 cx.scene.pop_layer();
1138
1139 PaintState {
1140 bounds,
1141 gutter_bounds,
1142 text_bounds,
1143 }
1144 }
1145
1146 fn dispatch_event(
1147 &mut self,
1148 event: &Event,
1149 _: RectF,
1150 layout: &mut LayoutState,
1151 paint: &mut PaintState,
1152 cx: &mut EventContext,
1153 ) -> bool {
1154 if let Some((_, context_menu)) = &mut layout.context_menu {
1155 if context_menu.dispatch_event(event, cx) {
1156 return true;
1157 }
1158 }
1159
1160 if let Some((_, indicator)) = &mut layout.code_actions_indicator {
1161 if indicator.dispatch_event(event, cx) {
1162 return true;
1163 }
1164 }
1165
1166 for (_, block) in &mut layout.blocks {
1167 if block.dispatch_event(event, cx) {
1168 return true;
1169 }
1170 }
1171
1172 match event {
1173 Event::LeftMouseDown {
1174 position,
1175 alt,
1176 shift,
1177 click_count,
1178 ..
1179 } => self.mouse_down(*position, *alt, *shift, *click_count, layout, paint, cx),
1180 Event::LeftMouseUp { position } => self.mouse_up(*position, cx),
1181 Event::LeftMouseDragged { position } => {
1182 self.mouse_dragged(*position, layout, paint, cx)
1183 }
1184 Event::ScrollWheel {
1185 position,
1186 delta,
1187 precise,
1188 } => self.scroll(*position, *delta, *precise, layout, paint, cx),
1189 Event::KeyDown { input, .. } => self.key_down(input.as_deref(), cx),
1190 _ => false,
1191 }
1192 }
1193
1194 fn debug(
1195 &self,
1196 bounds: RectF,
1197 _: &Self::LayoutState,
1198 _: &Self::PaintState,
1199 _: &gpui::DebugContext,
1200 ) -> json::Value {
1201 json!({
1202 "type": "BufferElement",
1203 "bounds": bounds.to_json()
1204 })
1205 }
1206}
1207
1208pub struct LayoutState {
1209 size: Vector2F,
1210 scroll_max: Vector2F,
1211 gutter_size: Vector2F,
1212 gutter_padding: f32,
1213 gutter_margin: f32,
1214 text_size: Vector2F,
1215 snapshot: EditorSnapshot,
1216 active_rows: BTreeMap<u32, bool>,
1217 highlighted_rows: Option<Range<u32>>,
1218 line_layouts: Vec<text_layout::Line>,
1219 line_number_layouts: Vec<Option<text_layout::Line>>,
1220 blocks: Vec<(u32, ElementBox)>,
1221 line_height: f32,
1222 em_width: f32,
1223 em_advance: f32,
1224 highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
1225 selections: Vec<(ReplicaId, Vec<text::Selection<DisplayPoint>>)>,
1226 context_menu: Option<(DisplayPoint, ElementBox)>,
1227 code_actions_indicator: Option<(u32, ElementBox)>,
1228}
1229
1230fn layout_line(
1231 row: u32,
1232 snapshot: &EditorSnapshot,
1233 style: &EditorStyle,
1234 layout_cache: &TextLayoutCache,
1235) -> text_layout::Line {
1236 let mut line = snapshot.line(row);
1237
1238 if line.len() > MAX_LINE_LEN {
1239 let mut len = MAX_LINE_LEN;
1240 while !line.is_char_boundary(len) {
1241 len -= 1;
1242 }
1243
1244 line.truncate(len);
1245 }
1246
1247 layout_cache.layout_str(
1248 &line,
1249 style.text.font_size,
1250 &[(
1251 snapshot.line_len(row) as usize,
1252 RunStyle {
1253 font_id: style.text.font_id,
1254 color: Color::black(),
1255 underline: Default::default(),
1256 },
1257 )],
1258 )
1259}
1260
1261pub struct PaintState {
1262 bounds: RectF,
1263 gutter_bounds: RectF,
1264 text_bounds: RectF,
1265}
1266
1267impl PaintState {
1268 fn point_for_position(
1269 &self,
1270 snapshot: &EditorSnapshot,
1271 layout: &LayoutState,
1272 position: Vector2F,
1273 ) -> (DisplayPoint, u32) {
1274 let scroll_position = snapshot.scroll_position();
1275 let position = position - self.text_bounds.origin();
1276 let y = position.y().max(0.0).min(layout.size.y());
1277 let row = ((y / layout.line_height) + scroll_position.y()) as u32;
1278 let row = cmp::min(row, snapshot.max_point().row());
1279 let line = &layout.line_layouts[(row - scroll_position.y() as u32) as usize];
1280 let x = position.x() + (scroll_position.x() * layout.em_width);
1281
1282 let column = if x >= 0.0 {
1283 line.index_for_x(x)
1284 .map(|ix| ix as u32)
1285 .unwrap_or_else(|| snapshot.line_len(row))
1286 } else {
1287 0
1288 };
1289 let overshoot = (0f32.max(x - line.width()) / layout.em_advance) as u32;
1290
1291 (DisplayPoint::new(row, column), overshoot)
1292 }
1293}
1294
1295#[derive(Copy, Clone, PartialEq, Eq)]
1296pub enum CursorShape {
1297 Bar,
1298 Block,
1299 Underscore,
1300}
1301
1302impl Default for CursorShape {
1303 fn default() -> Self {
1304 CursorShape::Bar
1305 }
1306}
1307
1308struct Cursor {
1309 origin: Vector2F,
1310 block_width: f32,
1311 line_height: f32,
1312 color: Color,
1313 shape: CursorShape,
1314 block_text: Option<Line>,
1315}
1316
1317impl Cursor {
1318 fn paint(&self, cx: &mut PaintContext) {
1319 let bounds = match self.shape {
1320 CursorShape::Bar => RectF::new(self.origin, vec2f(2.0, self.line_height)),
1321 CursorShape::Block => {
1322 RectF::new(self.origin, vec2f(self.block_width, self.line_height))
1323 }
1324 CursorShape::Underscore => RectF::new(
1325 self.origin + Vector2F::new(0.0, self.line_height - 2.0),
1326 vec2f(self.block_width, 2.0),
1327 ),
1328 };
1329
1330 cx.scene.push_quad(Quad {
1331 bounds,
1332 background: Some(self.color),
1333 border: Border::new(0., Color::black()),
1334 corner_radius: 0.,
1335 });
1336
1337 if let Some(block_text) = &self.block_text {
1338 block_text.paint(self.origin, bounds, self.line_height, cx);
1339 }
1340 }
1341}
1342
1343#[derive(Debug)]
1344struct HighlightedRange {
1345 start_y: f32,
1346 line_height: f32,
1347 lines: Vec<HighlightedRangeLine>,
1348 color: Color,
1349 corner_radius: f32,
1350}
1351
1352#[derive(Debug)]
1353struct HighlightedRangeLine {
1354 start_x: f32,
1355 end_x: f32,
1356}
1357
1358impl HighlightedRange {
1359 fn paint(&self, bounds: RectF, scene: &mut Scene) {
1360 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
1361 self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
1362 self.paint_lines(
1363 self.start_y + self.line_height,
1364 &self.lines[1..],
1365 bounds,
1366 scene,
1367 );
1368 } else {
1369 self.paint_lines(self.start_y, &self.lines, bounds, scene);
1370 }
1371 }
1372
1373 fn paint_lines(
1374 &self,
1375 start_y: f32,
1376 lines: &[HighlightedRangeLine],
1377 bounds: RectF,
1378 scene: &mut Scene,
1379 ) {
1380 if lines.is_empty() {
1381 return;
1382 }
1383
1384 let mut path = PathBuilder::new();
1385 let first_line = lines.first().unwrap();
1386 let last_line = lines.last().unwrap();
1387
1388 let first_top_left = vec2f(first_line.start_x, start_y);
1389 let first_top_right = vec2f(first_line.end_x, start_y);
1390
1391 let curve_height = vec2f(0., self.corner_radius);
1392 let curve_width = |start_x: f32, end_x: f32| {
1393 let max = (end_x - start_x) / 2.;
1394 let width = if max < self.corner_radius {
1395 max
1396 } else {
1397 self.corner_radius
1398 };
1399
1400 vec2f(width, 0.)
1401 };
1402
1403 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
1404 path.reset(first_top_right - top_curve_width);
1405 path.curve_to(first_top_right + curve_height, first_top_right);
1406
1407 let mut iter = lines.iter().enumerate().peekable();
1408 while let Some((ix, line)) = iter.next() {
1409 let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
1410
1411 if let Some((_, next_line)) = iter.peek() {
1412 let next_top_right = vec2f(next_line.end_x, bottom_right.y());
1413
1414 match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
1415 Ordering::Equal => {
1416 path.line_to(bottom_right);
1417 }
1418 Ordering::Less => {
1419 let curve_width = curve_width(next_top_right.x(), bottom_right.x());
1420 path.line_to(bottom_right - curve_height);
1421 if self.corner_radius > 0. {
1422 path.curve_to(bottom_right - curve_width, bottom_right);
1423 }
1424 path.line_to(next_top_right + curve_width);
1425 if self.corner_radius > 0. {
1426 path.curve_to(next_top_right + curve_height, next_top_right);
1427 }
1428 }
1429 Ordering::Greater => {
1430 let curve_width = curve_width(bottom_right.x(), next_top_right.x());
1431 path.line_to(bottom_right - curve_height);
1432 if self.corner_radius > 0. {
1433 path.curve_to(bottom_right + curve_width, bottom_right);
1434 }
1435 path.line_to(next_top_right - curve_width);
1436 if self.corner_radius > 0. {
1437 path.curve_to(next_top_right + curve_height, next_top_right);
1438 }
1439 }
1440 }
1441 } else {
1442 let curve_width = curve_width(line.start_x, line.end_x);
1443 path.line_to(bottom_right - curve_height);
1444 if self.corner_radius > 0. {
1445 path.curve_to(bottom_right - curve_width, bottom_right);
1446 }
1447
1448 let bottom_left = vec2f(line.start_x, bottom_right.y());
1449 path.line_to(bottom_left + curve_width);
1450 if self.corner_radius > 0. {
1451 path.curve_to(bottom_left - curve_height, bottom_left);
1452 }
1453 }
1454 }
1455
1456 if first_line.start_x > last_line.start_x {
1457 let curve_width = curve_width(last_line.start_x, first_line.start_x);
1458 let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
1459 path.line_to(second_top_left + curve_height);
1460 if self.corner_radius > 0. {
1461 path.curve_to(second_top_left + curve_width, second_top_left);
1462 }
1463 let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
1464 path.line_to(first_bottom_left - curve_width);
1465 if self.corner_radius > 0. {
1466 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
1467 }
1468 }
1469
1470 path.line_to(first_top_left + curve_height);
1471 if self.corner_radius > 0. {
1472 path.curve_to(first_top_left + top_curve_width, first_top_left);
1473 }
1474 path.line_to(first_top_right - top_curve_width);
1475
1476 scene.push_path(path.build(self.color, Some(bounds)));
1477 }
1478}
1479
1480fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
1481 delta.powf(1.5) / 100.0
1482}
1483
1484fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
1485 delta.powf(1.2) / 300.0
1486}
1487
1488#[cfg(test)]
1489mod tests {
1490 use std::sync::Arc;
1491
1492 use super::*;
1493 use crate::{
1494 display_map::{BlockDisposition, BlockProperties},
1495 Editor, MultiBuffer,
1496 };
1497 use util::test::sample_text;
1498 use workspace::Settings;
1499
1500 #[gpui::test]
1501 fn test_layout_line_numbers(cx: &mut gpui::MutableAppContext) {
1502 cx.set_global(Settings::test(cx));
1503 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
1504 let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1505 Editor::new(EditorMode::Full, buffer, None, None, cx)
1506 });
1507 let element = EditorElement::new(
1508 editor.downgrade(),
1509 editor.read(cx).style(cx),
1510 CursorShape::Bar,
1511 );
1512
1513 let layouts = editor.update(cx, |editor, cx| {
1514 let snapshot = editor.snapshot(cx);
1515 let mut presenter = cx.build_presenter(window_id, 30.);
1516 let mut layout_cx = presenter.build_layout_context(false, cx);
1517 element.layout_line_numbers(0..6, &Default::default(), &snapshot, &mut layout_cx)
1518 });
1519 assert_eq!(layouts.len(), 6);
1520 }
1521
1522 #[gpui::test]
1523 fn test_layout_with_placeholder_text_and_blocks(cx: &mut gpui::MutableAppContext) {
1524 cx.set_global(Settings::test(cx));
1525 let buffer = MultiBuffer::build_simple("", cx);
1526 let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1527 Editor::new(EditorMode::Full, buffer, None, None, cx)
1528 });
1529
1530 editor.update(cx, |editor, cx| {
1531 editor.set_placeholder_text("hello", cx);
1532 editor.insert_blocks(
1533 [BlockProperties {
1534 disposition: BlockDisposition::Above,
1535 height: 3,
1536 position: Anchor::min(),
1537 render: Arc::new(|_| Empty::new().boxed()),
1538 }],
1539 cx,
1540 );
1541
1542 // Blur the editor so that it displays placeholder text.
1543 cx.blur();
1544 });
1545
1546 let mut element = EditorElement::new(
1547 editor.downgrade(),
1548 editor.read(cx).style(cx),
1549 CursorShape::Bar,
1550 );
1551
1552 let mut scene = Scene::new(1.0);
1553 let mut presenter = cx.build_presenter(window_id, 30.);
1554 let mut layout_cx = presenter.build_layout_context(false, cx);
1555 let (size, mut state) = element.layout(
1556 SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
1557 &mut layout_cx,
1558 );
1559
1560 assert_eq!(state.line_layouts.len(), 4);
1561 assert_eq!(
1562 state
1563 .line_number_layouts
1564 .iter()
1565 .map(Option::is_some)
1566 .collect::<Vec<_>>(),
1567 &[false, false, false, true]
1568 );
1569
1570 // Don't panic.
1571 let bounds = RectF::new(Default::default(), size);
1572 let mut paint_cx = presenter.build_paint_context(&mut scene, cx);
1573 element.paint(bounds, bounds, &mut state, &mut paint_cx);
1574 }
1575}