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