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