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