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