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