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