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