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