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