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