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