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