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