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