1use super::{
2 display_map::{BlockContext, ToDisplayPoint},
3 Anchor, DisplayPoint, Editor, EditorMode, EditorSnapshot, Input, Scroll, Select, SelectPhase,
4 SoftWrap, ToPoint, MAX_LINE_LEN,
5};
6use crate::{
7 display_map::{DisplaySnapshot, TransformBlock},
8 EditorStyle, HoverAt,
9};
10use clock::ReplicaId;
11use collections::{BTreeMap, HashMap};
12use gpui::{
13 color::Color,
14 elements::*,
15 fonts::{HighlightStyle, Underline},
16 geometry::{
17 rect::RectF,
18 vector::{vec2f, Vector2F},
19 PathBuilder,
20 },
21 json::{self, ToJson},
22 platform::CursorStyle,
23 text_layout::{self, Line, RunStyle, TextLayoutCache},
24 AppContext, Axis, Border, CursorRegion, Element, ElementBox, Event, EventContext,
25 LayoutContext, MutableAppContext, PaintContext, Quad, Scene, SizeConstraint, ViewContext,
26 WeakViewHandle,
27};
28use json::json;
29use language::{Bias, DiagnosticSeverity, Selection};
30use settings::Settings;
31use smallvec::SmallVec;
32use std::{
33 cmp::{self, Ordering},
34 fmt::Write,
35 iter,
36 ops::Range,
37};
38
39struct SelectionLayout {
40 head: DisplayPoint,
41 range: Range<DisplayPoint>,
42}
43
44impl SelectionLayout {
45 fn new<T: ToPoint + ToDisplayPoint + Clone>(
46 selection: Selection<T>,
47 line_mode: bool,
48 map: &DisplaySnapshot,
49 ) -> Self {
50 if line_mode {
51 let selection = selection.map(|p| p.to_point(&map.buffer_snapshot));
52 let point_range = map.expand_to_line(selection.range());
53 Self {
54 head: selection.head().to_display_point(map),
55 range: point_range.start.to_display_point(map)
56 ..point_range.end.to_display_point(map),
57 }
58 } else {
59 let selection = selection.map(|p| p.to_display_point(map));
60 Self {
61 head: selection.head(),
62 range: selection.range(),
63 }
64 }
65 }
66}
67
68pub struct EditorElement {
69 view: WeakViewHandle<Editor>,
70 style: EditorStyle,
71 cursor_shape: CursorShape,
72}
73
74impl EditorElement {
75 pub fn new(
76 view: WeakViewHandle<Editor>,
77 style: EditorStyle,
78 cursor_shape: CursorShape,
79 ) -> Self {
80 Self {
81 view,
82 style,
83 cursor_shape,
84 }
85 }
86
87 fn view<'a>(&self, cx: &'a AppContext) -> &'a Editor {
88 self.view.upgrade(cx).unwrap().read(cx)
89 }
90
91 fn update_view<F, T>(&self, cx: &mut MutableAppContext, f: F) -> T
92 where
93 F: FnOnce(&mut Editor, &mut ViewContext<Editor>) -> T,
94 {
95 self.view.upgrade(cx).unwrap().update(cx, f)
96 }
97
98 fn snapshot(&self, cx: &mut MutableAppContext) -> EditorSnapshot {
99 self.update_view(cx, |view, cx| view.snapshot(cx))
100 }
101
102 fn mouse_down(
103 &self,
104 position: Vector2F,
105 _: bool,
106 alt: bool,
107 shift: bool,
108 mut click_count: usize,
109 layout: &mut LayoutState,
110 paint: &mut PaintState,
111 cx: &mut EventContext,
112 ) -> bool {
113 if paint.gutter_bounds.contains_point(position) {
114 click_count = 3; // Simulate triple-click when clicking the gutter to select lines
115 } else if !paint.text_bounds.contains_point(position) {
116 return false;
117 }
118
119 let snapshot = self.snapshot(cx.app);
120 let (position, overshoot) = paint.point_for_position(&snapshot, layout, position);
121
122 if shift && alt {
123 cx.dispatch_action(Select(SelectPhase::BeginColumnar {
124 position,
125 overshoot: overshoot.column(),
126 }));
127 } else if shift {
128 cx.dispatch_action(Select(SelectPhase::Extend {
129 position,
130 click_count,
131 }));
132 } else {
133 cx.dispatch_action(Select(SelectPhase::Begin {
134 position,
135 add: alt,
136 click_count,
137 }));
138 }
139
140 true
141 }
142
143 fn mouse_up(&self, _position: Vector2F, cx: &mut EventContext) -> bool {
144 if self.view(cx.app.as_ref()).is_selecting() {
145 cx.dispatch_action(Select(SelectPhase::End));
146 true
147 } else {
148 false
149 }
150 }
151
152 fn mouse_dragged(
153 &self,
154 position: Vector2F,
155 layout: &mut LayoutState,
156 paint: &mut PaintState,
157 cx: &mut EventContext,
158 ) -> bool {
159 let view = self.view(cx.app.as_ref());
160
161 if view.is_selecting() {
162 let rect = paint.text_bounds;
163 let mut scroll_delta = Vector2F::zero();
164
165 let vertical_margin = layout.line_height.min(rect.height() / 3.0);
166 let top = rect.origin_y() + vertical_margin;
167 let bottom = rect.lower_left().y() - vertical_margin;
168 if position.y() < top {
169 scroll_delta.set_y(-scale_vertical_mouse_autoscroll_delta(top - position.y()))
170 }
171 if position.y() > bottom {
172 scroll_delta.set_y(scale_vertical_mouse_autoscroll_delta(position.y() - bottom))
173 }
174
175 let horizontal_margin = layout.line_height.min(rect.width() / 3.0);
176 let left = rect.origin_x() + horizontal_margin;
177 let right = rect.upper_right().x() - horizontal_margin;
178 if position.x() < left {
179 scroll_delta.set_x(-scale_horizontal_mouse_autoscroll_delta(
180 left - position.x(),
181 ))
182 }
183 if position.x() > right {
184 scroll_delta.set_x(scale_horizontal_mouse_autoscroll_delta(
185 position.x() - right,
186 ))
187 }
188
189 let snapshot = self.snapshot(cx.app);
190 let (position, overshoot) = paint.point_for_position(&snapshot, layout, position);
191
192 cx.dispatch_action(Select(SelectPhase::Update {
193 position,
194 overshoot: overshoot.column(),
195 scroll_position: (snapshot.scroll_position() + scroll_delta)
196 .clamp(Vector2F::zero(), layout.scroll_max),
197 }));
198 true
199 } else {
200 false
201 }
202 }
203
204 fn key_down(&self, input: Option<&str>, cx: &mut EventContext) -> bool {
205 let view = self.view.upgrade(cx.app).unwrap();
206
207 if view.is_focused(cx.app) {
208 if let Some(input) = input {
209 cx.dispatch_action(Input(input.to_string()));
210 true
211 } else {
212 false
213 }
214 } else {
215 false
216 }
217 }
218
219 fn scroll(
220 &self,
221 position: Vector2F,
222 mut delta: Vector2F,
223 precise: bool,
224 layout: &mut LayoutState,
225 paint: &mut PaintState,
226 cx: &mut EventContext,
227 ) -> bool {
228 if !paint.bounds.contains_point(position) {
229 return false;
230 }
231
232 let snapshot = self.snapshot(cx.app);
233 let max_glyph_width = layout.em_width;
234 if !precise {
235 delta *= vec2f(max_glyph_width, layout.line_height);
236 }
237
238 let scroll_position = snapshot.scroll_position();
239 let x = (scroll_position.x() * max_glyph_width - delta.x()) / max_glyph_width;
240 let y = (scroll_position.y() * layout.line_height - delta.y()) / layout.line_height;
241 let scroll_position = vec2f(x, y).clamp(Vector2F::zero(), layout.scroll_max);
242
243 cx.dispatch_action(Scroll(scroll_position));
244
245 true
246 }
247
248 fn paint_background(
249 &self,
250 gutter_bounds: RectF,
251 text_bounds: RectF,
252 layout: &LayoutState,
253 cx: &mut PaintContext,
254 ) {
255 let bounds = gutter_bounds.union_rect(text_bounds);
256 let scroll_top = layout.snapshot.scroll_position().y() * layout.line_height;
257 let editor = self.view(cx.app);
258 cx.scene.push_quad(Quad {
259 bounds: gutter_bounds,
260 background: Some(self.style.gutter_background),
261 border: Border::new(0., Color::transparent_black()),
262 corner_radius: 0.,
263 });
264 cx.scene.push_quad(Quad {
265 bounds: text_bounds,
266 background: Some(self.style.background),
267 border: Border::new(0., Color::transparent_black()),
268 corner_radius: 0.,
269 });
270
271 if let EditorMode::Full = editor.mode {
272 let mut active_rows = layout.active_rows.iter().peekable();
273 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
274 let mut end_row = *start_row;
275 while active_rows.peek().map_or(false, |r| {
276 *r.0 == end_row + 1 && r.1 == contains_non_empty_selection
277 }) {
278 active_rows.next().unwrap();
279 end_row += 1;
280 }
281
282 if !contains_non_empty_selection {
283 let origin = vec2f(
284 bounds.origin_x(),
285 bounds.origin_y() + (layout.line_height * *start_row as f32) - scroll_top,
286 );
287 let size = vec2f(
288 bounds.width(),
289 layout.line_height * (end_row - start_row + 1) as f32,
290 );
291 cx.scene.push_quad(Quad {
292 bounds: RectF::new(origin, size),
293 background: Some(self.style.active_line_background),
294 border: Border::default(),
295 corner_radius: 0.,
296 });
297 }
298 }
299
300 if let Some(highlighted_rows) = &layout.highlighted_rows {
301 let origin = vec2f(
302 bounds.origin_x(),
303 bounds.origin_y() + (layout.line_height * highlighted_rows.start as f32)
304 - scroll_top,
305 );
306 let size = vec2f(
307 bounds.width(),
308 layout.line_height * highlighted_rows.len() as f32,
309 );
310 cx.scene.push_quad(Quad {
311 bounds: RectF::new(origin, size),
312 background: Some(self.style.highlighted_line_background),
313 border: Border::default(),
314 corner_radius: 0.,
315 });
316 }
317 }
318 }
319
320 fn paint_gutter(
321 &mut self,
322 bounds: RectF,
323 visible_bounds: RectF,
324 layout: &mut LayoutState,
325 cx: &mut PaintContext,
326 ) {
327 let scroll_top = layout.snapshot.scroll_position().y() * layout.line_height;
328 for (ix, line) in layout.line_number_layouts.iter().enumerate() {
329 if let Some(line) = line {
330 let line_origin = bounds.origin()
331 + vec2f(
332 bounds.width() - line.width() - layout.gutter_padding,
333 ix as f32 * layout.line_height - (scroll_top % layout.line_height),
334 );
335 line.paint(line_origin, visible_bounds, layout.line_height, cx);
336 }
337 }
338
339 if let Some((row, indicator)) = layout.code_actions_indicator.as_mut() {
340 let mut x = bounds.width() - layout.gutter_padding;
341 let mut y = *row as f32 * layout.line_height - scroll_top;
342 x += ((layout.gutter_padding + layout.gutter_margin) - indicator.size().x()) / 2.;
343 y += (layout.line_height - indicator.size().y()) / 2.;
344 indicator.paint(bounds.origin() + vec2f(x, y), visible_bounds, cx);
345 }
346 }
347
348 fn paint_text(
349 &mut self,
350 bounds: RectF,
351 visible_bounds: RectF,
352 layout: &mut LayoutState,
353 paint: &mut PaintState,
354 cx: &mut PaintContext,
355 ) {
356 let view = self.view(cx.app);
357 let style = &self.style;
358 let local_replica_id = view.replica_id(cx);
359 let scroll_position = layout.snapshot.scroll_position();
360 let start_row = scroll_position.y() as u32;
361 let scroll_top = scroll_position.y() * layout.line_height;
362 let end_row = ((scroll_top + bounds.height()) / layout.line_height).ceil() as u32 + 1; // Add 1 to ensure selections bleed off screen
363 let max_glyph_width = layout.em_width;
364 let scroll_left = scroll_position.x() * max_glyph_width;
365 let content_origin = bounds.origin() + vec2f(layout.gutter_margin, 0.);
366
367 cx.scene.push_layer(Some(bounds));
368 cx.scene.push_cursor_region(CursorRegion {
369 bounds,
370 style: CursorStyle::IBeam,
371 });
372
373 for (range, color) in &layout.highlighted_ranges {
374 self.paint_highlighted_range(
375 range.clone(),
376 start_row,
377 end_row,
378 *color,
379 0.,
380 0.15 * layout.line_height,
381 layout,
382 content_origin,
383 scroll_top,
384 scroll_left,
385 bounds,
386 cx,
387 );
388 }
389
390 let mut cursors = SmallVec::<[Cursor; 32]>::new();
391 for (replica_id, selections) in &layout.selections {
392 let selection_style = style.replica_selection_style(*replica_id);
393 let corner_radius = 0.15 * layout.line_height;
394
395 for selection in selections {
396 self.paint_highlighted_range(
397 selection.range.clone(),
398 start_row,
399 end_row,
400 selection_style.selection,
401 corner_radius,
402 corner_radius * 2.,
403 layout,
404 content_origin,
405 scroll_top,
406 scroll_left,
407 bounds,
408 cx,
409 );
410
411 if view.show_local_cursors() || *replica_id != local_replica_id {
412 let cursor_position = selection.head;
413 if (start_row..end_row).contains(&cursor_position.row()) {
414 let cursor_row_layout =
415 &layout.line_layouts[(cursor_position.row() - start_row) as usize];
416 let cursor_column = cursor_position.column() as usize;
417
418 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
419 let mut block_width =
420 cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
421 if block_width == 0.0 {
422 block_width = layout.em_width;
423 }
424
425 let block_text =
426 if matches!(self.cursor_shape, CursorShape::Block) {
427 layout.snapshot.chars_at(cursor_position).next().and_then(
428 |character| {
429 let font_id =
430 cursor_row_layout.font_for_index(cursor_column)?;
431 let text = character.to_string();
432
433 Some(cx.text_layout_cache.layout_str(
434 &text,
435 cursor_row_layout.font_size(),
436 &[(
437 text.len(),
438 RunStyle {
439 font_id,
440 color: style.background,
441 underline: Default::default(),
442 },
443 )],
444 ))
445 },
446 )
447 } else {
448 None
449 };
450
451 let x = cursor_character_x - scroll_left;
452 let y = cursor_position.row() as f32 * layout.line_height - scroll_top;
453 cursors.push(Cursor {
454 color: selection_style.cursor,
455 block_width,
456 origin: content_origin + vec2f(x, y),
457 line_height: layout.line_height,
458 shape: self.cursor_shape,
459 block_text,
460 });
461 }
462 }
463 }
464 }
465
466 if let Some(visible_text_bounds) = bounds.intersection(visible_bounds) {
467 // Draw glyphs
468 for (ix, line) in layout.line_layouts.iter().enumerate() {
469 let row = start_row + ix as u32;
470 line.paint(
471 content_origin
472 + vec2f(-scroll_left, row as f32 * layout.line_height - scroll_top),
473 visible_text_bounds,
474 layout.line_height,
475 cx,
476 );
477 }
478 }
479
480 cx.scene.push_layer(Some(bounds));
481 for cursor in cursors {
482 cursor.paint(cx);
483 }
484 cx.scene.pop_layer();
485
486 if let Some((position, context_menu)) = layout.context_menu.as_mut() {
487 cx.scene.push_stacking_context(None);
488
489 let cursor_row_layout = &layout.line_layouts[(position.row() - start_row) as usize];
490 let x = cursor_row_layout.x_for_index(position.column() as usize) - scroll_left;
491 let y = (position.row() + 1) as f32 * layout.line_height - scroll_top;
492 let mut list_origin = content_origin + vec2f(x, y);
493 let list_height = context_menu.size().y();
494
495 if list_origin.y() + list_height > bounds.max_y() {
496 list_origin.set_y(list_origin.y() - layout.line_height - list_height);
497 }
498
499 context_menu.paint(
500 list_origin,
501 RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
502 cx,
503 );
504
505 cx.scene.pop_stacking_context();
506 }
507
508 if let Some((position, hover_popover)) = layout.hover.as_mut() {
509 cx.scene.push_stacking_context(None);
510
511 // This is safe because we check on layout whether the required row is available
512 let hovered_row_layout = &layout.line_layouts[(position.row() - start_row) as usize];
513 let size = hover_popover.size();
514 let x = hovered_row_layout.x_for_index(position.column() as usize) - scroll_left;
515 let y = position.row() as f32 * layout.line_height - scroll_top - size.y();
516 let mut popover_origin = content_origin + vec2f(x, y);
517
518 if popover_origin.y() < 0.0 {
519 popover_origin.set_y(popover_origin.y() + layout.line_height + size.y());
520 }
521
522 let x_out_of_bounds = bounds.max_x() - (popover_origin.x() + size.x());
523 if x_out_of_bounds < 0.0 {
524 popover_origin.set_x(popover_origin.x() + x_out_of_bounds);
525 }
526
527 hover_popover.paint(
528 popover_origin,
529 RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
530 cx,
531 );
532
533 paint.hover_bounds = Some(
534 RectF::new(popover_origin, hover_popover.size()).dilate(Vector2F::new(0., 5.)),
535 );
536
537 cx.scene.pop_stacking_context();
538 }
539
540 cx.scene.pop_layer();
541 }
542
543 fn paint_highlighted_range(
544 &self,
545 range: Range<DisplayPoint>,
546 start_row: u32,
547 end_row: u32,
548 color: Color,
549 corner_radius: f32,
550 line_end_overshoot: f32,
551 layout: &LayoutState,
552 content_origin: Vector2F,
553 scroll_top: f32,
554 scroll_left: f32,
555 bounds: RectF,
556 cx: &mut PaintContext,
557 ) {
558 if range.start != range.end {
559 let row_range = if range.end.column() == 0 {
560 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
561 } else {
562 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
563 };
564
565 let highlighted_range = HighlightedRange {
566 color,
567 line_height: layout.line_height,
568 corner_radius,
569 start_y: content_origin.y() + row_range.start as f32 * layout.line_height
570 - scroll_top,
571 lines: row_range
572 .into_iter()
573 .map(|row| {
574 let line_layout = &layout.line_layouts[(row - start_row) as usize];
575 HighlightedRangeLine {
576 start_x: if row == range.start.row() {
577 content_origin.x()
578 + line_layout.x_for_index(range.start.column() as usize)
579 - scroll_left
580 } else {
581 content_origin.x() - scroll_left
582 },
583 end_x: if row == range.end.row() {
584 content_origin.x()
585 + line_layout.x_for_index(range.end.column() as usize)
586 - scroll_left
587 } else {
588 content_origin.x() + line_layout.width() + line_end_overshoot
589 - scroll_left
590 },
591 }
592 })
593 .collect(),
594 };
595
596 highlighted_range.paint(bounds, cx.scene);
597 }
598 }
599
600 fn paint_blocks(
601 &mut self,
602 bounds: RectF,
603 visible_bounds: RectF,
604 layout: &mut LayoutState,
605 cx: &mut PaintContext,
606 ) {
607 let scroll_position = layout.snapshot.scroll_position();
608 let scroll_left = scroll_position.x() * layout.em_width;
609 let scroll_top = scroll_position.y() * layout.line_height;
610
611 for (row, element) in &mut layout.blocks {
612 let origin = bounds.origin()
613 + vec2f(-scroll_left, *row as f32 * layout.line_height - scroll_top);
614 element.paint(origin, visible_bounds, cx);
615 }
616 }
617
618 fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &LayoutContext) -> f32 {
619 let digit_count = (snapshot.max_buffer_row() as f32).log10().floor() as usize + 1;
620 let style = &self.style;
621
622 cx.text_layout_cache
623 .layout_str(
624 "1".repeat(digit_count).as_str(),
625 style.text.font_size,
626 &[(
627 digit_count,
628 RunStyle {
629 font_id: style.text.font_id,
630 color: Color::black(),
631 underline: Default::default(),
632 },
633 )],
634 )
635 .width()
636 }
637
638 fn layout_line_numbers(
639 &self,
640 rows: Range<u32>,
641 active_rows: &BTreeMap<u32, bool>,
642 snapshot: &EditorSnapshot,
643 cx: &LayoutContext,
644 ) -> Vec<Option<text_layout::Line>> {
645 let style = &self.style;
646 let include_line_numbers = snapshot.mode == EditorMode::Full;
647 let mut line_number_layouts = Vec::with_capacity(rows.len());
648 let mut line_number = String::new();
649 for (ix, row) in snapshot
650 .buffer_rows(rows.start)
651 .take((rows.end - rows.start) as usize)
652 .enumerate()
653 {
654 let display_row = rows.start + ix as u32;
655 let color = if active_rows.contains_key(&display_row) {
656 style.line_number_active
657 } else {
658 style.line_number
659 };
660 if let Some(buffer_row) = row {
661 if include_line_numbers {
662 line_number.clear();
663 write!(&mut line_number, "{}", buffer_row + 1).unwrap();
664 line_number_layouts.push(Some(cx.text_layout_cache.layout_str(
665 &line_number,
666 style.text.font_size,
667 &[(
668 line_number.len(),
669 RunStyle {
670 font_id: style.text.font_id,
671 color,
672 underline: Default::default(),
673 },
674 )],
675 )));
676 }
677 } else {
678 line_number_layouts.push(None);
679 }
680 }
681
682 line_number_layouts
683 }
684
685 fn layout_lines(
686 &mut self,
687 rows: Range<u32>,
688 snapshot: &EditorSnapshot,
689 cx: &LayoutContext,
690 ) -> Vec<text_layout::Line> {
691 if rows.start >= rows.end {
692 return Vec::new();
693 }
694
695 // When the editor is empty and unfocused, then show the placeholder.
696 if snapshot.is_empty() && !snapshot.is_focused() {
697 let placeholder_style = self
698 .style
699 .placeholder_text
700 .as_ref()
701 .unwrap_or_else(|| &self.style.text);
702 let placeholder_text = snapshot.placeholder_text();
703 let placeholder_lines = placeholder_text
704 .as_ref()
705 .map_or("", AsRef::as_ref)
706 .split('\n')
707 .skip(rows.start as usize)
708 .chain(iter::repeat(""))
709 .take(rows.len());
710 return placeholder_lines
711 .map(|line| {
712 cx.text_layout_cache.layout_str(
713 line,
714 placeholder_style.font_size,
715 &[(
716 line.len(),
717 RunStyle {
718 font_id: placeholder_style.font_id,
719 color: placeholder_style.color,
720 underline: Default::default(),
721 },
722 )],
723 )
724 })
725 .collect();
726 } else {
727 let style = &self.style;
728 let chunks = snapshot.chunks(rows.clone(), true).map(|chunk| {
729 let mut highlight_style = chunk
730 .syntax_highlight_id
731 .and_then(|id| id.style(&style.syntax));
732
733 if let Some(chunk_highlight) = chunk.highlight_style {
734 if let Some(highlight_style) = highlight_style.as_mut() {
735 highlight_style.highlight(chunk_highlight);
736 } else {
737 highlight_style = Some(chunk_highlight);
738 }
739 }
740
741 let mut diagnostic_highlight = HighlightStyle::default();
742
743 if chunk.is_unnecessary {
744 diagnostic_highlight.fade_out = Some(style.unnecessary_code_fade);
745 }
746
747 if let Some(severity) = chunk.diagnostic_severity {
748 // Omit underlines for HINT/INFO diagnostics on 'unnecessary' code.
749 if severity <= DiagnosticSeverity::WARNING || !chunk.is_unnecessary {
750 let diagnostic_style = super::diagnostic_style(severity, true, style);
751 diagnostic_highlight.underline = Some(Underline {
752 color: Some(diagnostic_style.message.text.color),
753 thickness: 1.0.into(),
754 squiggly: true,
755 });
756 }
757 }
758
759 if let Some(highlight_style) = highlight_style.as_mut() {
760 highlight_style.highlight(diagnostic_highlight);
761 } else {
762 highlight_style = Some(diagnostic_highlight);
763 }
764
765 (chunk.text, highlight_style)
766 });
767 layout_highlighted_chunks(
768 chunks,
769 &style.text,
770 &cx.text_layout_cache,
771 &cx.font_cache,
772 MAX_LINE_LEN,
773 rows.len() as usize,
774 )
775 }
776 }
777
778 fn layout_blocks(
779 &mut self,
780 rows: Range<u32>,
781 snapshot: &EditorSnapshot,
782 width: f32,
783 gutter_padding: f32,
784 gutter_width: f32,
785 em_width: f32,
786 text_x: f32,
787 line_height: f32,
788 style: &EditorStyle,
789 line_layouts: &[text_layout::Line],
790 cx: &mut LayoutContext,
791 ) -> Vec<(u32, ElementBox)> {
792 let editor = if let Some(editor) = self.view.upgrade(cx) {
793 editor
794 } else {
795 return Default::default();
796 };
797
798 let scroll_x = snapshot.scroll_position.x();
799 snapshot
800 .blocks_in_range(rows.clone())
801 .map(|(block_row, block)| {
802 let mut element = match block {
803 TransformBlock::Custom(block) => {
804 let align_to = block
805 .position()
806 .to_point(&snapshot.buffer_snapshot)
807 .to_display_point(snapshot);
808 let anchor_x = text_x
809 + if rows.contains(&align_to.row()) {
810 line_layouts[(align_to.row() - rows.start) as usize]
811 .x_for_index(align_to.column() as usize)
812 } else {
813 layout_line(align_to.row(), snapshot, style, cx.text_layout_cache)
814 .x_for_index(align_to.column() as usize)
815 };
816
817 cx.render(&editor, |_, cx| {
818 block.render(&mut BlockContext {
819 cx,
820 anchor_x,
821 gutter_padding,
822 line_height,
823 scroll_x,
824 gutter_width,
825 em_width,
826 })
827 })
828 }
829 TransformBlock::ExcerptHeader {
830 buffer,
831 starts_new_buffer,
832 ..
833 } => {
834 if *starts_new_buffer {
835 let style = &self.style.diagnostic_path_header;
836 let font_size =
837 (style.text_scale_factor * self.style.text.font_size).round();
838
839 let mut filename = None;
840 let mut parent_path = None;
841 if let Some(file) = buffer.file() {
842 let path = file.path();
843 filename =
844 path.file_name().map(|f| f.to_string_lossy().to_string());
845 parent_path =
846 path.parent().map(|p| p.to_string_lossy().to_string() + "/");
847 }
848
849 Flex::row()
850 .with_child(
851 Label::new(
852 filename.unwrap_or_else(|| "untitled".to_string()),
853 style.filename.text.clone().with_font_size(font_size),
854 )
855 .contained()
856 .with_style(style.filename.container)
857 .boxed(),
858 )
859 .with_children(parent_path.map(|path| {
860 Label::new(
861 path,
862 style.path.text.clone().with_font_size(font_size),
863 )
864 .contained()
865 .with_style(style.path.container)
866 .boxed()
867 }))
868 .aligned()
869 .left()
870 .contained()
871 .with_style(style.container)
872 .with_padding_left(gutter_padding + scroll_x * em_width)
873 .expanded()
874 .named("path header block")
875 } else {
876 let text_style = self.style.text.clone();
877 Label::new("…".to_string(), text_style)
878 .contained()
879 .with_padding_left(gutter_padding + scroll_x * em_width)
880 .named("collapsed context")
881 }
882 }
883 };
884
885 element.layout(
886 SizeConstraint {
887 min: Vector2F::zero(),
888 max: vec2f(width, block.height() as f32 * line_height),
889 },
890 cx,
891 );
892 (block_row, element)
893 })
894 .collect()
895 }
896}
897
898impl Element for EditorElement {
899 type LayoutState = LayoutState;
900 type PaintState = PaintState;
901
902 fn layout(
903 &mut self,
904 constraint: SizeConstraint,
905 cx: &mut LayoutContext,
906 ) -> (Vector2F, Self::LayoutState) {
907 let mut size = constraint.max;
908 if size.x().is_infinite() {
909 unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
910 }
911
912 let snapshot = self.snapshot(cx.app);
913 let style = self.style.clone();
914 let line_height = style.text.line_height(cx.font_cache);
915
916 let gutter_padding;
917 let gutter_width;
918 let gutter_margin;
919 if snapshot.mode == EditorMode::Full {
920 gutter_padding = style.text.em_width(cx.font_cache) * style.gutter_padding_factor;
921 gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
922 gutter_margin = -style.text.descent(cx.font_cache);
923 } else {
924 gutter_padding = 0.0;
925 gutter_width = 0.0;
926 gutter_margin = 0.0;
927 };
928
929 let text_width = size.x() - gutter_width;
930 let em_width = style.text.em_width(cx.font_cache);
931 let em_advance = style.text.em_advance(cx.font_cache);
932 let overscroll = vec2f(em_width, 0.);
933 let snapshot = self.update_view(cx.app, |view, cx| {
934 let wrap_width = match view.soft_wrap_mode(cx) {
935 SoftWrap::None => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
936 SoftWrap::EditorWidth => {
937 Some(text_width - gutter_margin - overscroll.x() - em_width)
938 }
939 SoftWrap::Column(column) => Some(column as f32 * em_advance),
940 };
941
942 if view.set_wrap_width(wrap_width, cx) {
943 view.snapshot(cx)
944 } else {
945 snapshot
946 }
947 });
948
949 let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
950 if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
951 size.set_y(
952 scroll_height
953 .min(constraint.max_along(Axis::Vertical))
954 .max(constraint.min_along(Axis::Vertical))
955 .min(line_height * max_lines as f32),
956 )
957 } else if let EditorMode::SingleLine = snapshot.mode {
958 size.set_y(
959 line_height
960 .min(constraint.max_along(Axis::Vertical))
961 .max(constraint.min_along(Axis::Vertical)),
962 )
963 } else if size.y().is_infinite() {
964 size.set_y(scroll_height);
965 }
966 let gutter_size = vec2f(gutter_width, size.y());
967 let text_size = vec2f(text_width, size.y());
968
969 let (autoscroll_horizontally, mut snapshot) = self.update_view(cx.app, |view, cx| {
970 let autoscroll_horizontally = view.autoscroll_vertically(size.y(), line_height, cx);
971 let snapshot = view.snapshot(cx);
972 (autoscroll_horizontally, snapshot)
973 });
974
975 let scroll_position = snapshot.scroll_position();
976 let start_row = scroll_position.y() as u32;
977 let scroll_top = scroll_position.y() * line_height;
978
979 // Add 1 to ensure selections bleed off screen
980 let end_row = 1 + cmp::min(
981 ((scroll_top + size.y()) / line_height).ceil() as u32,
982 snapshot.max_point().row(),
983 );
984
985 let start_anchor = if start_row == 0 {
986 Anchor::min()
987 } else {
988 snapshot
989 .buffer_snapshot
990 .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
991 };
992 let end_anchor = if end_row > snapshot.max_point().row() {
993 Anchor::max()
994 } else {
995 snapshot
996 .buffer_snapshot
997 .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
998 };
999
1000 let mut selections: Vec<(ReplicaId, Vec<SelectionLayout>)> = Vec::new();
1001 let mut active_rows = BTreeMap::new();
1002 let mut highlighted_rows = None;
1003 let mut highlighted_ranges = Vec::new();
1004 self.update_view(cx.app, |view, cx| {
1005 let display_map = view.display_map.update(cx, |map, cx| map.snapshot(cx));
1006
1007 highlighted_rows = view.highlighted_rows();
1008 let theme = cx.global::<Settings>().theme.as_ref();
1009 highlighted_ranges = view.background_highlights_in_range(
1010 start_anchor.clone()..end_anchor.clone(),
1011 &display_map,
1012 theme,
1013 );
1014
1015 let mut remote_selections = HashMap::default();
1016 for (replica_id, line_mode, selection) in display_map
1017 .buffer_snapshot
1018 .remote_selections_in_range(&(start_anchor.clone()..end_anchor.clone()))
1019 {
1020 // The local selections match the leader's selections.
1021 if Some(replica_id) == view.leader_replica_id {
1022 continue;
1023 }
1024 remote_selections
1025 .entry(replica_id)
1026 .or_insert(Vec::new())
1027 .push(SelectionLayout::new(selection, line_mode, &display_map));
1028 }
1029 selections.extend(remote_selections);
1030
1031 if view.show_local_selections {
1032 let mut local_selections = view
1033 .selections
1034 .disjoint_in_range(start_anchor..end_anchor, cx);
1035 local_selections.extend(view.selections.pending(cx));
1036 for selection in &local_selections {
1037 let is_empty = selection.start == selection.end;
1038 let selection_start = snapshot.prev_line_boundary(selection.start).1;
1039 let selection_end = snapshot.next_line_boundary(selection.end).1;
1040 for row in cmp::max(selection_start.row(), start_row)
1041 ..=cmp::min(selection_end.row(), end_row)
1042 {
1043 let contains_non_empty_selection =
1044 active_rows.entry(row).or_insert(!is_empty);
1045 *contains_non_empty_selection |= !is_empty;
1046 }
1047 }
1048
1049 // Render the local selections in the leader's color when following.
1050 let local_replica_id = view.leader_replica_id.unwrap_or(view.replica_id(cx));
1051
1052 selections.push((
1053 local_replica_id,
1054 local_selections
1055 .into_iter()
1056 .map(|selection| {
1057 SelectionLayout::new(selection, view.selections.line_mode, &display_map)
1058 })
1059 .collect(),
1060 ));
1061 }
1062 });
1063
1064 let line_number_layouts =
1065 self.layout_line_numbers(start_row..end_row, &active_rows, &snapshot, cx);
1066
1067 let mut max_visible_line_width = 0.0;
1068 let line_layouts = self.layout_lines(start_row..end_row, &snapshot, cx);
1069 for line in &line_layouts {
1070 if line.width() > max_visible_line_width {
1071 max_visible_line_width = line.width();
1072 }
1073 }
1074
1075 let style = self.style.clone();
1076 let longest_line_width = layout_line(
1077 snapshot.longest_row(),
1078 &snapshot,
1079 &style,
1080 cx.text_layout_cache,
1081 )
1082 .width();
1083 let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
1084 let em_width = style.text.em_width(cx.font_cache);
1085 let max_row = snapshot.max_point().row();
1086 let scroll_max = vec2f(
1087 ((scroll_width - text_size.x()) / em_width).max(0.0),
1088 max_row.saturating_sub(1) as f32,
1089 );
1090
1091 self.update_view(cx.app, |view, cx| {
1092 let clamped = view.clamp_scroll_left(scroll_max.x());
1093 let autoscrolled;
1094 if autoscroll_horizontally {
1095 autoscrolled = view.autoscroll_horizontally(
1096 start_row,
1097 text_size.x(),
1098 scroll_width,
1099 em_width,
1100 &line_layouts,
1101 cx,
1102 );
1103 } else {
1104 autoscrolled = false;
1105 }
1106
1107 if clamped || autoscrolled {
1108 snapshot = view.snapshot(cx);
1109 }
1110 });
1111
1112 let mut context_menu = None;
1113 let mut code_actions_indicator = None;
1114 let mut hover = None;
1115 cx.render(&self.view.upgrade(cx).unwrap(), |view, cx| {
1116 let newest_selection_head = view
1117 .selections
1118 .newest::<usize>(cx)
1119 .head()
1120 .to_display_point(&snapshot);
1121
1122 let style = view.style(cx);
1123 if (start_row..end_row).contains(&newest_selection_head.row()) {
1124 if view.context_menu_visible() {
1125 context_menu =
1126 view.render_context_menu(newest_selection_head, style.clone(), cx);
1127 }
1128
1129 code_actions_indicator = view
1130 .render_code_actions_indicator(&style, cx)
1131 .map(|indicator| (newest_selection_head.row(), indicator));
1132 }
1133
1134 hover = view.hover_popover().and_then(|hover| {
1135 let (point, rendered) = hover.render(style.clone(), cx);
1136 if point.row() >= snapshot.scroll_position().y() as u32 {
1137 if line_layouts.len() > (point.row() - start_row) as usize {
1138 return Some((point, rendered));
1139 }
1140 }
1141
1142 None
1143 });
1144 });
1145
1146 if let Some((_, context_menu)) = context_menu.as_mut() {
1147 context_menu.layout(
1148 SizeConstraint {
1149 min: Vector2F::zero(),
1150 max: vec2f(
1151 f32::INFINITY,
1152 (12. * line_height).min((size.y() - line_height) / 2.),
1153 ),
1154 },
1155 cx,
1156 );
1157 }
1158
1159 if let Some((_, indicator)) = code_actions_indicator.as_mut() {
1160 indicator.layout(
1161 SizeConstraint::strict_along(Axis::Vertical, line_height * 0.618),
1162 cx,
1163 );
1164 }
1165
1166 if let Some((_, hover)) = hover.as_mut() {
1167 hover.layout(
1168 SizeConstraint {
1169 min: Vector2F::zero(),
1170 max: vec2f(
1171 (120. * em_width).min(size.x()),
1172 (size.y() - line_height) * 1. / 2.,
1173 ),
1174 },
1175 cx,
1176 );
1177 }
1178
1179 let blocks = self.layout_blocks(
1180 start_row..end_row,
1181 &snapshot,
1182 size.x().max(scroll_width + gutter_width),
1183 gutter_padding,
1184 gutter_width,
1185 em_width,
1186 gutter_width + gutter_margin,
1187 line_height,
1188 &style,
1189 &line_layouts,
1190 cx,
1191 );
1192
1193 (
1194 size,
1195 LayoutState {
1196 size,
1197 scroll_max,
1198 gutter_size,
1199 gutter_padding,
1200 text_size,
1201 gutter_margin,
1202 snapshot,
1203 active_rows,
1204 highlighted_rows,
1205 highlighted_ranges,
1206 line_layouts,
1207 line_number_layouts,
1208 blocks,
1209 line_height,
1210 em_width,
1211 em_advance,
1212 selections,
1213 context_menu,
1214 code_actions_indicator,
1215 hover,
1216 },
1217 )
1218 }
1219
1220 fn paint(
1221 &mut self,
1222 bounds: RectF,
1223 visible_bounds: RectF,
1224 layout: &mut Self::LayoutState,
1225 cx: &mut PaintContext,
1226 ) -> Self::PaintState {
1227 cx.scene.push_layer(Some(bounds));
1228
1229 let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
1230 let text_bounds = RectF::new(
1231 bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
1232 layout.text_size,
1233 );
1234
1235 let mut paint_state = PaintState {
1236 bounds,
1237 gutter_bounds,
1238 text_bounds,
1239 hover_bounds: None,
1240 };
1241
1242 self.paint_background(gutter_bounds, text_bounds, layout, cx);
1243 if layout.gutter_size.x() > 0. {
1244 self.paint_gutter(gutter_bounds, visible_bounds, layout, cx);
1245 }
1246 self.paint_text(text_bounds, visible_bounds, layout, &mut paint_state, cx);
1247
1248 if !layout.blocks.is_empty() {
1249 cx.scene.push_layer(Some(bounds));
1250 self.paint_blocks(bounds, visible_bounds, layout, cx);
1251 cx.scene.pop_layer();
1252 }
1253
1254 cx.scene.pop_layer();
1255
1256 paint_state
1257 }
1258
1259 fn dispatch_event(
1260 &mut self,
1261 event: &Event,
1262 _: RectF,
1263 _: RectF,
1264 layout: &mut LayoutState,
1265 paint: &mut PaintState,
1266 cx: &mut EventContext,
1267 ) -> bool {
1268 if let Some((_, context_menu)) = &mut layout.context_menu {
1269 if context_menu.dispatch_event(event, cx) {
1270 return true;
1271 }
1272 }
1273
1274 if let Some((_, indicator)) = &mut layout.code_actions_indicator {
1275 if indicator.dispatch_event(event, cx) {
1276 return true;
1277 }
1278 }
1279
1280 if let Some((_, hover)) = &mut layout.hover {
1281 if hover.dispatch_event(event, cx) {
1282 return true;
1283 }
1284 }
1285
1286 for (_, block) in &mut layout.blocks {
1287 if block.dispatch_event(event, cx) {
1288 return true;
1289 }
1290 }
1291
1292 match event {
1293 Event::LeftMouseDown {
1294 position,
1295 cmd,
1296 alt,
1297 shift,
1298 click_count,
1299 ..
1300 } => self.mouse_down(
1301 *position,
1302 *cmd,
1303 *alt,
1304 *shift,
1305 *click_count,
1306 layout,
1307 paint,
1308 cx,
1309 ),
1310 Event::LeftMouseUp { position, .. } => self.mouse_up(*position, cx),
1311 Event::LeftMouseDragged { position } => {
1312 self.mouse_dragged(*position, layout, paint, cx)
1313 }
1314 Event::ScrollWheel {
1315 position,
1316 delta,
1317 precise,
1318 } => self.scroll(*position, *delta, *precise, layout, paint, cx),
1319 Event::KeyDown { input, .. } => self.key_down(input.as_deref(), cx),
1320 Event::MouseMoved { position, .. } => {
1321 if paint
1322 .hover_bounds
1323 .map_or(false, |hover_bounds| hover_bounds.contains_point(*position))
1324 {
1325 return false;
1326 }
1327
1328 let point = if paint.text_bounds.contains_point(*position) {
1329 let (point, overshoot) =
1330 paint.point_for_position(&self.snapshot(cx), layout, *position);
1331 if overshoot.is_zero() {
1332 Some(point)
1333 } else {
1334 None
1335 }
1336 } else {
1337 None
1338 };
1339
1340 cx.dispatch_action(HoverAt { point });
1341 true
1342 }
1343 _ => false,
1344 }
1345 }
1346
1347 fn debug(
1348 &self,
1349 bounds: RectF,
1350 _: &Self::LayoutState,
1351 _: &Self::PaintState,
1352 _: &gpui::DebugContext,
1353 ) -> json::Value {
1354 json!({
1355 "type": "BufferElement",
1356 "bounds": bounds.to_json()
1357 })
1358 }
1359}
1360
1361pub struct LayoutState {
1362 size: Vector2F,
1363 scroll_max: Vector2F,
1364 gutter_size: Vector2F,
1365 gutter_padding: f32,
1366 gutter_margin: f32,
1367 text_size: Vector2F,
1368 snapshot: EditorSnapshot,
1369 active_rows: BTreeMap<u32, bool>,
1370 highlighted_rows: Option<Range<u32>>,
1371 line_layouts: Vec<text_layout::Line>,
1372 line_number_layouts: Vec<Option<text_layout::Line>>,
1373 blocks: Vec<(u32, ElementBox)>,
1374 line_height: f32,
1375 em_width: f32,
1376 em_advance: f32,
1377 highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
1378 selections: Vec<(ReplicaId, Vec<SelectionLayout>)>,
1379 context_menu: Option<(DisplayPoint, ElementBox)>,
1380 code_actions_indicator: Option<(u32, ElementBox)>,
1381 hover: Option<(DisplayPoint, ElementBox)>,
1382}
1383
1384fn layout_line(
1385 row: u32,
1386 snapshot: &EditorSnapshot,
1387 style: &EditorStyle,
1388 layout_cache: &TextLayoutCache,
1389) -> text_layout::Line {
1390 let mut line = snapshot.line(row);
1391
1392 if line.len() > MAX_LINE_LEN {
1393 let mut len = MAX_LINE_LEN;
1394 while !line.is_char_boundary(len) {
1395 len -= 1;
1396 }
1397
1398 line.truncate(len);
1399 }
1400
1401 layout_cache.layout_str(
1402 &line,
1403 style.text.font_size,
1404 &[(
1405 snapshot.line_len(row) as usize,
1406 RunStyle {
1407 font_id: style.text.font_id,
1408 color: Color::black(),
1409 underline: Default::default(),
1410 },
1411 )],
1412 )
1413}
1414
1415pub struct PaintState {
1416 bounds: RectF,
1417 gutter_bounds: RectF,
1418 text_bounds: RectF,
1419 hover_bounds: Option<RectF>,
1420}
1421
1422impl PaintState {
1423 /// Returns two display points. The first is the nearest valid
1424 /// position in the current buffer and the second is the distance to the
1425 /// nearest valid position if there was overshoot.
1426 fn point_for_position(
1427 &self,
1428 snapshot: &EditorSnapshot,
1429 layout: &LayoutState,
1430 position: Vector2F,
1431 ) -> (DisplayPoint, DisplayPoint) {
1432 let scroll_position = snapshot.scroll_position();
1433 let position = position - self.text_bounds.origin();
1434 let y = position.y().max(0.0).min(layout.size.y());
1435 let row = ((y / layout.line_height) + scroll_position.y()) as u32;
1436 let row_overshoot = row.saturating_sub(snapshot.max_point().row());
1437 let row = cmp::min(row, snapshot.max_point().row());
1438 let line = &layout.line_layouts[(row - scroll_position.y() as u32) as usize];
1439 let x = position.x() + (scroll_position.x() * layout.em_width);
1440
1441 let column = if x >= 0.0 {
1442 line.index_for_x(x)
1443 .map(|ix| ix as u32)
1444 .unwrap_or_else(|| snapshot.line_len(row))
1445 } else {
1446 0
1447 };
1448 let column_overshoot = (0f32.max(x - line.width()) / layout.em_advance) as u32;
1449
1450 (
1451 DisplayPoint::new(row, column),
1452 DisplayPoint::new(row_overshoot, column_overshoot),
1453 )
1454 }
1455}
1456
1457#[derive(Copy, Clone, PartialEq, Eq)]
1458pub enum CursorShape {
1459 Bar,
1460 Block,
1461 Underscore,
1462}
1463
1464impl Default for CursorShape {
1465 fn default() -> Self {
1466 CursorShape::Bar
1467 }
1468}
1469
1470struct Cursor {
1471 origin: Vector2F,
1472 block_width: f32,
1473 line_height: f32,
1474 color: Color,
1475 shape: CursorShape,
1476 block_text: Option<Line>,
1477}
1478
1479impl Cursor {
1480 fn paint(&self, cx: &mut PaintContext) {
1481 let bounds = match self.shape {
1482 CursorShape::Bar => RectF::new(self.origin, vec2f(2.0, self.line_height)),
1483 CursorShape::Block => {
1484 RectF::new(self.origin, vec2f(self.block_width, self.line_height))
1485 }
1486 CursorShape::Underscore => RectF::new(
1487 self.origin + Vector2F::new(0.0, self.line_height - 2.0),
1488 vec2f(self.block_width, 2.0),
1489 ),
1490 };
1491
1492 cx.scene.push_quad(Quad {
1493 bounds,
1494 background: Some(self.color),
1495 border: Border::new(0., Color::black()),
1496 corner_radius: 0.,
1497 });
1498
1499 if let Some(block_text) = &self.block_text {
1500 block_text.paint(self.origin, bounds, self.line_height, cx);
1501 }
1502 }
1503}
1504
1505#[derive(Debug)]
1506struct HighlightedRange {
1507 start_y: f32,
1508 line_height: f32,
1509 lines: Vec<HighlightedRangeLine>,
1510 color: Color,
1511 corner_radius: f32,
1512}
1513
1514#[derive(Debug)]
1515struct HighlightedRangeLine {
1516 start_x: f32,
1517 end_x: f32,
1518}
1519
1520impl HighlightedRange {
1521 fn paint(&self, bounds: RectF, scene: &mut Scene) {
1522 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
1523 self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
1524 self.paint_lines(
1525 self.start_y + self.line_height,
1526 &self.lines[1..],
1527 bounds,
1528 scene,
1529 );
1530 } else {
1531 self.paint_lines(self.start_y, &self.lines, bounds, scene);
1532 }
1533 }
1534
1535 fn paint_lines(
1536 &self,
1537 start_y: f32,
1538 lines: &[HighlightedRangeLine],
1539 bounds: RectF,
1540 scene: &mut Scene,
1541 ) {
1542 if lines.is_empty() {
1543 return;
1544 }
1545
1546 let mut path = PathBuilder::new();
1547 let first_line = lines.first().unwrap();
1548 let last_line = lines.last().unwrap();
1549
1550 let first_top_left = vec2f(first_line.start_x, start_y);
1551 let first_top_right = vec2f(first_line.end_x, start_y);
1552
1553 let curve_height = vec2f(0., self.corner_radius);
1554 let curve_width = |start_x: f32, end_x: f32| {
1555 let max = (end_x - start_x) / 2.;
1556 let width = if max < self.corner_radius {
1557 max
1558 } else {
1559 self.corner_radius
1560 };
1561
1562 vec2f(width, 0.)
1563 };
1564
1565 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
1566 path.reset(first_top_right - top_curve_width);
1567 path.curve_to(first_top_right + curve_height, first_top_right);
1568
1569 let mut iter = lines.iter().enumerate().peekable();
1570 while let Some((ix, line)) = iter.next() {
1571 let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
1572
1573 if let Some((_, next_line)) = iter.peek() {
1574 let next_top_right = vec2f(next_line.end_x, bottom_right.y());
1575
1576 match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
1577 Ordering::Equal => {
1578 path.line_to(bottom_right);
1579 }
1580 Ordering::Less => {
1581 let curve_width = curve_width(next_top_right.x(), bottom_right.x());
1582 path.line_to(bottom_right - curve_height);
1583 if self.corner_radius > 0. {
1584 path.curve_to(bottom_right - curve_width, bottom_right);
1585 }
1586 path.line_to(next_top_right + curve_width);
1587 if self.corner_radius > 0. {
1588 path.curve_to(next_top_right + curve_height, next_top_right);
1589 }
1590 }
1591 Ordering::Greater => {
1592 let curve_width = curve_width(bottom_right.x(), next_top_right.x());
1593 path.line_to(bottom_right - curve_height);
1594 if self.corner_radius > 0. {
1595 path.curve_to(bottom_right + curve_width, bottom_right);
1596 }
1597 path.line_to(next_top_right - curve_width);
1598 if self.corner_radius > 0. {
1599 path.curve_to(next_top_right + curve_height, next_top_right);
1600 }
1601 }
1602 }
1603 } else {
1604 let curve_width = curve_width(line.start_x, line.end_x);
1605 path.line_to(bottom_right - curve_height);
1606 if self.corner_radius > 0. {
1607 path.curve_to(bottom_right - curve_width, bottom_right);
1608 }
1609
1610 let bottom_left = vec2f(line.start_x, bottom_right.y());
1611 path.line_to(bottom_left + curve_width);
1612 if self.corner_radius > 0. {
1613 path.curve_to(bottom_left - curve_height, bottom_left);
1614 }
1615 }
1616 }
1617
1618 if first_line.start_x > last_line.start_x {
1619 let curve_width = curve_width(last_line.start_x, first_line.start_x);
1620 let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
1621 path.line_to(second_top_left + curve_height);
1622 if self.corner_radius > 0. {
1623 path.curve_to(second_top_left + curve_width, second_top_left);
1624 }
1625 let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
1626 path.line_to(first_bottom_left - curve_width);
1627 if self.corner_radius > 0. {
1628 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
1629 }
1630 }
1631
1632 path.line_to(first_top_left + curve_height);
1633 if self.corner_radius > 0. {
1634 path.curve_to(first_top_left + top_curve_width, first_top_left);
1635 }
1636 path.line_to(first_top_right - top_curve_width);
1637
1638 scene.push_path(path.build(self.color, Some(bounds)));
1639 }
1640}
1641
1642fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
1643 delta.powf(1.5) / 100.0
1644}
1645
1646fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
1647 delta.powf(1.2) / 300.0
1648}
1649
1650#[cfg(test)]
1651mod tests {
1652 use std::sync::Arc;
1653
1654 use super::*;
1655 use crate::{
1656 display_map::{BlockDisposition, BlockProperties},
1657 Editor, MultiBuffer,
1658 };
1659 use settings::Settings;
1660 use util::test::sample_text;
1661
1662 #[gpui::test]
1663 fn test_layout_line_numbers(cx: &mut gpui::MutableAppContext) {
1664 cx.set_global(Settings::test(cx));
1665 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
1666 let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1667 Editor::new(EditorMode::Full, buffer, None, None, None, cx)
1668 });
1669 let element = EditorElement::new(
1670 editor.downgrade(),
1671 editor.read(cx).style(cx),
1672 CursorShape::Bar,
1673 );
1674
1675 let layouts = editor.update(cx, |editor, cx| {
1676 let snapshot = editor.snapshot(cx);
1677 let mut presenter = cx.build_presenter(window_id, 30.);
1678 let mut layout_cx = presenter.build_layout_context(Vector2F::zero(), false, cx);
1679 element.layout_line_numbers(0..6, &Default::default(), &snapshot, &mut layout_cx)
1680 });
1681 assert_eq!(layouts.len(), 6);
1682 }
1683
1684 #[gpui::test]
1685 fn test_layout_with_placeholder_text_and_blocks(cx: &mut gpui::MutableAppContext) {
1686 cx.set_global(Settings::test(cx));
1687 let buffer = MultiBuffer::build_simple("", cx);
1688 let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1689 Editor::new(EditorMode::Full, buffer, None, None, None, cx)
1690 });
1691
1692 editor.update(cx, |editor, cx| {
1693 editor.set_placeholder_text("hello", cx);
1694 editor.insert_blocks(
1695 [BlockProperties {
1696 disposition: BlockDisposition::Above,
1697 height: 3,
1698 position: Anchor::min(),
1699 render: Arc::new(|_| Empty::new().boxed()),
1700 }],
1701 cx,
1702 );
1703
1704 // Blur the editor so that it displays placeholder text.
1705 cx.blur();
1706 });
1707
1708 let mut element = EditorElement::new(
1709 editor.downgrade(),
1710 editor.read(cx).style(cx),
1711 CursorShape::Bar,
1712 );
1713
1714 let mut scene = Scene::new(1.0);
1715 let mut presenter = cx.build_presenter(window_id, 30.);
1716 let mut layout_cx = presenter.build_layout_context(Vector2F::zero(), false, cx);
1717 let (size, mut state) = element.layout(
1718 SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
1719 &mut layout_cx,
1720 );
1721
1722 assert_eq!(state.line_layouts.len(), 4);
1723 assert_eq!(
1724 state
1725 .line_number_layouts
1726 .iter()
1727 .map(Option::is_some)
1728 .collect::<Vec<_>>(),
1729 &[false, false, false, true]
1730 );
1731
1732 // Don't panic.
1733 let bounds = RectF::new(Default::default(), size);
1734 let mut paint_cx = presenter.build_paint_context(&mut scene, bounds.size(), cx);
1735 element.paint(bounds, bounds, &mut state, &mut paint_cx);
1736 }
1737}