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 text_x: f32,
628 line_height: f32,
629 style: &EditorStyle,
630 line_layouts: &[text_layout::Line],
631 cx: &mut LayoutContext,
632 ) -> Vec<(u32, ElementBox)> {
633 snapshot
634 .blocks_in_range(rows.clone())
635 .map(|(start_row, block)| {
636 let anchor_row = block
637 .position()
638 .to_point(&snapshot.buffer_snapshot)
639 .to_display_point(snapshot)
640 .row();
641
642 let anchor_x = text_x + if rows.contains(&anchor_row) {
643 line_layouts[(anchor_row - rows.start) as usize]
644 .x_for_index(block.column() as usize)
645 } else {
646 layout_line(anchor_row, snapshot, style, cx.text_layout_cache)
647 .x_for_index(block.column() as usize)
648 };
649
650 let mut element = block.render(&BlockContext { cx, anchor_x });
651 element.layout(
652 SizeConstraint {
653 min: Vector2F::zero(),
654 max: vec2f(width, block.height() as f32 * line_height),
655 },
656 cx,
657 );
658 (start_row, element)
659 })
660 .collect()
661 }
662}
663
664impl Element for EditorElement {
665 type LayoutState = Option<LayoutState>;
666 type PaintState = Option<PaintState>;
667
668 fn layout(
669 &mut self,
670 constraint: SizeConstraint,
671 cx: &mut LayoutContext,
672 ) -> (Vector2F, Self::LayoutState) {
673 let mut size = constraint.max;
674 if size.x().is_infinite() {
675 unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
676 }
677
678 let snapshot = self.snapshot(cx.app);
679 let style = self.settings.style.clone();
680 let line_height = style.text.line_height(cx.font_cache);
681
682 let gutter_padding;
683 let gutter_width;
684 if snapshot.mode == EditorMode::Full {
685 gutter_padding = style.text.em_width(cx.font_cache);
686 gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
687 } else {
688 gutter_padding = 0.0;
689 gutter_width = 0.0
690 };
691
692 let text_width = size.x() - gutter_width;
693 let text_offset = vec2f(-style.text.descent(cx.font_cache), 0.);
694 let em_width = style.text.em_width(cx.font_cache);
695 let em_advance = style.text.em_advance(cx.font_cache);
696 let overscroll = vec2f(em_width, 0.);
697 let wrap_width = match self.settings.soft_wrap {
698 SoftWrap::None => None,
699 SoftWrap::EditorWidth => Some(text_width - text_offset.x() - overscroll.x() - em_width),
700 SoftWrap::Column(column) => Some(column as f32 * em_advance),
701 };
702 let snapshot = self.update_view(cx.app, |view, cx| {
703 if view.set_wrap_width(wrap_width, cx) {
704 view.snapshot(cx)
705 } else {
706 snapshot
707 }
708 });
709
710 let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
711 if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
712 size.set_y(
713 scroll_height
714 .min(constraint.max_along(Axis::Vertical))
715 .max(constraint.min_along(Axis::Vertical))
716 .min(line_height * max_lines as f32),
717 )
718 } else if size.y().is_infinite() {
719 size.set_y(scroll_height);
720 }
721 let gutter_size = vec2f(gutter_width, size.y());
722 let text_size = vec2f(text_width, size.y());
723
724 let (autoscroll_horizontally, mut snapshot) = self.update_view(cx.app, |view, cx| {
725 let autoscroll_horizontally = view.autoscroll_vertically(size.y(), line_height, cx);
726 let snapshot = view.snapshot(cx);
727 (autoscroll_horizontally, snapshot)
728 });
729
730 let scroll_position = snapshot.scroll_position();
731 let start_row = scroll_position.y() as u32;
732 let scroll_top = scroll_position.y() * line_height;
733 let end_row = ((scroll_top + size.y()) / line_height).ceil() as u32 + 1; // Add 1 to ensure selections bleed off screen
734
735 let start_anchor = if start_row == 0 {
736 Anchor::min()
737 } else {
738 snapshot
739 .buffer_snapshot
740 .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
741 };
742 let end_anchor = if end_row > snapshot.max_point().row() {
743 Anchor::max()
744 } else {
745 snapshot
746 .buffer_snapshot
747 .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
748 };
749
750 let mut selections = HashMap::default();
751 let mut active_rows = BTreeMap::new();
752 let mut highlighted_row = None;
753 self.update_view(cx.app, |view, cx| {
754 highlighted_row = view.highlighted_row();
755 let display_map = view.display_map.update(cx, |map, cx| map.snapshot(cx));
756
757 let local_selections = view
758 .local_selections_in_range(start_anchor.clone()..end_anchor.clone(), &display_map);
759 for selection in &local_selections {
760 let is_empty = selection.start == selection.end;
761 let selection_start = snapshot.prev_line_boundary(selection.start).1;
762 let selection_end = snapshot.next_line_boundary(selection.end).1;
763 for row in cmp::max(selection_start.row(), start_row)
764 ..=cmp::min(selection_end.row(), end_row)
765 {
766 let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
767 *contains_non_empty_selection |= !is_empty;
768 }
769 }
770 selections.insert(
771 view.replica_id(cx),
772 local_selections
773 .into_iter()
774 .map(|selection| crate::Selection {
775 id: selection.id,
776 goal: selection.goal,
777 reversed: selection.reversed,
778 start: selection.start.to_display_point(&display_map),
779 end: selection.end.to_display_point(&display_map),
780 })
781 .collect(),
782 );
783
784 for (replica_id, selection) in display_map
785 .buffer_snapshot
786 .remote_selections_in_range(&(start_anchor..end_anchor))
787 {
788 selections
789 .entry(replica_id)
790 .or_insert(Vec::new())
791 .push(crate::Selection {
792 id: selection.id,
793 goal: selection.goal,
794 reversed: selection.reversed,
795 start: selection.start.to_display_point(&display_map),
796 end: selection.end.to_display_point(&display_map),
797 });
798 }
799 });
800
801 let line_number_layouts = self.layout_rows(start_row..end_row, &active_rows, &snapshot, cx);
802
803 let mut max_visible_line_width = 0.0;
804 let line_layouts = self.layout_lines(start_row..end_row, &mut snapshot, cx);
805 for line in &line_layouts {
806 if line.width() > max_visible_line_width {
807 max_visible_line_width = line.width();
808 }
809 }
810
811 let blocks = self.layout_blocks(
812 start_row..end_row,
813 &snapshot,
814 size.x(),
815 gutter_width + text_offset.x(),
816 line_height,
817 &style,
818 &line_layouts,
819 cx,
820 );
821
822 let mut layout = LayoutState {
823 size,
824 gutter_size,
825 gutter_padding,
826 text_size,
827 overscroll,
828 text_offset,
829 snapshot,
830 style: self.settings.style.clone(),
831 active_rows,
832 highlighted_row,
833 line_layouts,
834 line_number_layouts,
835 blocks,
836 line_height,
837 em_width,
838 em_advance,
839 selections,
840 max_visible_line_width,
841 };
842
843 let scroll_max = layout.scroll_max(cx.font_cache, cx.text_layout_cache).x();
844 let scroll_width = layout.scroll_width(cx.text_layout_cache);
845 let max_glyph_width = style.text.em_width(&cx.font_cache);
846 self.update_view(cx.app, |view, cx| {
847 let clamped = view.clamp_scroll_left(scroll_max);
848 let autoscrolled;
849 if autoscroll_horizontally {
850 autoscrolled = view.autoscroll_horizontally(
851 start_row,
852 layout.text_size.x(),
853 scroll_width,
854 max_glyph_width,
855 &layout.line_layouts,
856 cx,
857 );
858 } else {
859 autoscrolled = false;
860 }
861
862 if clamped || autoscrolled {
863 layout.snapshot = view.snapshot(cx);
864 }
865 });
866
867 (size, Some(layout))
868 }
869
870 fn paint(
871 &mut self,
872 bounds: RectF,
873 visible_bounds: RectF,
874 layout: &mut Self::LayoutState,
875 cx: &mut PaintContext,
876 ) -> Self::PaintState {
877 if let Some(layout) = layout {
878 cx.scene.push_layer(Some(bounds));
879
880 let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
881 let text_bounds = RectF::new(
882 bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
883 layout.text_size,
884 );
885
886 self.paint_background(gutter_bounds, text_bounds, layout, cx);
887 if layout.gutter_size.x() > 0. {
888 self.paint_gutter(gutter_bounds, visible_bounds, layout, cx);
889 }
890 self.paint_text(text_bounds, visible_bounds, layout, cx);
891 self.paint_blocks(bounds, visible_bounds, layout, cx);
892
893 cx.scene.pop_layer();
894
895 Some(PaintState {
896 bounds,
897 gutter_bounds,
898 text_bounds,
899 })
900 } else {
901 None
902 }
903 }
904
905 fn dispatch_event(
906 &mut self,
907 event: &Event,
908 _: RectF,
909 layout: &mut Self::LayoutState,
910 paint: &mut Self::PaintState,
911 cx: &mut EventContext,
912 ) -> bool {
913 if let (Some(layout), Some(paint)) = (layout, paint) {
914 match event {
915 Event::LeftMouseDown {
916 position,
917 alt,
918 shift,
919 click_count,
920 ..
921 } => self.mouse_down(*position, *alt, *shift, *click_count, layout, paint, cx),
922 Event::LeftMouseUp { position } => self.mouse_up(*position, cx),
923 Event::LeftMouseDragged { position } => {
924 self.mouse_dragged(*position, layout, paint, cx)
925 }
926 Event::ScrollWheel {
927 position,
928 delta,
929 precise,
930 } => self.scroll(*position, *delta, *precise, layout, paint, cx),
931 Event::KeyDown {
932 chars, keystroke, ..
933 } => self.key_down(chars, keystroke, cx),
934 _ => false,
935 }
936 } else {
937 false
938 }
939 }
940
941 fn debug(
942 &self,
943 bounds: RectF,
944 _: &Self::LayoutState,
945 _: &Self::PaintState,
946 _: &gpui::DebugContext,
947 ) -> json::Value {
948 json!({
949 "type": "BufferElement",
950 "bounds": bounds.to_json()
951 })
952 }
953}
954
955pub struct LayoutState {
956 size: Vector2F,
957 gutter_size: Vector2F,
958 gutter_padding: f32,
959 text_size: Vector2F,
960 style: EditorStyle,
961 snapshot: EditorSnapshot,
962 active_rows: BTreeMap<u32, bool>,
963 highlighted_row: Option<u32>,
964 line_layouts: Vec<text_layout::Line>,
965 line_number_layouts: Vec<Option<text_layout::Line>>,
966 blocks: Vec<(u32, ElementBox)>,
967 line_height: f32,
968 em_width: f32,
969 em_advance: f32,
970 selections: HashMap<ReplicaId, Vec<text::Selection<DisplayPoint>>>,
971 overscroll: Vector2F,
972 text_offset: Vector2F,
973 max_visible_line_width: f32,
974}
975
976impl LayoutState {
977 fn scroll_width(&self, layout_cache: &TextLayoutCache) -> f32 {
978 let row = self.snapshot.longest_row();
979 let longest_line_width =
980 layout_line(row, &self.snapshot, &self.style, layout_cache).width();
981 longest_line_width.max(self.max_visible_line_width) + self.overscroll.x()
982 }
983
984 fn scroll_max(&self, font_cache: &FontCache, layout_cache: &TextLayoutCache) -> Vector2F {
985 let text_width = self.text_size.x();
986 let scroll_width = self.scroll_width(layout_cache);
987 let em_width = self.style.text.em_width(font_cache);
988 let max_row = self.snapshot.max_point().row();
989
990 vec2f(
991 ((scroll_width - text_width) / em_width).max(0.0),
992 max_row.saturating_sub(1) as f32,
993 )
994 }
995}
996
997fn layout_line(
998 row: u32,
999 snapshot: &EditorSnapshot,
1000 style: &EditorStyle,
1001 layout_cache: &TextLayoutCache,
1002) -> text_layout::Line {
1003 let mut line = snapshot.line(row);
1004
1005 if line.len() > MAX_LINE_LEN {
1006 let mut len = MAX_LINE_LEN;
1007 while !line.is_char_boundary(len) {
1008 len -= 1;
1009 }
1010 line.truncate(len);
1011 }
1012
1013 layout_cache.layout_str(
1014 &line,
1015 style.text.font_size,
1016 &[(
1017 snapshot.line_len(row) as usize,
1018 RunStyle {
1019 font_id: style.text.font_id,
1020 color: Color::black(),
1021 underline: None,
1022 },
1023 )],
1024 )
1025}
1026
1027pub struct PaintState {
1028 bounds: RectF,
1029 gutter_bounds: RectF,
1030 text_bounds: RectF,
1031}
1032
1033impl PaintState {
1034 fn point_for_position(
1035 &self,
1036 snapshot: &EditorSnapshot,
1037 layout: &LayoutState,
1038 position: Vector2F,
1039 ) -> (DisplayPoint, u32) {
1040 let scroll_position = snapshot.scroll_position();
1041 let position = position - self.text_bounds.origin();
1042 let y = position.y().max(0.0).min(layout.size.y());
1043 let row = ((y / layout.line_height) + scroll_position.y()) as u32;
1044 let row = cmp::min(row, snapshot.max_point().row());
1045 let line = &layout.line_layouts[(row - scroll_position.y() as u32) as usize];
1046 let x = position.x() + (scroll_position.x() * layout.em_width);
1047
1048 let column = if x >= 0.0 {
1049 line.index_for_x(x)
1050 .map(|ix| ix as u32)
1051 .unwrap_or_else(|| snapshot.line_len(row))
1052 } else {
1053 0
1054 };
1055 let overshoot = (0f32.max(x - line.width()) / layout.em_advance) as u32;
1056
1057 (DisplayPoint::new(row, column), overshoot)
1058 }
1059}
1060
1061struct Cursor {
1062 origin: Vector2F,
1063 line_height: f32,
1064 color: Color,
1065}
1066
1067impl Cursor {
1068 fn paint(&self, cx: &mut PaintContext) {
1069 cx.scene.push_quad(Quad {
1070 bounds: RectF::new(self.origin, vec2f(2.0, self.line_height)),
1071 background: Some(self.color),
1072 border: Border::new(0., Color::black()),
1073 corner_radius: 0.,
1074 });
1075 }
1076}
1077
1078#[derive(Debug)]
1079struct Selection {
1080 start_y: f32,
1081 line_height: f32,
1082 lines: Vec<SelectionLine>,
1083 color: Color,
1084}
1085
1086#[derive(Debug)]
1087struct SelectionLine {
1088 start_x: f32,
1089 end_x: f32,
1090}
1091
1092impl Selection {
1093 fn paint(&self, bounds: RectF, scene: &mut Scene) {
1094 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
1095 self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
1096 self.paint_lines(
1097 self.start_y + self.line_height,
1098 &self.lines[1..],
1099 bounds,
1100 scene,
1101 );
1102 } else {
1103 self.paint_lines(self.start_y, &self.lines, bounds, scene);
1104 }
1105 }
1106
1107 fn paint_lines(&self, start_y: f32, lines: &[SelectionLine], bounds: RectF, scene: &mut Scene) {
1108 if lines.is_empty() {
1109 return;
1110 }
1111
1112 let mut path = PathBuilder::new();
1113 let corner_radius = 0.15 * self.line_height;
1114 let first_line = lines.first().unwrap();
1115 let last_line = lines.last().unwrap();
1116
1117 let first_top_left = vec2f(first_line.start_x, start_y);
1118 let first_top_right = vec2f(first_line.end_x, start_y);
1119
1120 let curve_height = vec2f(0., corner_radius);
1121 let curve_width = |start_x: f32, end_x: f32| {
1122 let max = (end_x - start_x) / 2.;
1123 let width = if max < corner_radius {
1124 max
1125 } else {
1126 corner_radius
1127 };
1128
1129 vec2f(width, 0.)
1130 };
1131
1132 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
1133 path.reset(first_top_right - top_curve_width);
1134 path.curve_to(first_top_right + curve_height, first_top_right);
1135
1136 let mut iter = lines.iter().enumerate().peekable();
1137 while let Some((ix, line)) = iter.next() {
1138 let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
1139
1140 if let Some((_, next_line)) = iter.peek() {
1141 let next_top_right = vec2f(next_line.end_x, bottom_right.y());
1142
1143 match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
1144 Ordering::Equal => {
1145 path.line_to(bottom_right);
1146 }
1147 Ordering::Less => {
1148 let curve_width = curve_width(next_top_right.x(), bottom_right.x());
1149 path.line_to(bottom_right - curve_height);
1150 path.curve_to(bottom_right - curve_width, bottom_right);
1151 path.line_to(next_top_right + curve_width);
1152 path.curve_to(next_top_right + curve_height, next_top_right);
1153 }
1154 Ordering::Greater => {
1155 let curve_width = curve_width(bottom_right.x(), next_top_right.x());
1156 path.line_to(bottom_right - curve_height);
1157 path.curve_to(bottom_right + curve_width, bottom_right);
1158 path.line_to(next_top_right - curve_width);
1159 path.curve_to(next_top_right + curve_height, next_top_right);
1160 }
1161 }
1162 } else {
1163 let curve_width = curve_width(line.start_x, line.end_x);
1164 path.line_to(bottom_right - curve_height);
1165 path.curve_to(bottom_right - curve_width, bottom_right);
1166
1167 let bottom_left = vec2f(line.start_x, bottom_right.y());
1168 path.line_to(bottom_left + curve_width);
1169 path.curve_to(bottom_left - curve_height, bottom_left);
1170 }
1171 }
1172
1173 if first_line.start_x > last_line.start_x {
1174 let curve_width = curve_width(last_line.start_x, first_line.start_x);
1175 let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
1176 path.line_to(second_top_left + curve_height);
1177 path.curve_to(second_top_left + curve_width, second_top_left);
1178 let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
1179 path.line_to(first_bottom_left - curve_width);
1180 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
1181 }
1182
1183 path.line_to(first_top_left + curve_height);
1184 path.curve_to(first_top_left + top_curve_width, first_top_left);
1185 path.line_to(first_top_right - top_curve_width);
1186
1187 scene.push_path(path.build(self.color, Some(bounds)));
1188 }
1189}
1190
1191fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
1192 delta.powf(1.5) / 100.0
1193}
1194
1195fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
1196 delta.powf(1.2) / 300.0
1197}
1198
1199#[cfg(test)]
1200mod tests {
1201 use super::*;
1202 use crate::{Editor, EditorSettings, MultiBuffer};
1203 use std::sync::Arc;
1204 use util::test::sample_text;
1205
1206 #[gpui::test]
1207 fn test_layout_line_numbers(cx: &mut gpui::MutableAppContext) {
1208 let settings = EditorSettings::test(cx);
1209 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
1210 let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1211 Editor::for_buffer(
1212 buffer,
1213 {
1214 let settings = settings.clone();
1215 Arc::new(move |_| settings.clone())
1216 },
1217 cx,
1218 )
1219 });
1220 let element = EditorElement::new(editor.downgrade(), settings);
1221
1222 let layouts = editor.update(cx, |editor, cx| {
1223 let snapshot = editor.snapshot(cx);
1224 let mut presenter = cx.build_presenter(window_id, 30.);
1225 let mut layout_cx = presenter.build_layout_context(false, cx);
1226 element.layout_rows(0..6, &Default::default(), &snapshot, &mut layout_cx)
1227 });
1228 assert_eq!(layouts.len(), 6);
1229 }
1230}