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