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;
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 {
669 ..Default::default()
670 };
671
672 if chunk.is_unnecessary {
673 diagnostic_highlight.fade_out = Some(style.unnecessary_code_fade);
674 } else if let Some(severity) = chunk.diagnostic_severity {
675 let diagnostic_style = super::diagnostic_style(severity, true, style);
676 diagnostic_highlight.underline = Some(Underline {
677 color: Some(diagnostic_style.message.text.color),
678 thickness: 1.0.into(),
679 squiggly: true,
680 });
681 }
682
683 if let Some(highlight_style) = highlight_style.as_mut() {
684 highlight_style.highlight(diagnostic_highlight);
685 } else {
686 highlight_style = Some(diagnostic_highlight);
687 }
688
689 (chunk.text, highlight_style)
690 });
691 layout_highlighted_chunks(
692 chunks,
693 &style.text,
694 &cx.text_layout_cache,
695 &cx.font_cache,
696 MAX_LINE_LEN,
697 rows.len() as usize,
698 )
699 }
700 }
701
702 fn layout_blocks(
703 &mut self,
704 rows: Range<u32>,
705 snapshot: &EditorSnapshot,
706 width: f32,
707 gutter_padding: f32,
708 gutter_width: f32,
709 em_width: f32,
710 text_x: f32,
711 line_height: f32,
712 style: &EditorStyle,
713 line_layouts: &[text_layout::Line],
714 cx: &mut LayoutContext,
715 ) -> Vec<(u32, ElementBox)> {
716 let scroll_x = snapshot.scroll_position.x();
717 snapshot
718 .blocks_in_range(rows.clone())
719 .map(|(block_row, block)| {
720 let mut element = match block {
721 TransformBlock::Custom(block) => {
722 let align_to = block
723 .position()
724 .to_point(&snapshot.buffer_snapshot)
725 .to_display_point(snapshot);
726 let anchor_x = text_x
727 + if rows.contains(&align_to.row()) {
728 line_layouts[(align_to.row() - rows.start) as usize]
729 .x_for_index(align_to.column() as usize)
730 } else {
731 layout_line(align_to.row(), snapshot, style, cx.text_layout_cache)
732 .x_for_index(align_to.column() as usize)
733 };
734
735 block.render(&BlockContext {
736 cx,
737 anchor_x,
738 gutter_padding,
739 line_height,
740 scroll_x,
741 gutter_width,
742 em_width,
743 })
744 }
745 TransformBlock::ExcerptHeader {
746 buffer,
747 starts_new_buffer,
748 ..
749 } => {
750 if *starts_new_buffer {
751 let style = &self.style.diagnostic_path_header;
752 let font_size =
753 (style.text_scale_factor * self.style.text.font_size).round();
754
755 let mut filename = None;
756 let mut parent_path = None;
757 if let Some(path) = buffer.path() {
758 filename =
759 path.file_name().map(|f| f.to_string_lossy().to_string());
760 parent_path =
761 path.parent().map(|p| p.to_string_lossy().to_string() + "/");
762 }
763
764 Flex::row()
765 .with_child(
766 Label::new(
767 filename.unwrap_or_else(|| "untitled".to_string()),
768 style.filename.text.clone().with_font_size(font_size),
769 )
770 .contained()
771 .with_style(style.filename.container)
772 .boxed(),
773 )
774 .with_children(parent_path.map(|path| {
775 Label::new(
776 path,
777 style.path.text.clone().with_font_size(font_size),
778 )
779 .contained()
780 .with_style(style.path.container)
781 .boxed()
782 }))
783 .aligned()
784 .left()
785 .contained()
786 .with_style(style.container)
787 .with_padding_left(gutter_padding + scroll_x * em_width)
788 .expanded()
789 .named("path header block")
790 } else {
791 let text_style = self.style.text.clone();
792 Label::new("…".to_string(), text_style)
793 .contained()
794 .with_padding_left(gutter_padding + scroll_x * em_width)
795 .named("collapsed context")
796 }
797 }
798 };
799
800 element.layout(
801 SizeConstraint {
802 min: Vector2F::zero(),
803 max: vec2f(width, block.height() as f32 * line_height),
804 },
805 cx,
806 );
807 (block_row, element)
808 })
809 .collect()
810 }
811}
812
813impl Element for EditorElement {
814 type LayoutState = LayoutState;
815 type PaintState = PaintState;
816
817 fn layout(
818 &mut self,
819 constraint: SizeConstraint,
820 cx: &mut LayoutContext,
821 ) -> (Vector2F, Self::LayoutState) {
822 let mut size = constraint.max;
823 if size.x().is_infinite() {
824 unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
825 }
826
827 let snapshot = self.snapshot(cx.app);
828 let style = self.style.clone();
829 let line_height = style.text.line_height(cx.font_cache);
830
831 let gutter_padding;
832 let gutter_width;
833 let gutter_margin;
834 if snapshot.mode == EditorMode::Full {
835 gutter_padding = style.text.em_width(cx.font_cache) * style.gutter_padding_factor;
836 gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
837 gutter_margin = -style.text.descent(cx.font_cache);
838 } else {
839 gutter_padding = 0.0;
840 gutter_width = 0.0;
841 gutter_margin = 0.0;
842 };
843
844 let text_width = size.x() - gutter_width;
845 let em_width = style.text.em_width(cx.font_cache);
846 let em_advance = style.text.em_advance(cx.font_cache);
847 let overscroll = vec2f(em_width, 0.);
848 let snapshot = self.update_view(cx.app, |view, cx| {
849 let wrap_width = match view.soft_wrap_mode(cx) {
850 SoftWrap::None => None,
851 SoftWrap::EditorWidth => {
852 Some(text_width - gutter_margin - overscroll.x() - em_width)
853 }
854 SoftWrap::Column(column) => Some(column as f32 * em_advance),
855 };
856
857 if view.set_wrap_width(wrap_width, cx) {
858 view.snapshot(cx)
859 } else {
860 snapshot
861 }
862 });
863
864 let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
865 if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
866 size.set_y(
867 scroll_height
868 .min(constraint.max_along(Axis::Vertical))
869 .max(constraint.min_along(Axis::Vertical))
870 .min(line_height * max_lines as f32),
871 )
872 } else if size.y().is_infinite() {
873 size.set_y(scroll_height);
874 }
875 let gutter_size = vec2f(gutter_width, size.y());
876 let text_size = vec2f(text_width, size.y());
877
878 let (autoscroll_horizontally, mut snapshot) = self.update_view(cx.app, |view, cx| {
879 let autoscroll_horizontally = view.autoscroll_vertically(size.y(), line_height, cx);
880 let snapshot = view.snapshot(cx);
881 (autoscroll_horizontally, snapshot)
882 });
883
884 let scroll_position = snapshot.scroll_position();
885 let start_row = scroll_position.y() as u32;
886 let scroll_top = scroll_position.y() * line_height;
887
888 // Add 1 to ensure selections bleed off screen
889 let end_row = 1 + cmp::min(
890 ((scroll_top + size.y()) / line_height).ceil() as u32,
891 snapshot.max_point().row(),
892 );
893
894 let start_anchor = if start_row == 0 {
895 Anchor::min()
896 } else {
897 snapshot
898 .buffer_snapshot
899 .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
900 };
901 let end_anchor = if end_row > snapshot.max_point().row() {
902 Anchor::max()
903 } else {
904 snapshot
905 .buffer_snapshot
906 .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
907 };
908
909 let mut selections = HashMap::default();
910 let mut active_rows = BTreeMap::new();
911 let mut highlighted_rows = None;
912 let mut highlighted_ranges = Vec::new();
913 self.update_view(cx.app, |view, cx| {
914 let display_map = view.display_map.update(cx, |map, cx| map.snapshot(cx));
915
916 highlighted_rows = view.highlighted_rows();
917 highlighted_ranges = view.background_highlights_in_range(
918 start_anchor.clone()..end_anchor.clone(),
919 &display_map,
920 );
921
922 if view.show_local_selections {
923 let local_selections = view.local_selections_in_range(
924 start_anchor.clone()..end_anchor.clone(),
925 &display_map,
926 );
927 for selection in &local_selections {
928 let is_empty = selection.start == selection.end;
929 let selection_start = snapshot.prev_line_boundary(selection.start).1;
930 let selection_end = snapshot.next_line_boundary(selection.end).1;
931 for row in cmp::max(selection_start.row(), start_row)
932 ..=cmp::min(selection_end.row(), end_row)
933 {
934 let contains_non_empty_selection =
935 active_rows.entry(row).or_insert(!is_empty);
936 *contains_non_empty_selection |= !is_empty;
937 }
938 }
939 selections.insert(
940 view.replica_id(cx),
941 local_selections
942 .into_iter()
943 .map(|selection| crate::Selection {
944 id: selection.id,
945 goal: selection.goal,
946 reversed: selection.reversed,
947 start: selection.start.to_display_point(&display_map),
948 end: selection.end.to_display_point(&display_map),
949 })
950 .collect(),
951 );
952 }
953
954 for (replica_id, selection) in display_map
955 .buffer_snapshot
956 .remote_selections_in_range(&(start_anchor..end_anchor))
957 {
958 selections
959 .entry(replica_id)
960 .or_insert(Vec::new())
961 .push(crate::Selection {
962 id: selection.id,
963 goal: selection.goal,
964 reversed: selection.reversed,
965 start: selection.start.to_display_point(&display_map),
966 end: selection.end.to_display_point(&display_map),
967 });
968 }
969 });
970
971 let line_number_layouts =
972 self.layout_line_numbers(start_row..end_row, &active_rows, &snapshot, cx);
973
974 let mut max_visible_line_width = 0.0;
975 let line_layouts = self.layout_lines(start_row..end_row, &snapshot, cx);
976 for line in &line_layouts {
977 if line.width() > max_visible_line_width {
978 max_visible_line_width = line.width();
979 }
980 }
981
982 let style = self.style.clone();
983 let longest_line_width = layout_line(
984 snapshot.longest_row(),
985 &snapshot,
986 &style,
987 cx.text_layout_cache,
988 )
989 .width();
990 let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
991 let em_width = style.text.em_width(cx.font_cache);
992 let max_row = snapshot.max_point().row();
993 let scroll_max = vec2f(
994 ((scroll_width - text_size.x()) / em_width).max(0.0),
995 max_row.saturating_sub(1) as f32,
996 );
997
998 let mut context_menu = None;
999 let mut code_actions_indicator = None;
1000 self.update_view(cx.app, |view, cx| {
1001 let clamped = view.clamp_scroll_left(scroll_max.x());
1002 let autoscrolled;
1003 if autoscroll_horizontally {
1004 autoscrolled = view.autoscroll_horizontally(
1005 start_row,
1006 text_size.x(),
1007 scroll_width,
1008 em_width,
1009 &line_layouts,
1010 cx,
1011 );
1012 } else {
1013 autoscrolled = false;
1014 }
1015
1016 if clamped || autoscrolled {
1017 snapshot = view.snapshot(cx);
1018 }
1019
1020 let newest_selection_head = view
1021 .newest_selection_with_snapshot::<usize>(&snapshot.buffer_snapshot)
1022 .head()
1023 .to_display_point(&snapshot);
1024
1025 if (start_row..end_row).contains(&newest_selection_head.row()) {
1026 let style = view.style(cx);
1027 if view.context_menu_visible() {
1028 context_menu =
1029 view.render_context_menu(newest_selection_head, style.clone(), cx);
1030 }
1031
1032 code_actions_indicator = view
1033 .render_code_actions_indicator(&style, cx)
1034 .map(|indicator| (newest_selection_head.row(), indicator));
1035 }
1036 });
1037
1038 if let Some((_, context_menu)) = context_menu.as_mut() {
1039 context_menu.layout(
1040 SizeConstraint {
1041 min: Vector2F::zero(),
1042 max: vec2f(
1043 f32::INFINITY,
1044 (12. * line_height).min((size.y() - line_height) / 2.),
1045 ),
1046 },
1047 cx,
1048 );
1049 }
1050
1051 if let Some((_, indicator)) = code_actions_indicator.as_mut() {
1052 indicator.layout(
1053 SizeConstraint::strict_along(Axis::Vertical, line_height * 0.618),
1054 cx,
1055 );
1056 }
1057
1058 let blocks = self.layout_blocks(
1059 start_row..end_row,
1060 &snapshot,
1061 size.x().max(scroll_width + gutter_width),
1062 gutter_padding,
1063 gutter_width,
1064 em_width,
1065 gutter_width + gutter_margin,
1066 line_height,
1067 &style,
1068 &line_layouts,
1069 cx,
1070 );
1071
1072 (
1073 size,
1074 LayoutState {
1075 size,
1076 scroll_max,
1077 gutter_size,
1078 gutter_padding,
1079 text_size,
1080 gutter_margin,
1081 snapshot,
1082 active_rows,
1083 highlighted_rows,
1084 highlighted_ranges,
1085 line_layouts,
1086 line_number_layouts,
1087 blocks,
1088 line_height,
1089 em_width,
1090 em_advance,
1091 selections,
1092 context_menu,
1093 code_actions_indicator,
1094 },
1095 )
1096 }
1097
1098 fn paint(
1099 &mut self,
1100 bounds: RectF,
1101 visible_bounds: RectF,
1102 layout: &mut Self::LayoutState,
1103 cx: &mut PaintContext,
1104 ) -> Self::PaintState {
1105 cx.scene.push_layer(Some(bounds));
1106
1107 let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
1108 let text_bounds = RectF::new(
1109 bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
1110 layout.text_size,
1111 );
1112
1113 self.paint_background(gutter_bounds, text_bounds, layout, cx);
1114 if layout.gutter_size.x() > 0. {
1115 self.paint_gutter(gutter_bounds, visible_bounds, layout, cx);
1116 }
1117 self.paint_text(text_bounds, visible_bounds, layout, cx);
1118
1119 if !layout.blocks.is_empty() {
1120 cx.scene.push_layer(Some(bounds));
1121 self.paint_blocks(bounds, visible_bounds, layout, cx);
1122 cx.scene.pop_layer();
1123 }
1124
1125 cx.scene.pop_layer();
1126
1127 PaintState {
1128 bounds,
1129 gutter_bounds,
1130 text_bounds,
1131 }
1132 }
1133
1134 fn dispatch_event(
1135 &mut self,
1136 event: &Event,
1137 _: RectF,
1138 layout: &mut LayoutState,
1139 paint: &mut PaintState,
1140 cx: &mut EventContext,
1141 ) -> bool {
1142 if let Some((_, context_menu)) = &mut layout.context_menu {
1143 if context_menu.dispatch_event(event, cx) {
1144 return true;
1145 }
1146 }
1147
1148 if let Some((_, indicator)) = &mut layout.code_actions_indicator {
1149 if indicator.dispatch_event(event, cx) {
1150 return true;
1151 }
1152 }
1153
1154 for (_, block) in &mut layout.blocks {
1155 if block.dispatch_event(event, cx) {
1156 return true;
1157 }
1158 }
1159
1160 match event {
1161 Event::LeftMouseDown {
1162 position,
1163 alt,
1164 shift,
1165 click_count,
1166 ..
1167 } => self.mouse_down(*position, *alt, *shift, *click_count, layout, paint, cx),
1168 Event::LeftMouseUp { position } => self.mouse_up(*position, cx),
1169 Event::LeftMouseDragged { position } => {
1170 self.mouse_dragged(*position, layout, paint, cx)
1171 }
1172 Event::ScrollWheel {
1173 position,
1174 delta,
1175 precise,
1176 } => self.scroll(*position, *delta, *precise, layout, paint, cx),
1177 Event::KeyDown { input, .. } => self.key_down(input.as_deref(), cx),
1178 _ => false,
1179 }
1180 }
1181
1182 fn debug(
1183 &self,
1184 bounds: RectF,
1185 _: &Self::LayoutState,
1186 _: &Self::PaintState,
1187 _: &gpui::DebugContext,
1188 ) -> json::Value {
1189 json!({
1190 "type": "BufferElement",
1191 "bounds": bounds.to_json()
1192 })
1193 }
1194}
1195
1196pub struct LayoutState {
1197 size: Vector2F,
1198 scroll_max: Vector2F,
1199 gutter_size: Vector2F,
1200 gutter_padding: f32,
1201 gutter_margin: f32,
1202 text_size: Vector2F,
1203 snapshot: EditorSnapshot,
1204 active_rows: BTreeMap<u32, bool>,
1205 highlighted_rows: Option<Range<u32>>,
1206 line_layouts: Vec<text_layout::Line>,
1207 line_number_layouts: Vec<Option<text_layout::Line>>,
1208 blocks: Vec<(u32, ElementBox)>,
1209 line_height: f32,
1210 em_width: f32,
1211 em_advance: f32,
1212 highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
1213 selections: HashMap<ReplicaId, Vec<text::Selection<DisplayPoint>>>,
1214 context_menu: Option<(DisplayPoint, ElementBox)>,
1215 code_actions_indicator: Option<(u32, ElementBox)>,
1216}
1217
1218fn layout_line(
1219 row: u32,
1220 snapshot: &EditorSnapshot,
1221 style: &EditorStyle,
1222 layout_cache: &TextLayoutCache,
1223) -> text_layout::Line {
1224 let mut line = snapshot.line(row);
1225
1226 if line.len() > MAX_LINE_LEN {
1227 let mut len = MAX_LINE_LEN;
1228 while !line.is_char_boundary(len) {
1229 len -= 1;
1230 }
1231
1232 line.truncate(len);
1233 }
1234
1235 layout_cache.layout_str(
1236 &line,
1237 style.text.font_size,
1238 &[(
1239 snapshot.line_len(row) as usize,
1240 RunStyle {
1241 font_id: style.text.font_id,
1242 color: Color::black(),
1243 underline: Default::default(),
1244 },
1245 )],
1246 )
1247}
1248
1249pub struct PaintState {
1250 bounds: RectF,
1251 gutter_bounds: RectF,
1252 text_bounds: RectF,
1253}
1254
1255impl PaintState {
1256 fn point_for_position(
1257 &self,
1258 snapshot: &EditorSnapshot,
1259 layout: &LayoutState,
1260 position: Vector2F,
1261 ) -> (DisplayPoint, u32) {
1262 let scroll_position = snapshot.scroll_position();
1263 let position = position - self.text_bounds.origin();
1264 let y = position.y().max(0.0).min(layout.size.y());
1265 let row = ((y / layout.line_height) + scroll_position.y()) as u32;
1266 let row = cmp::min(row, snapshot.max_point().row());
1267 let line = &layout.line_layouts[(row - scroll_position.y() as u32) as usize];
1268 let x = position.x() + (scroll_position.x() * layout.em_width);
1269
1270 let column = if x >= 0.0 {
1271 line.index_for_x(x)
1272 .map(|ix| ix as u32)
1273 .unwrap_or_else(|| snapshot.line_len(row))
1274 } else {
1275 0
1276 };
1277 let overshoot = (0f32.max(x - line.width()) / layout.em_advance) as u32;
1278
1279 (DisplayPoint::new(row, column), overshoot)
1280 }
1281}
1282
1283#[derive(Copy, Clone)]
1284pub enum CursorShape {
1285 Bar,
1286 Block,
1287 Underscore,
1288}
1289
1290impl Default for CursorShape {
1291 fn default() -> Self {
1292 CursorShape::Bar
1293 }
1294}
1295
1296struct Cursor {
1297 origin: Vector2F,
1298 block_width: f32,
1299 line_height: f32,
1300 color: Color,
1301 shape: CursorShape,
1302 block_text: Option<Line>,
1303}
1304
1305impl Cursor {
1306 fn paint(&self, cx: &mut PaintContext) {
1307 let bounds = match self.shape {
1308 CursorShape::Bar => RectF::new(self.origin, vec2f(2.0, self.line_height)),
1309 CursorShape::Block => {
1310 RectF::new(self.origin, vec2f(self.block_width, self.line_height))
1311 }
1312 CursorShape::Underscore => RectF::new(
1313 self.origin + Vector2F::new(0.0, self.line_height - 2.0),
1314 vec2f(self.block_width, 2.0),
1315 ),
1316 };
1317
1318 cx.scene.push_quad(Quad {
1319 bounds,
1320 background: Some(self.color),
1321 border: Border::new(0., Color::black()),
1322 corner_radius: 0.,
1323 });
1324
1325 if let Some(block_text) = &self.block_text {
1326 block_text.paint(self.origin, bounds, self.line_height, cx);
1327 }
1328 }
1329}
1330
1331#[derive(Debug)]
1332struct HighlightedRange {
1333 start_y: f32,
1334 line_height: f32,
1335 lines: Vec<HighlightedRangeLine>,
1336 color: Color,
1337 corner_radius: f32,
1338}
1339
1340#[derive(Debug)]
1341struct HighlightedRangeLine {
1342 start_x: f32,
1343 end_x: f32,
1344}
1345
1346impl HighlightedRange {
1347 fn paint(&self, bounds: RectF, scene: &mut Scene) {
1348 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
1349 self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
1350 self.paint_lines(
1351 self.start_y + self.line_height,
1352 &self.lines[1..],
1353 bounds,
1354 scene,
1355 );
1356 } else {
1357 self.paint_lines(self.start_y, &self.lines, bounds, scene);
1358 }
1359 }
1360
1361 fn paint_lines(
1362 &self,
1363 start_y: f32,
1364 lines: &[HighlightedRangeLine],
1365 bounds: RectF,
1366 scene: &mut Scene,
1367 ) {
1368 if lines.is_empty() {
1369 return;
1370 }
1371
1372 let mut path = PathBuilder::new();
1373 let first_line = lines.first().unwrap();
1374 let last_line = lines.last().unwrap();
1375
1376 let first_top_left = vec2f(first_line.start_x, start_y);
1377 let first_top_right = vec2f(first_line.end_x, start_y);
1378
1379 let curve_height = vec2f(0., self.corner_radius);
1380 let curve_width = |start_x: f32, end_x: f32| {
1381 let max = (end_x - start_x) / 2.;
1382 let width = if max < self.corner_radius {
1383 max
1384 } else {
1385 self.corner_radius
1386 };
1387
1388 vec2f(width, 0.)
1389 };
1390
1391 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
1392 path.reset(first_top_right - top_curve_width);
1393 path.curve_to(first_top_right + curve_height, first_top_right);
1394
1395 let mut iter = lines.iter().enumerate().peekable();
1396 while let Some((ix, line)) = iter.next() {
1397 let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
1398
1399 if let Some((_, next_line)) = iter.peek() {
1400 let next_top_right = vec2f(next_line.end_x, bottom_right.y());
1401
1402 match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
1403 Ordering::Equal => {
1404 path.line_to(bottom_right);
1405 }
1406 Ordering::Less => {
1407 let curve_width = curve_width(next_top_right.x(), bottom_right.x());
1408 path.line_to(bottom_right - curve_height);
1409 if self.corner_radius > 0. {
1410 path.curve_to(bottom_right - curve_width, bottom_right);
1411 }
1412 path.line_to(next_top_right + curve_width);
1413 if self.corner_radius > 0. {
1414 path.curve_to(next_top_right + curve_height, next_top_right);
1415 }
1416 }
1417 Ordering::Greater => {
1418 let curve_width = curve_width(bottom_right.x(), next_top_right.x());
1419 path.line_to(bottom_right - curve_height);
1420 if self.corner_radius > 0. {
1421 path.curve_to(bottom_right + curve_width, bottom_right);
1422 }
1423 path.line_to(next_top_right - curve_width);
1424 if self.corner_radius > 0. {
1425 path.curve_to(next_top_right + curve_height, next_top_right);
1426 }
1427 }
1428 }
1429 } else {
1430 let curve_width = curve_width(line.start_x, line.end_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
1436 let bottom_left = vec2f(line.start_x, bottom_right.y());
1437 path.line_to(bottom_left + curve_width);
1438 if self.corner_radius > 0. {
1439 path.curve_to(bottom_left - curve_height, bottom_left);
1440 }
1441 }
1442 }
1443
1444 if first_line.start_x > last_line.start_x {
1445 let curve_width = curve_width(last_line.start_x, first_line.start_x);
1446 let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
1447 path.line_to(second_top_left + curve_height);
1448 if self.corner_radius > 0. {
1449 path.curve_to(second_top_left + curve_width, second_top_left);
1450 }
1451 let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
1452 path.line_to(first_bottom_left - curve_width);
1453 if self.corner_radius > 0. {
1454 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
1455 }
1456 }
1457
1458 path.line_to(first_top_left + curve_height);
1459 if self.corner_radius > 0. {
1460 path.curve_to(first_top_left + top_curve_width, first_top_left);
1461 }
1462 path.line_to(first_top_right - top_curve_width);
1463
1464 scene.push_path(path.build(self.color, Some(bounds)));
1465 }
1466}
1467
1468fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
1469 delta.powf(1.5) / 100.0
1470}
1471
1472fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
1473 delta.powf(1.2) / 300.0
1474}
1475
1476#[cfg(test)]
1477mod tests {
1478 use std::sync::Arc;
1479
1480 use super::*;
1481 use crate::{
1482 display_map::{BlockDisposition, BlockProperties},
1483 Editor, MultiBuffer,
1484 };
1485 use util::test::sample_text;
1486 use workspace::Settings;
1487
1488 #[gpui::test]
1489 fn test_layout_line_numbers(cx: &mut gpui::MutableAppContext) {
1490 cx.add_app_state(Settings::test(cx));
1491 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
1492 let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1493 Editor::new(EditorMode::Full, buffer, None, None, cx)
1494 });
1495 let element = EditorElement::new(
1496 editor.downgrade(),
1497 editor.read(cx).style(cx),
1498 CursorShape::Bar,
1499 );
1500
1501 let layouts = editor.update(cx, |editor, cx| {
1502 let snapshot = editor.snapshot(cx);
1503 let mut presenter = cx.build_presenter(window_id, 30.);
1504 let mut layout_cx = presenter.build_layout_context(false, cx);
1505 element.layout_line_numbers(0..6, &Default::default(), &snapshot, &mut layout_cx)
1506 });
1507 assert_eq!(layouts.len(), 6);
1508 }
1509
1510 #[gpui::test]
1511 fn test_layout_with_placeholder_text_and_blocks(cx: &mut gpui::MutableAppContext) {
1512 cx.add_app_state(Settings::test(cx));
1513 let buffer = MultiBuffer::build_simple("", cx);
1514 let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1515 Editor::new(EditorMode::Full, buffer, None, None, cx)
1516 });
1517
1518 editor.update(cx, |editor, cx| {
1519 editor.set_placeholder_text("hello", cx);
1520 editor.insert_blocks(
1521 [BlockProperties {
1522 disposition: BlockDisposition::Above,
1523 height: 3,
1524 position: Anchor::min(),
1525 render: Arc::new(|_| Empty::new().boxed()),
1526 }],
1527 cx,
1528 );
1529
1530 // Blur the editor so that it displays placeholder text.
1531 cx.blur();
1532 });
1533
1534 let mut element = EditorElement::new(
1535 editor.downgrade(),
1536 editor.read(cx).style(cx),
1537 CursorShape::Bar,
1538 );
1539
1540 let mut scene = Scene::new(1.0);
1541 let mut presenter = cx.build_presenter(window_id, 30.);
1542 let mut layout_cx = presenter.build_layout_context(false, cx);
1543 let (size, mut state) = element.layout(
1544 SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
1545 &mut layout_cx,
1546 );
1547
1548 assert_eq!(state.line_layouts.len(), 4);
1549 assert_eq!(
1550 state
1551 .line_number_layouts
1552 .iter()
1553 .map(Option::is_some)
1554 .collect::<Vec<_>>(),
1555 &[false, false, false, true]
1556 );
1557
1558 // Don't panic.
1559 let bounds = RectF::new(Default::default(), size);
1560 let mut paint_cx = presenter.build_paint_context(&mut scene, cx);
1561 element.paint(bounds, bounds, &mut state, &mut paint_cx);
1562 }
1563}