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