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