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