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 context_menu = view.render_context_menu(newest_selection_head, cx);
959 }
960
961 code_actions_indicator = view
962 .render_code_actions_indicator(cx)
963 .map(|indicator| (newest_selection_head.row(), indicator));
964 }
965 });
966
967 if let Some((_, context_menu)) = context_menu.as_mut() {
968 context_menu.layout(
969 SizeConstraint {
970 min: Vector2F::zero(),
971 max: vec2f(
972 f32::INFINITY,
973 (12. * line_height).min((size.y() - line_height) / 2.),
974 ),
975 },
976 cx,
977 );
978 }
979
980 if let Some((_, indicator)) = code_actions_indicator.as_mut() {
981 indicator.layout(
982 SizeConstraint::strict_along(Axis::Vertical, line_height * 0.618),
983 cx,
984 );
985 }
986
987 let blocks = self.layout_blocks(
988 start_row..end_row,
989 &snapshot,
990 size.x().max(scroll_width + gutter_width),
991 gutter_padding,
992 gutter_width,
993 em_width,
994 gutter_width + text_offset.x(),
995 line_height,
996 &style,
997 &line_layouts,
998 cx,
999 );
1000
1001 (
1002 size,
1003 LayoutState {
1004 size,
1005 scroll_max,
1006 gutter_size,
1007 gutter_padding,
1008 text_size,
1009 text_offset,
1010 snapshot,
1011 active_rows,
1012 highlighted_rows,
1013 highlighted_ranges,
1014 line_layouts,
1015 line_number_layouts,
1016 blocks,
1017 line_height,
1018 em_width,
1019 em_advance,
1020 selections,
1021 context_menu,
1022 code_actions_indicator,
1023 },
1024 )
1025 }
1026
1027 fn paint(
1028 &mut self,
1029 bounds: RectF,
1030 visible_bounds: RectF,
1031 layout: &mut Self::LayoutState,
1032 cx: &mut PaintContext,
1033 ) -> Self::PaintState {
1034 cx.scene.push_layer(Some(bounds));
1035
1036 let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
1037 let text_bounds = RectF::new(
1038 bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
1039 layout.text_size,
1040 );
1041
1042 self.paint_background(gutter_bounds, text_bounds, layout, cx);
1043 if layout.gutter_size.x() > 0. {
1044 self.paint_gutter(gutter_bounds, visible_bounds, layout, cx);
1045 }
1046 self.paint_text(text_bounds, visible_bounds, layout, cx);
1047
1048 if !layout.blocks.is_empty() {
1049 cx.scene.push_layer(Some(bounds));
1050 self.paint_blocks(bounds, visible_bounds, layout, cx);
1051 cx.scene.pop_layer();
1052 }
1053
1054 cx.scene.pop_layer();
1055
1056 PaintState {
1057 bounds,
1058 gutter_bounds,
1059 text_bounds,
1060 }
1061 }
1062
1063 fn dispatch_event(
1064 &mut self,
1065 event: &Event,
1066 _: RectF,
1067 layout: &mut LayoutState,
1068 paint: &mut PaintState,
1069 cx: &mut EventContext,
1070 ) -> bool {
1071 if let Some((_, context_menu)) = &mut layout.context_menu {
1072 if context_menu.dispatch_event(event, cx) {
1073 return true;
1074 }
1075 }
1076
1077 if let Some((_, indicator)) = &mut layout.code_actions_indicator {
1078 if indicator.dispatch_event(event, cx) {
1079 return true;
1080 }
1081 }
1082
1083 match event {
1084 Event::LeftMouseDown {
1085 position,
1086 alt,
1087 shift,
1088 click_count,
1089 ..
1090 } => self.mouse_down(*position, *alt, *shift, *click_count, layout, paint, cx),
1091 Event::LeftMouseUp { position } => self.mouse_up(*position, cx),
1092 Event::LeftMouseDragged { position } => {
1093 self.mouse_dragged(*position, layout, paint, cx)
1094 }
1095 Event::ScrollWheel {
1096 position,
1097 delta,
1098 precise,
1099 } => self.scroll(*position, *delta, *precise, layout, paint, cx),
1100 Event::KeyDown {
1101 chars, keystroke, ..
1102 } => self.key_down(chars, keystroke, cx),
1103 _ => false,
1104 }
1105 }
1106
1107 fn debug(
1108 &self,
1109 bounds: RectF,
1110 _: &Self::LayoutState,
1111 _: &Self::PaintState,
1112 _: &gpui::DebugContext,
1113 ) -> json::Value {
1114 json!({
1115 "type": "BufferElement",
1116 "bounds": bounds.to_json()
1117 })
1118 }
1119}
1120
1121pub struct LayoutState {
1122 size: Vector2F,
1123 scroll_max: Vector2F,
1124 gutter_size: Vector2F,
1125 gutter_padding: f32,
1126 text_size: Vector2F,
1127 snapshot: EditorSnapshot,
1128 active_rows: BTreeMap<u32, bool>,
1129 highlighted_rows: Option<Range<u32>>,
1130 line_layouts: Vec<text_layout::Line>,
1131 line_number_layouts: Vec<Option<text_layout::Line>>,
1132 blocks: Vec<(u32, ElementBox)>,
1133 line_height: f32,
1134 em_width: f32,
1135 em_advance: f32,
1136 highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
1137 selections: HashMap<ReplicaId, Vec<text::Selection<DisplayPoint>>>,
1138 text_offset: Vector2F,
1139 context_menu: Option<(DisplayPoint, ElementBox)>,
1140 code_actions_indicator: Option<(u32, ElementBox)>,
1141}
1142
1143fn layout_line(
1144 row: u32,
1145 snapshot: &EditorSnapshot,
1146 style: &EditorStyle,
1147 layout_cache: &TextLayoutCache,
1148) -> text_layout::Line {
1149 let mut line = snapshot.line(row);
1150
1151 if line.len() > MAX_LINE_LEN {
1152 let mut len = MAX_LINE_LEN;
1153 while !line.is_char_boundary(len) {
1154 len -= 1;
1155 }
1156 line.truncate(len);
1157 }
1158
1159 layout_cache.layout_str(
1160 &line,
1161 style.text.font_size,
1162 &[(
1163 snapshot.line_len(row) as usize,
1164 RunStyle {
1165 font_id: style.text.font_id,
1166 color: Color::black(),
1167 underline: None,
1168 },
1169 )],
1170 )
1171}
1172
1173pub struct PaintState {
1174 bounds: RectF,
1175 gutter_bounds: RectF,
1176 text_bounds: RectF,
1177}
1178
1179impl PaintState {
1180 fn point_for_position(
1181 &self,
1182 snapshot: &EditorSnapshot,
1183 layout: &LayoutState,
1184 position: Vector2F,
1185 ) -> (DisplayPoint, u32) {
1186 let scroll_position = snapshot.scroll_position();
1187 let position = position - self.text_bounds.origin();
1188 let y = position.y().max(0.0).min(layout.size.y());
1189 let row = ((y / layout.line_height) + scroll_position.y()) as u32;
1190 let row = cmp::min(row, snapshot.max_point().row());
1191 let line = &layout.line_layouts[(row - scroll_position.y() as u32) as usize];
1192 let x = position.x() + (scroll_position.x() * layout.em_width);
1193
1194 let column = if x >= 0.0 {
1195 line.index_for_x(x)
1196 .map(|ix| ix as u32)
1197 .unwrap_or_else(|| snapshot.line_len(row))
1198 } else {
1199 0
1200 };
1201 let overshoot = (0f32.max(x - line.width()) / layout.em_advance) as u32;
1202
1203 (DisplayPoint::new(row, column), overshoot)
1204 }
1205}
1206
1207struct Cursor {
1208 origin: Vector2F,
1209 line_height: f32,
1210 color: Color,
1211}
1212
1213impl Cursor {
1214 fn paint(&self, cx: &mut PaintContext) {
1215 cx.scene.push_quad(Quad {
1216 bounds: RectF::new(self.origin, vec2f(2.0, self.line_height)),
1217 background: Some(self.color),
1218 border: Border::new(0., Color::black()),
1219 corner_radius: 0.,
1220 });
1221 }
1222}
1223
1224#[derive(Debug)]
1225struct HighlightedRange {
1226 start_y: f32,
1227 line_height: f32,
1228 lines: Vec<HighlightedRangeLine>,
1229 color: Color,
1230 corner_radius: f32,
1231}
1232
1233#[derive(Debug)]
1234struct HighlightedRangeLine {
1235 start_x: f32,
1236 end_x: f32,
1237}
1238
1239impl HighlightedRange {
1240 fn paint(&self, bounds: RectF, scene: &mut Scene) {
1241 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
1242 self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
1243 self.paint_lines(
1244 self.start_y + self.line_height,
1245 &self.lines[1..],
1246 bounds,
1247 scene,
1248 );
1249 } else {
1250 self.paint_lines(self.start_y, &self.lines, bounds, scene);
1251 }
1252 }
1253
1254 fn paint_lines(
1255 &self,
1256 start_y: f32,
1257 lines: &[HighlightedRangeLine],
1258 bounds: RectF,
1259 scene: &mut Scene,
1260 ) {
1261 if lines.is_empty() {
1262 return;
1263 }
1264
1265 let mut path = PathBuilder::new();
1266 let first_line = lines.first().unwrap();
1267 let last_line = lines.last().unwrap();
1268
1269 let first_top_left = vec2f(first_line.start_x, start_y);
1270 let first_top_right = vec2f(first_line.end_x, start_y);
1271
1272 let curve_height = vec2f(0., self.corner_radius);
1273 let curve_width = |start_x: f32, end_x: f32| {
1274 let max = (end_x - start_x) / 2.;
1275 let width = if max < self.corner_radius {
1276 max
1277 } else {
1278 self.corner_radius
1279 };
1280
1281 vec2f(width, 0.)
1282 };
1283
1284 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
1285 path.reset(first_top_right - top_curve_width);
1286 path.curve_to(first_top_right + curve_height, first_top_right);
1287
1288 let mut iter = lines.iter().enumerate().peekable();
1289 while let Some((ix, line)) = iter.next() {
1290 let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
1291
1292 if let Some((_, next_line)) = iter.peek() {
1293 let next_top_right = vec2f(next_line.end_x, bottom_right.y());
1294
1295 match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
1296 Ordering::Equal => {
1297 path.line_to(bottom_right);
1298 }
1299 Ordering::Less => {
1300 let curve_width = curve_width(next_top_right.x(), bottom_right.x());
1301 path.line_to(bottom_right - curve_height);
1302 if self.corner_radius > 0. {
1303 path.curve_to(bottom_right - curve_width, bottom_right);
1304 }
1305 path.line_to(next_top_right + curve_width);
1306 if self.corner_radius > 0. {
1307 path.curve_to(next_top_right + curve_height, next_top_right);
1308 }
1309 }
1310 Ordering::Greater => {
1311 let curve_width = curve_width(bottom_right.x(), next_top_right.x());
1312 path.line_to(bottom_right - curve_height);
1313 if self.corner_radius > 0. {
1314 path.curve_to(bottom_right + curve_width, bottom_right);
1315 }
1316 path.line_to(next_top_right - curve_width);
1317 if self.corner_radius > 0. {
1318 path.curve_to(next_top_right + curve_height, next_top_right);
1319 }
1320 }
1321 }
1322 } else {
1323 let curve_width = curve_width(line.start_x, line.end_x);
1324 path.line_to(bottom_right - curve_height);
1325 if self.corner_radius > 0. {
1326 path.curve_to(bottom_right - curve_width, bottom_right);
1327 }
1328
1329 let bottom_left = vec2f(line.start_x, bottom_right.y());
1330 path.line_to(bottom_left + curve_width);
1331 if self.corner_radius > 0. {
1332 path.curve_to(bottom_left - curve_height, bottom_left);
1333 }
1334 }
1335 }
1336
1337 if first_line.start_x > last_line.start_x {
1338 let curve_width = curve_width(last_line.start_x, first_line.start_x);
1339 let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
1340 path.line_to(second_top_left + curve_height);
1341 if self.corner_radius > 0. {
1342 path.curve_to(second_top_left + curve_width, second_top_left);
1343 }
1344 let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
1345 path.line_to(first_bottom_left - curve_width);
1346 if self.corner_radius > 0. {
1347 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
1348 }
1349 }
1350
1351 path.line_to(first_top_left + curve_height);
1352 if self.corner_radius > 0. {
1353 path.curve_to(first_top_left + top_curve_width, first_top_left);
1354 }
1355 path.line_to(first_top_right - top_curve_width);
1356
1357 scene.push_path(path.build(self.color, Some(bounds)));
1358 }
1359}
1360
1361fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
1362 delta.powf(1.5) / 100.0
1363}
1364
1365fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
1366 delta.powf(1.2) / 300.0
1367}
1368
1369#[cfg(test)]
1370mod tests {
1371 use super::*;
1372 use crate::{Editor, EditorSettings, MultiBuffer};
1373 use std::sync::Arc;
1374 use util::test::sample_text;
1375
1376 #[gpui::test]
1377 fn test_layout_line_numbers(cx: &mut gpui::MutableAppContext) {
1378 let settings = EditorSettings::test(cx);
1379 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
1380 let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1381 Editor::for_buffer(
1382 buffer,
1383 {
1384 let settings = settings.clone();
1385 Arc::new(move |_| settings.clone())
1386 },
1387 None,
1388 cx,
1389 )
1390 });
1391 let element = EditorElement::new(editor.downgrade(), settings);
1392
1393 let layouts = editor.update(cx, |editor, cx| {
1394 let snapshot = editor.snapshot(cx);
1395 let mut presenter = cx.build_presenter(window_id, 30.);
1396 let mut layout_cx = presenter.build_layout_context(false, cx);
1397 element.layout_line_numbers(0..6, &Default::default(), &snapshot, &mut layout_cx)
1398 });
1399 assert_eq!(layouts.len(), 6);
1400 }
1401}