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