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