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 { buffer, .. } => {
683 let style = &self.settings.style.diagnostic_path_header;
684 let font_size =
685 (style.text_scale_factor * self.settings.style.text.font_size).round();
686
687 let mut filename = None;
688 let mut parent_path = None;
689 if let Some(path) = buffer.path() {
690 filename = path.file_name().map(|f| f.to_string_lossy().to_string());
691 parent_path =
692 path.parent().map(|p| p.to_string_lossy().to_string() + "/");
693 }
694
695 Flex::row()
696 .with_child(
697 Label::new(
698 filename.unwrap_or_else(|| "untitled".to_string()),
699 style.filename.text.clone().with_font_size(font_size),
700 )
701 .contained()
702 .with_style(style.filename.container)
703 .boxed(),
704 )
705 .with_children(parent_path.map(|path| {
706 Label::new(path, style.path.text.clone().with_font_size(font_size))
707 .contained()
708 .with_style(style.path.container)
709 .boxed()
710 }))
711 .aligned()
712 .left()
713 .contained()
714 .with_style(style.container)
715 .with_padding_left(gutter_padding + scroll_x * em_width)
716 .expanded()
717 .named("path header block")
718 }
719 };
720
721 element.layout(
722 SizeConstraint {
723 min: Vector2F::zero(),
724 max: vec2f(width, block.height() as f32 * line_height),
725 },
726 cx,
727 );
728 (block_row, element)
729 })
730 .collect()
731 }
732}
733
734impl Element for EditorElement {
735 type LayoutState = LayoutState;
736 type PaintState = PaintState;
737
738 fn layout(
739 &mut self,
740 constraint: SizeConstraint,
741 cx: &mut LayoutContext,
742 ) -> (Vector2F, Self::LayoutState) {
743 let mut size = constraint.max;
744 if size.x().is_infinite() {
745 unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
746 }
747
748 let snapshot = self.snapshot(cx.app);
749 let style = self.settings.style.clone();
750 let line_height = style.text.line_height(cx.font_cache);
751
752 let gutter_padding;
753 let gutter_width;
754 if snapshot.mode == EditorMode::Full {
755 gutter_padding = style.text.em_width(cx.font_cache) * style.gutter_padding_factor;
756 gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
757 } else {
758 gutter_padding = 0.0;
759 gutter_width = 0.0
760 };
761
762 let text_width = size.x() - gutter_width;
763 let text_offset = vec2f(-style.text.descent(cx.font_cache), 0.);
764 let em_width = style.text.em_width(cx.font_cache);
765 let em_advance = style.text.em_advance(cx.font_cache);
766 let overscroll = vec2f(em_width, 0.);
767 let wrap_width = match self.settings.soft_wrap {
768 SoftWrap::None => None,
769 SoftWrap::EditorWidth => Some(text_width - text_offset.x() - overscroll.x() - em_width),
770 SoftWrap::Column(column) => Some(column as f32 * em_advance),
771 };
772 let snapshot = self.update_view(cx.app, |view, cx| {
773 if view.set_wrap_width(wrap_width, cx) {
774 view.snapshot(cx)
775 } else {
776 snapshot
777 }
778 });
779
780 let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
781 if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
782 size.set_y(
783 scroll_height
784 .min(constraint.max_along(Axis::Vertical))
785 .max(constraint.min_along(Axis::Vertical))
786 .min(line_height * max_lines as f32),
787 )
788 } else if size.y().is_infinite() {
789 size.set_y(scroll_height);
790 }
791 let gutter_size = vec2f(gutter_width, size.y());
792 let text_size = vec2f(text_width, size.y());
793
794 let (autoscroll_horizontally, mut snapshot) = self.update_view(cx.app, |view, cx| {
795 let autoscroll_horizontally = view.autoscroll_vertically(size.y(), line_height, cx);
796 let snapshot = view.snapshot(cx);
797 (autoscroll_horizontally, snapshot)
798 });
799
800 let scroll_position = snapshot.scroll_position();
801 let start_row = scroll_position.y() as u32;
802 let scroll_top = scroll_position.y() * line_height;
803 let end_row = ((scroll_top + size.y()) / line_height).ceil() as u32 + 1; // Add 1 to ensure selections bleed off screen
804
805 let start_anchor = if start_row == 0 {
806 Anchor::min()
807 } else {
808 snapshot
809 .buffer_snapshot
810 .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
811 };
812 let end_anchor = if end_row > snapshot.max_point().row() {
813 Anchor::max()
814 } else {
815 snapshot
816 .buffer_snapshot
817 .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
818 };
819
820 let mut selections = HashMap::default();
821 let mut active_rows = BTreeMap::new();
822 let mut highlighted_rows = None;
823 let mut highlighted_ranges = Vec::new();
824 self.update_view(cx.app, |view, cx| {
825 let display_map = view.display_map.update(cx, |map, cx| map.snapshot(cx));
826
827 highlighted_rows = view.highlighted_rows();
828 highlighted_ranges = view.highlighted_ranges_in_range(
829 start_anchor.clone()..end_anchor.clone(),
830 &display_map,
831 );
832
833 let local_selections = view
834 .local_selections_in_range(start_anchor.clone()..end_anchor.clone(), &display_map);
835 for selection in &local_selections {
836 let is_empty = selection.start == selection.end;
837 let selection_start = snapshot.prev_line_boundary(selection.start).1;
838 let selection_end = snapshot.next_line_boundary(selection.end).1;
839 for row in cmp::max(selection_start.row(), start_row)
840 ..=cmp::min(selection_end.row(), end_row)
841 {
842 let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
843 *contains_non_empty_selection |= !is_empty;
844 }
845 }
846 selections.insert(
847 view.replica_id(cx),
848 local_selections
849 .into_iter()
850 .map(|selection| crate::Selection {
851 id: selection.id,
852 goal: selection.goal,
853 reversed: selection.reversed,
854 start: selection.start.to_display_point(&display_map),
855 end: selection.end.to_display_point(&display_map),
856 })
857 .collect(),
858 );
859
860 for (replica_id, selection) in display_map
861 .buffer_snapshot
862 .remote_selections_in_range(&(start_anchor..end_anchor))
863 {
864 selections
865 .entry(replica_id)
866 .or_insert(Vec::new())
867 .push(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 }
875 });
876
877 let line_number_layouts =
878 self.layout_line_numbers(start_row..end_row, &active_rows, &snapshot, cx);
879
880 let mut max_visible_line_width = 0.0;
881 let line_layouts = self.layout_lines(start_row..end_row, &mut snapshot, cx);
882 for line in &line_layouts {
883 if line.width() > max_visible_line_width {
884 max_visible_line_width = line.width();
885 }
886 }
887
888 let style = self.settings.style.clone();
889 let longest_line_width = layout_line(
890 snapshot.longest_row(),
891 &snapshot,
892 &style,
893 cx.text_layout_cache,
894 )
895 .width();
896 let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
897 let em_width = style.text.em_width(cx.font_cache);
898 let max_row = snapshot.max_point().row();
899 let scroll_max = vec2f(
900 ((scroll_width - text_size.x()) / em_width).max(0.0),
901 max_row.saturating_sub(1) as f32,
902 );
903
904 let mut completions = None;
905 self.update_view(cx.app, |view, cx| {
906 let clamped = view.clamp_scroll_left(scroll_max.x());
907 let autoscrolled;
908 if autoscroll_horizontally {
909 autoscrolled = view.autoscroll_horizontally(
910 start_row,
911 text_size.x(),
912 scroll_width,
913 em_width,
914 &line_layouts,
915 cx,
916 );
917 } else {
918 autoscrolled = false;
919 }
920
921 if clamped || autoscrolled {
922 snapshot = view.snapshot(cx);
923 }
924
925 if view.showing_context_menu() {
926 let newest_selection_head = view
927 .newest_selection::<usize>(&snapshot.buffer_snapshot)
928 .head()
929 .to_display_point(&snapshot);
930
931 if (start_row..end_row).contains(&newest_selection_head.row()) {
932 let list = view.render_context_menu(cx).unwrap();
933 completions = Some((newest_selection_head, list));
934 }
935 }
936 });
937
938 if let Some((_, completions_list)) = completions.as_mut() {
939 completions_list.layout(
940 SizeConstraint {
941 min: Vector2F::zero(),
942 max: vec2f(
943 f32::INFINITY,
944 (12. * line_height).min((size.y() - line_height) / 2.),
945 ),
946 },
947 cx,
948 );
949 }
950
951 let blocks = self.layout_blocks(
952 start_row..end_row,
953 &snapshot,
954 size.x().max(scroll_width + gutter_width),
955 gutter_padding,
956 gutter_width,
957 em_width,
958 gutter_width + text_offset.x(),
959 line_height,
960 &style,
961 &line_layouts,
962 cx,
963 );
964
965 (
966 size,
967 LayoutState {
968 size,
969 scroll_max,
970 gutter_size,
971 gutter_padding,
972 text_size,
973 text_offset,
974 snapshot,
975 active_rows,
976 highlighted_rows,
977 highlighted_ranges,
978 line_layouts,
979 line_number_layouts,
980 blocks,
981 line_height,
982 em_width,
983 em_advance,
984 selections,
985 completions,
986 },
987 )
988 }
989
990 fn paint(
991 &mut self,
992 bounds: RectF,
993 visible_bounds: RectF,
994 layout: &mut Self::LayoutState,
995 cx: &mut PaintContext,
996 ) -> Self::PaintState {
997 cx.scene.push_layer(Some(bounds));
998
999 let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
1000 let text_bounds = RectF::new(
1001 bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
1002 layout.text_size,
1003 );
1004
1005 self.paint_background(gutter_bounds, text_bounds, layout, cx);
1006 if layout.gutter_size.x() > 0. {
1007 self.paint_gutter(gutter_bounds, visible_bounds, layout, cx);
1008 }
1009 self.paint_text(text_bounds, visible_bounds, layout, cx);
1010
1011 if !layout.blocks.is_empty() {
1012 cx.scene.push_layer(Some(bounds));
1013 self.paint_blocks(bounds, visible_bounds, layout, cx);
1014 cx.scene.pop_layer();
1015 }
1016
1017 cx.scene.pop_layer();
1018
1019 PaintState {
1020 bounds,
1021 gutter_bounds,
1022 text_bounds,
1023 }
1024 }
1025
1026 fn dispatch_event(
1027 &mut self,
1028 event: &Event,
1029 _: RectF,
1030 layout: &mut LayoutState,
1031 paint: &mut PaintState,
1032 cx: &mut EventContext,
1033 ) -> bool {
1034 if let Some((_, completion_list)) = &mut layout.completions {
1035 if completion_list.dispatch_event(event, cx) {
1036 return true;
1037 }
1038 }
1039
1040 match event {
1041 Event::LeftMouseDown {
1042 position,
1043 alt,
1044 shift,
1045 click_count,
1046 ..
1047 } => self.mouse_down(*position, *alt, *shift, *click_count, layout, paint, cx),
1048 Event::LeftMouseUp { position } => self.mouse_up(*position, cx),
1049 Event::LeftMouseDragged { position } => {
1050 self.mouse_dragged(*position, layout, paint, cx)
1051 }
1052 Event::ScrollWheel {
1053 position,
1054 delta,
1055 precise,
1056 } => self.scroll(*position, *delta, *precise, layout, paint, cx),
1057 Event::KeyDown {
1058 chars, keystroke, ..
1059 } => self.key_down(chars, keystroke, cx),
1060 _ => false,
1061 }
1062 }
1063
1064 fn debug(
1065 &self,
1066 bounds: RectF,
1067 _: &Self::LayoutState,
1068 _: &Self::PaintState,
1069 _: &gpui::DebugContext,
1070 ) -> json::Value {
1071 json!({
1072 "type": "BufferElement",
1073 "bounds": bounds.to_json()
1074 })
1075 }
1076}
1077
1078pub struct LayoutState {
1079 size: Vector2F,
1080 scroll_max: Vector2F,
1081 gutter_size: Vector2F,
1082 gutter_padding: f32,
1083 text_size: Vector2F,
1084 snapshot: EditorSnapshot,
1085 active_rows: BTreeMap<u32, bool>,
1086 highlighted_rows: Option<Range<u32>>,
1087 line_layouts: Vec<text_layout::Line>,
1088 line_number_layouts: Vec<Option<text_layout::Line>>,
1089 blocks: Vec<(u32, ElementBox)>,
1090 line_height: f32,
1091 em_width: f32,
1092 em_advance: f32,
1093 highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
1094 selections: HashMap<ReplicaId, Vec<text::Selection<DisplayPoint>>>,
1095 text_offset: Vector2F,
1096 completions: Option<(DisplayPoint, ElementBox)>,
1097}
1098
1099fn layout_line(
1100 row: u32,
1101 snapshot: &EditorSnapshot,
1102 style: &EditorStyle,
1103 layout_cache: &TextLayoutCache,
1104) -> text_layout::Line {
1105 let mut line = snapshot.line(row);
1106
1107 if line.len() > MAX_LINE_LEN {
1108 let mut len = MAX_LINE_LEN;
1109 while !line.is_char_boundary(len) {
1110 len -= 1;
1111 }
1112 line.truncate(len);
1113 }
1114
1115 layout_cache.layout_str(
1116 &line,
1117 style.text.font_size,
1118 &[(
1119 snapshot.line_len(row) as usize,
1120 RunStyle {
1121 font_id: style.text.font_id,
1122 color: Color::black(),
1123 underline: None,
1124 },
1125 )],
1126 )
1127}
1128
1129pub struct PaintState {
1130 bounds: RectF,
1131 gutter_bounds: RectF,
1132 text_bounds: RectF,
1133}
1134
1135impl PaintState {
1136 fn point_for_position(
1137 &self,
1138 snapshot: &EditorSnapshot,
1139 layout: &LayoutState,
1140 position: Vector2F,
1141 ) -> (DisplayPoint, u32) {
1142 let scroll_position = snapshot.scroll_position();
1143 let position = position - self.text_bounds.origin();
1144 let y = position.y().max(0.0).min(layout.size.y());
1145 let row = ((y / layout.line_height) + scroll_position.y()) as u32;
1146 let row = cmp::min(row, snapshot.max_point().row());
1147 let line = &layout.line_layouts[(row - scroll_position.y() as u32) as usize];
1148 let x = position.x() + (scroll_position.x() * layout.em_width);
1149
1150 let column = if x >= 0.0 {
1151 line.index_for_x(x)
1152 .map(|ix| ix as u32)
1153 .unwrap_or_else(|| snapshot.line_len(row))
1154 } else {
1155 0
1156 };
1157 let overshoot = (0f32.max(x - line.width()) / layout.em_advance) as u32;
1158
1159 (DisplayPoint::new(row, column), overshoot)
1160 }
1161}
1162
1163struct Cursor {
1164 origin: Vector2F,
1165 line_height: f32,
1166 color: Color,
1167}
1168
1169impl Cursor {
1170 fn paint(&self, cx: &mut PaintContext) {
1171 cx.scene.push_quad(Quad {
1172 bounds: RectF::new(self.origin, vec2f(2.0, self.line_height)),
1173 background: Some(self.color),
1174 border: Border::new(0., Color::black()),
1175 corner_radius: 0.,
1176 });
1177 }
1178}
1179
1180#[derive(Debug)]
1181struct HighlightedRange {
1182 start_y: f32,
1183 line_height: f32,
1184 lines: Vec<HighlightedRangeLine>,
1185 color: Color,
1186 corner_radius: f32,
1187}
1188
1189#[derive(Debug)]
1190struct HighlightedRangeLine {
1191 start_x: f32,
1192 end_x: f32,
1193}
1194
1195impl HighlightedRange {
1196 fn paint(&self, bounds: RectF, scene: &mut Scene) {
1197 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
1198 self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
1199 self.paint_lines(
1200 self.start_y + self.line_height,
1201 &self.lines[1..],
1202 bounds,
1203 scene,
1204 );
1205 } else {
1206 self.paint_lines(self.start_y, &self.lines, bounds, scene);
1207 }
1208 }
1209
1210 fn paint_lines(
1211 &self,
1212 start_y: f32,
1213 lines: &[HighlightedRangeLine],
1214 bounds: RectF,
1215 scene: &mut Scene,
1216 ) {
1217 if lines.is_empty() {
1218 return;
1219 }
1220
1221 let mut path = PathBuilder::new();
1222 let first_line = lines.first().unwrap();
1223 let last_line = lines.last().unwrap();
1224
1225 let first_top_left = vec2f(first_line.start_x, start_y);
1226 let first_top_right = vec2f(first_line.end_x, start_y);
1227
1228 let curve_height = vec2f(0., self.corner_radius);
1229 let curve_width = |start_x: f32, end_x: f32| {
1230 let max = (end_x - start_x) / 2.;
1231 let width = if max < self.corner_radius {
1232 max
1233 } else {
1234 self.corner_radius
1235 };
1236
1237 vec2f(width, 0.)
1238 };
1239
1240 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
1241 path.reset(first_top_right - top_curve_width);
1242 path.curve_to(first_top_right + curve_height, first_top_right);
1243
1244 let mut iter = lines.iter().enumerate().peekable();
1245 while let Some((ix, line)) = iter.next() {
1246 let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
1247
1248 if let Some((_, next_line)) = iter.peek() {
1249 let next_top_right = vec2f(next_line.end_x, bottom_right.y());
1250
1251 match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
1252 Ordering::Equal => {
1253 path.line_to(bottom_right);
1254 }
1255 Ordering::Less => {
1256 let curve_width = curve_width(next_top_right.x(), bottom_right.x());
1257 path.line_to(bottom_right - curve_height);
1258 if self.corner_radius > 0. {
1259 path.curve_to(bottom_right - curve_width, bottom_right);
1260 }
1261 path.line_to(next_top_right + curve_width);
1262 if self.corner_radius > 0. {
1263 path.curve_to(next_top_right + curve_height, next_top_right);
1264 }
1265 }
1266 Ordering::Greater => {
1267 let curve_width = curve_width(bottom_right.x(), next_top_right.x());
1268 path.line_to(bottom_right - curve_height);
1269 if self.corner_radius > 0. {
1270 path.curve_to(bottom_right + curve_width, bottom_right);
1271 }
1272 path.line_to(next_top_right - curve_width);
1273 if self.corner_radius > 0. {
1274 path.curve_to(next_top_right + curve_height, next_top_right);
1275 }
1276 }
1277 }
1278 } else {
1279 let curve_width = curve_width(line.start_x, line.end_x);
1280 path.line_to(bottom_right - curve_height);
1281 if self.corner_radius > 0. {
1282 path.curve_to(bottom_right - curve_width, bottom_right);
1283 }
1284
1285 let bottom_left = vec2f(line.start_x, bottom_right.y());
1286 path.line_to(bottom_left + curve_width);
1287 if self.corner_radius > 0. {
1288 path.curve_to(bottom_left - curve_height, bottom_left);
1289 }
1290 }
1291 }
1292
1293 if first_line.start_x > last_line.start_x {
1294 let curve_width = curve_width(last_line.start_x, first_line.start_x);
1295 let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
1296 path.line_to(second_top_left + curve_height);
1297 if self.corner_radius > 0. {
1298 path.curve_to(second_top_left + curve_width, second_top_left);
1299 }
1300 let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
1301 path.line_to(first_bottom_left - curve_width);
1302 if self.corner_radius > 0. {
1303 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
1304 }
1305 }
1306
1307 path.line_to(first_top_left + curve_height);
1308 if self.corner_radius > 0. {
1309 path.curve_to(first_top_left + top_curve_width, first_top_left);
1310 }
1311 path.line_to(first_top_right - top_curve_width);
1312
1313 scene.push_path(path.build(self.color, Some(bounds)));
1314 }
1315}
1316
1317fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
1318 delta.powf(1.5) / 100.0
1319}
1320
1321fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
1322 delta.powf(1.2) / 300.0
1323}
1324
1325#[cfg(test)]
1326mod tests {
1327 use super::*;
1328 use crate::{Editor, EditorSettings, MultiBuffer};
1329 use std::sync::Arc;
1330 use util::test::sample_text;
1331
1332 #[gpui::test]
1333 fn test_layout_line_numbers(cx: &mut gpui::MutableAppContext) {
1334 let settings = EditorSettings::test(cx);
1335 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
1336 let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1337 Editor::for_buffer(
1338 buffer,
1339 {
1340 let settings = settings.clone();
1341 Arc::new(move |_| settings.clone())
1342 },
1343 None,
1344 cx,
1345 )
1346 });
1347 let element = EditorElement::new(editor.downgrade(), settings);
1348
1349 let layouts = editor.update(cx, |editor, cx| {
1350 let snapshot = editor.snapshot(cx);
1351 let mut presenter = cx.build_presenter(window_id, 30.);
1352 let mut layout_cx = presenter.build_layout_context(false, cx);
1353 element.layout_line_numbers(0..6, &Default::default(), &snapshot, &mut layout_cx)
1354 });
1355 assert_eq!(layouts.len(), 6);
1356 }
1357}