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