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