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::{BlockStyle, DisplaySnapshot, TransformBlock},
8 hover_popover::HoverAt,
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 block in &mut layout.blocks {
621 let mut origin =
622 bounds.origin() + vec2f(0., block.row as f32 * layout.line_height - scroll_top);
623 if !matches!(block.style, BlockStyle::Sticky) {
624 origin += vec2f(-scroll_left, 0.);
625 }
626 block.element.paint(origin, visible_bounds, cx);
627 }
628 }
629
630 fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &LayoutContext) -> f32 {
631 let digit_count = (snapshot.max_buffer_row() as f32).log10().floor() as usize + 1;
632 let style = &self.style;
633
634 cx.text_layout_cache
635 .layout_str(
636 "1".repeat(digit_count).as_str(),
637 style.text.font_size,
638 &[(
639 digit_count,
640 RunStyle {
641 font_id: style.text.font_id,
642 color: Color::black(),
643 underline: Default::default(),
644 },
645 )],
646 )
647 .width()
648 }
649
650 fn layout_line_numbers(
651 &self,
652 rows: Range<u32>,
653 active_rows: &BTreeMap<u32, bool>,
654 snapshot: &EditorSnapshot,
655 cx: &LayoutContext,
656 ) -> Vec<Option<text_layout::Line>> {
657 let style = &self.style;
658 let include_line_numbers = snapshot.mode == EditorMode::Full;
659 let mut line_number_layouts = Vec::with_capacity(rows.len());
660 let mut line_number = String::new();
661 for (ix, row) in snapshot
662 .buffer_rows(rows.start)
663 .take((rows.end - rows.start) as usize)
664 .enumerate()
665 {
666 let display_row = rows.start + ix as u32;
667 let color = if active_rows.contains_key(&display_row) {
668 style.line_number_active
669 } else {
670 style.line_number
671 };
672 if let Some(buffer_row) = row {
673 if include_line_numbers {
674 line_number.clear();
675 write!(&mut line_number, "{}", buffer_row + 1).unwrap();
676 line_number_layouts.push(Some(cx.text_layout_cache.layout_str(
677 &line_number,
678 style.text.font_size,
679 &[(
680 line_number.len(),
681 RunStyle {
682 font_id: style.text.font_id,
683 color,
684 underline: Default::default(),
685 },
686 )],
687 )));
688 }
689 } else {
690 line_number_layouts.push(None);
691 }
692 }
693
694 line_number_layouts
695 }
696
697 fn layout_lines(
698 &mut self,
699 rows: Range<u32>,
700 snapshot: &EditorSnapshot,
701 cx: &LayoutContext,
702 ) -> Vec<text_layout::Line> {
703 if rows.start >= rows.end {
704 return Vec::new();
705 }
706
707 // When the editor is empty and unfocused, then show the placeholder.
708 if snapshot.is_empty() && !snapshot.is_focused() {
709 let placeholder_style = self
710 .style
711 .placeholder_text
712 .as_ref()
713 .unwrap_or_else(|| &self.style.text);
714 let placeholder_text = snapshot.placeholder_text();
715 let placeholder_lines = placeholder_text
716 .as_ref()
717 .map_or("", AsRef::as_ref)
718 .split('\n')
719 .skip(rows.start as usize)
720 .chain(iter::repeat(""))
721 .take(rows.len());
722 return placeholder_lines
723 .map(|line| {
724 cx.text_layout_cache.layout_str(
725 line,
726 placeholder_style.font_size,
727 &[(
728 line.len(),
729 RunStyle {
730 font_id: placeholder_style.font_id,
731 color: placeholder_style.color,
732 underline: Default::default(),
733 },
734 )],
735 )
736 })
737 .collect();
738 } else {
739 let style = &self.style;
740 let chunks = snapshot.chunks(rows.clone(), true).map(|chunk| {
741 let mut highlight_style = chunk
742 .syntax_highlight_id
743 .and_then(|id| id.style(&style.syntax));
744
745 if let Some(chunk_highlight) = chunk.highlight_style {
746 if let Some(highlight_style) = highlight_style.as_mut() {
747 highlight_style.highlight(chunk_highlight);
748 } else {
749 highlight_style = Some(chunk_highlight);
750 }
751 }
752
753 let mut diagnostic_highlight = HighlightStyle::default();
754
755 if chunk.is_unnecessary {
756 diagnostic_highlight.fade_out = Some(style.unnecessary_code_fade);
757 }
758
759 if let Some(severity) = chunk.diagnostic_severity {
760 // Omit underlines for HINT/INFO diagnostics on 'unnecessary' code.
761 if severity <= DiagnosticSeverity::WARNING || !chunk.is_unnecessary {
762 let diagnostic_style = super::diagnostic_style(severity, true, style);
763 diagnostic_highlight.underline = Some(Underline {
764 color: Some(diagnostic_style.message.text.color),
765 thickness: 1.0.into(),
766 squiggly: true,
767 });
768 }
769 }
770
771 if let Some(highlight_style) = highlight_style.as_mut() {
772 highlight_style.highlight(diagnostic_highlight);
773 } else {
774 highlight_style = Some(diagnostic_highlight);
775 }
776
777 (chunk.text, highlight_style)
778 });
779 layout_highlighted_chunks(
780 chunks,
781 &style.text,
782 &cx.text_layout_cache,
783 &cx.font_cache,
784 MAX_LINE_LEN,
785 rows.len() as usize,
786 )
787 }
788 }
789
790 fn layout_blocks(
791 &mut self,
792 rows: Range<u32>,
793 snapshot: &EditorSnapshot,
794 width: f32,
795 scroll_width: f32,
796 gutter_padding: f32,
797 gutter_width: f32,
798 em_width: f32,
799 text_x: f32,
800 line_height: f32,
801 style: &EditorStyle,
802 line_layouts: &[text_layout::Line],
803 cx: &mut LayoutContext,
804 ) -> (f32, Vec<BlockLayout>) {
805 let editor = if let Some(editor) = self.view.upgrade(cx) {
806 editor
807 } else {
808 return Default::default();
809 };
810
811 let tooltip_style = cx.global::<Settings>().theme.tooltip.clone();
812 let scroll_x = snapshot.scroll_position.x();
813 let (fixed_blocks, non_fixed_blocks) = snapshot
814 .blocks_in_range(rows.clone())
815 .partition::<Vec<_>, _>(|(_, block)| match block {
816 TransformBlock::ExcerptHeader { .. } => false,
817 TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
818 });
819 let mut render_block = |block: &TransformBlock, width: f32| {
820 let mut element = match block {
821 TransformBlock::Custom(block) => {
822 let align_to = block
823 .position()
824 .to_point(&snapshot.buffer_snapshot)
825 .to_display_point(snapshot);
826 let anchor_x = text_x
827 + if rows.contains(&align_to.row()) {
828 line_layouts[(align_to.row() - rows.start) as usize]
829 .x_for_index(align_to.column() as usize)
830 } else {
831 layout_line(align_to.row(), snapshot, style, cx.text_layout_cache)
832 .x_for_index(align_to.column() as usize)
833 };
834
835 cx.render(&editor, |_, cx| {
836 block.render(&mut BlockContext {
837 cx,
838 anchor_x,
839 gutter_padding,
840 line_height,
841 scroll_x,
842 gutter_width,
843 em_width,
844 })
845 })
846 }
847 TransformBlock::ExcerptHeader {
848 key,
849 buffer,
850 range,
851 starts_new_buffer,
852 ..
853 } => {
854 let jump_icon = project::File::from_dyn(buffer.file()).map(|file| {
855 let jump_position = range
856 .primary
857 .as_ref()
858 .map_or(range.context.start, |primary| primary.start);
859 let jump_action = crate::Jump {
860 path: ProjectPath {
861 worktree_id: file.worktree_id(cx),
862 path: file.path.clone(),
863 },
864 position: language::ToPoint::to_point(&jump_position, buffer),
865 anchor: jump_position,
866 };
867
868 enum JumpIcon {}
869 cx.render(&editor, |_, cx| {
870 MouseEventHandler::new::<JumpIcon, _, _>(*key, cx, |state, _| {
871 let style = style.jump_icon.style_for(state, false);
872 Svg::new("icons/jump.svg")
873 .with_color(style.color)
874 .constrained()
875 .with_width(style.icon_width)
876 .aligned()
877 .contained()
878 .with_style(style.container)
879 .constrained()
880 .with_width(style.button_width)
881 .with_height(style.button_width)
882 .boxed()
883 })
884 .with_cursor_style(CursorStyle::PointingHand)
885 .on_click(move |_, _, cx| cx.dispatch_action(jump_action.clone()))
886 .with_tooltip(
887 *key,
888 "Jump to Buffer".to_string(),
889 Some(Box::new(crate::OpenExcerpts)),
890 tooltip_style.clone(),
891 cx,
892 )
893 .aligned()
894 .flex_float()
895 .boxed()
896 })
897 });
898
899 if *starts_new_buffer {
900 let style = &self.style.diagnostic_path_header;
901 let font_size =
902 (style.text_scale_factor * self.style.text.font_size).round();
903
904 let mut filename = None;
905 let mut parent_path = None;
906 if let Some(file) = buffer.file() {
907 let path = file.path();
908 filename = path.file_name().map(|f| f.to_string_lossy().to_string());
909 parent_path =
910 path.parent().map(|p| p.to_string_lossy().to_string() + "/");
911 }
912
913 Flex::row()
914 .with_child(
915 Label::new(
916 filename.unwrap_or_else(|| "untitled".to_string()),
917 style.filename.text.clone().with_font_size(font_size),
918 )
919 .contained()
920 .with_style(style.filename.container)
921 .aligned()
922 .boxed(),
923 )
924 .with_children(parent_path.map(|path| {
925 Label::new(path, style.path.text.clone().with_font_size(font_size))
926 .contained()
927 .with_style(style.path.container)
928 .aligned()
929 .boxed()
930 }))
931 .with_children(jump_icon)
932 .contained()
933 .with_style(style.container)
934 .with_padding_left(gutter_padding)
935 .with_padding_right(gutter_padding)
936 .expanded()
937 .named("path header block")
938 } else {
939 let text_style = self.style.text.clone();
940 Flex::row()
941 .with_child(Label::new("…".to_string(), text_style).boxed())
942 .with_children(jump_icon)
943 .contained()
944 .with_padding_left(gutter_padding)
945 .with_padding_right(gutter_padding)
946 .expanded()
947 .named("collapsed context")
948 }
949 }
950 };
951
952 element.layout(
953 SizeConstraint {
954 min: Vector2F::zero(),
955 max: vec2f(width, block.height() as f32 * line_height),
956 },
957 cx,
958 );
959 element
960 };
961
962 let mut max_width = width.max(scroll_width);
963 let mut blocks = Vec::new();
964 for (row, block) in fixed_blocks {
965 let element = render_block(block, f32::INFINITY);
966 max_width = max_width.max(element.size().x() + em_width);
967 blocks.push(BlockLayout {
968 row,
969 element,
970 style: BlockStyle::Fixed,
971 });
972 }
973 for (row, block) in non_fixed_blocks {
974 let style = match block {
975 TransformBlock::Custom(block) => block.style(),
976 TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
977 };
978 let width = match style {
979 BlockStyle::Fixed => unreachable!(),
980 BlockStyle::Sticky => width,
981 BlockStyle::Flex => max_width,
982 };
983 let element = render_block(block, width);
984 blocks.push(BlockLayout {
985 row,
986 element,
987 style,
988 });
989 }
990 (max_width, blocks)
991 }
992}
993
994impl Element for EditorElement {
995 type LayoutState = LayoutState;
996 type PaintState = PaintState;
997
998 fn layout(
999 &mut self,
1000 constraint: SizeConstraint,
1001 cx: &mut LayoutContext,
1002 ) -> (Vector2F, Self::LayoutState) {
1003 let mut size = constraint.max;
1004 if size.x().is_infinite() {
1005 unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
1006 }
1007
1008 let snapshot = self.snapshot(cx.app);
1009 let style = self.style.clone();
1010 let line_height = style.text.line_height(cx.font_cache);
1011
1012 let gutter_padding;
1013 let gutter_width;
1014 let gutter_margin;
1015 if snapshot.mode == EditorMode::Full {
1016 gutter_padding = style.text.em_width(cx.font_cache) * style.gutter_padding_factor;
1017 gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
1018 gutter_margin = -style.text.descent(cx.font_cache);
1019 } else {
1020 gutter_padding = 0.0;
1021 gutter_width = 0.0;
1022 gutter_margin = 0.0;
1023 };
1024
1025 let text_width = size.x() - gutter_width;
1026 let em_width = style.text.em_width(cx.font_cache);
1027 let em_advance = style.text.em_advance(cx.font_cache);
1028 let overscroll = vec2f(em_width, 0.);
1029 let snapshot = self.update_view(cx.app, |view, cx| {
1030 let wrap_width = match view.soft_wrap_mode(cx) {
1031 SoftWrap::None => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
1032 SoftWrap::EditorWidth => {
1033 Some(text_width - gutter_margin - overscroll.x() - em_width)
1034 }
1035 SoftWrap::Column(column) => Some(column as f32 * em_advance),
1036 };
1037
1038 if view.set_wrap_width(wrap_width, cx) {
1039 view.snapshot(cx)
1040 } else {
1041 snapshot
1042 }
1043 });
1044
1045 let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
1046 if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
1047 size.set_y(
1048 scroll_height
1049 .min(constraint.max_along(Axis::Vertical))
1050 .max(constraint.min_along(Axis::Vertical))
1051 .min(line_height * max_lines as f32),
1052 )
1053 } else if let EditorMode::SingleLine = snapshot.mode {
1054 size.set_y(
1055 line_height
1056 .min(constraint.max_along(Axis::Vertical))
1057 .max(constraint.min_along(Axis::Vertical)),
1058 )
1059 } else if size.y().is_infinite() {
1060 size.set_y(scroll_height);
1061 }
1062 let gutter_size = vec2f(gutter_width, size.y());
1063 let text_size = vec2f(text_width, size.y());
1064
1065 let (autoscroll_horizontally, mut snapshot) = self.update_view(cx.app, |view, cx| {
1066 let autoscroll_horizontally = view.autoscroll_vertically(size.y(), line_height, cx);
1067 let snapshot = view.snapshot(cx);
1068 (autoscroll_horizontally, snapshot)
1069 });
1070
1071 let scroll_position = snapshot.scroll_position();
1072 let start_row = scroll_position.y() as u32;
1073 let scroll_top = scroll_position.y() * line_height;
1074
1075 // Add 1 to ensure selections bleed off screen
1076 let end_row = 1 + cmp::min(
1077 ((scroll_top + size.y()) / line_height).ceil() as u32,
1078 snapshot.max_point().row(),
1079 );
1080
1081 let start_anchor = if start_row == 0 {
1082 Anchor::min()
1083 } else {
1084 snapshot
1085 .buffer_snapshot
1086 .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
1087 };
1088 let end_anchor = if end_row > snapshot.max_point().row() {
1089 Anchor::max()
1090 } else {
1091 snapshot
1092 .buffer_snapshot
1093 .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
1094 };
1095
1096 let mut selections: Vec<(ReplicaId, Vec<SelectionLayout>)> = Vec::new();
1097 let mut active_rows = BTreeMap::new();
1098 let mut highlighted_rows = None;
1099 let mut highlighted_ranges = Vec::new();
1100 self.update_view(cx.app, |view, cx| {
1101 let display_map = view.display_map.update(cx, |map, cx| map.snapshot(cx));
1102
1103 highlighted_rows = view.highlighted_rows();
1104 let theme = cx.global::<Settings>().theme.as_ref();
1105 highlighted_ranges = view.background_highlights_in_range(
1106 start_anchor.clone()..end_anchor.clone(),
1107 &display_map,
1108 theme,
1109 );
1110
1111 let mut remote_selections = HashMap::default();
1112 for (replica_id, line_mode, selection) in display_map
1113 .buffer_snapshot
1114 .remote_selections_in_range(&(start_anchor.clone()..end_anchor.clone()))
1115 {
1116 // The local selections match the leader's selections.
1117 if Some(replica_id) == view.leader_replica_id {
1118 continue;
1119 }
1120 remote_selections
1121 .entry(replica_id)
1122 .or_insert(Vec::new())
1123 .push(SelectionLayout::new(selection, line_mode, &display_map));
1124 }
1125 selections.extend(remote_selections);
1126
1127 if view.show_local_selections {
1128 let mut local_selections = view
1129 .selections
1130 .disjoint_in_range(start_anchor..end_anchor, cx);
1131 local_selections.extend(view.selections.pending(cx));
1132 for selection in &local_selections {
1133 let is_empty = selection.start == selection.end;
1134 let selection_start = snapshot.prev_line_boundary(selection.start).1;
1135 let selection_end = snapshot.next_line_boundary(selection.end).1;
1136 for row in cmp::max(selection_start.row(), start_row)
1137 ..=cmp::min(selection_end.row(), end_row)
1138 {
1139 let contains_non_empty_selection =
1140 active_rows.entry(row).or_insert(!is_empty);
1141 *contains_non_empty_selection |= !is_empty;
1142 }
1143 }
1144
1145 // Render the local selections in the leader's color when following.
1146 let local_replica_id = view.leader_replica_id.unwrap_or(view.replica_id(cx));
1147
1148 selections.push((
1149 local_replica_id,
1150 local_selections
1151 .into_iter()
1152 .map(|selection| {
1153 SelectionLayout::new(selection, view.selections.line_mode, &display_map)
1154 })
1155 .collect(),
1156 ));
1157 }
1158 });
1159
1160 let line_number_layouts =
1161 self.layout_line_numbers(start_row..end_row, &active_rows, &snapshot, cx);
1162
1163 let mut max_visible_line_width = 0.0;
1164 let line_layouts = self.layout_lines(start_row..end_row, &snapshot, cx);
1165 for line in &line_layouts {
1166 if line.width() > max_visible_line_width {
1167 max_visible_line_width = line.width();
1168 }
1169 }
1170
1171 let style = self.style.clone();
1172 let longest_line_width = layout_line(
1173 snapshot.longest_row(),
1174 &snapshot,
1175 &style,
1176 cx.text_layout_cache,
1177 )
1178 .width();
1179 let mut scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
1180 let em_width = style.text.em_width(cx.font_cache);
1181 let (blocks_max_width, blocks) = self.layout_blocks(
1182 start_row..end_row,
1183 &snapshot,
1184 size.x(),
1185 scroll_width + gutter_width,
1186 gutter_padding,
1187 gutter_width,
1188 em_width,
1189 gutter_width + gutter_margin,
1190 line_height,
1191 &style,
1192 &line_layouts,
1193 cx,
1194 );
1195 scroll_width = scroll_width.max(blocks_max_width - gutter_width);
1196
1197 let max_row = snapshot.max_point().row();
1198 let scroll_max = vec2f(
1199 ((scroll_width - text_size.x()) / em_width).max(0.0),
1200 max_row.saturating_sub(1) as f32,
1201 );
1202
1203 self.update_view(cx.app, |view, cx| {
1204 let clamped = view.clamp_scroll_left(scroll_max.x());
1205 let autoscrolled;
1206 if autoscroll_horizontally {
1207 autoscrolled = view.autoscroll_horizontally(
1208 start_row,
1209 text_size.x(),
1210 scroll_width,
1211 em_width,
1212 &line_layouts,
1213 cx,
1214 );
1215 } else {
1216 autoscrolled = false;
1217 }
1218
1219 if clamped || autoscrolled {
1220 snapshot = view.snapshot(cx);
1221 }
1222 });
1223
1224 let mut context_menu = None;
1225 let mut code_actions_indicator = None;
1226 let mut hover = None;
1227 cx.render(&self.view.upgrade(cx).unwrap(), |view, cx| {
1228 let newest_selection_head = view
1229 .selections
1230 .newest::<usize>(cx)
1231 .head()
1232 .to_display_point(&snapshot);
1233
1234 let style = view.style(cx);
1235 if (start_row..end_row).contains(&newest_selection_head.row()) {
1236 if view.context_menu_visible() {
1237 context_menu =
1238 view.render_context_menu(newest_selection_head, style.clone(), cx);
1239 }
1240
1241 code_actions_indicator = view
1242 .render_code_actions_indicator(&style, cx)
1243 .map(|indicator| (newest_selection_head.row(), indicator));
1244 }
1245
1246 hover = view.hover_state.popover.clone().and_then(|hover| {
1247 let (point, rendered) = hover.render(&snapshot, style.clone(), cx);
1248 if point.row() >= snapshot.scroll_position().y() as u32 {
1249 if line_layouts.len() > (point.row() - start_row) as usize {
1250 return Some((point, rendered));
1251 }
1252 }
1253
1254 None
1255 });
1256 });
1257
1258 if let Some((_, context_menu)) = context_menu.as_mut() {
1259 context_menu.layout(
1260 SizeConstraint {
1261 min: Vector2F::zero(),
1262 max: vec2f(
1263 f32::INFINITY,
1264 (12. * line_height).min((size.y() - line_height) / 2.),
1265 ),
1266 },
1267 cx,
1268 );
1269 }
1270
1271 if let Some((_, indicator)) = code_actions_indicator.as_mut() {
1272 indicator.layout(
1273 SizeConstraint::strict_along(Axis::Vertical, line_height * 0.618),
1274 cx,
1275 );
1276 }
1277
1278 if let Some((_, hover)) = hover.as_mut() {
1279 hover.layout(
1280 SizeConstraint {
1281 min: Vector2F::zero(),
1282 max: vec2f(
1283 (120. * em_width) // Default size
1284 .min(size.x() / 2.) // Shrink to half of the editor width
1285 .max(20. * em_width), // Apply minimum width of 20 characters
1286 (16. * line_height) // Default size
1287 .min(size.y() / 2.) // Shrink to half of the editor height
1288 .max(4. * line_height), // Apply minimum height of 4 lines
1289 ),
1290 },
1291 cx,
1292 );
1293 }
1294
1295 (
1296 size,
1297 LayoutState {
1298 size,
1299 scroll_max,
1300 gutter_size,
1301 gutter_padding,
1302 text_size,
1303 gutter_margin,
1304 snapshot,
1305 active_rows,
1306 highlighted_rows,
1307 highlighted_ranges,
1308 line_layouts,
1309 line_number_layouts,
1310 blocks,
1311 line_height,
1312 em_width,
1313 em_advance,
1314 selections,
1315 context_menu,
1316 code_actions_indicator,
1317 hover,
1318 },
1319 )
1320 }
1321
1322 fn paint(
1323 &mut self,
1324 bounds: RectF,
1325 visible_bounds: RectF,
1326 layout: &mut Self::LayoutState,
1327 cx: &mut PaintContext,
1328 ) -> Self::PaintState {
1329 cx.scene.push_layer(Some(bounds));
1330
1331 let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
1332 let text_bounds = RectF::new(
1333 bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
1334 layout.text_size,
1335 );
1336
1337 let mut paint_state = PaintState {
1338 bounds,
1339 gutter_bounds,
1340 text_bounds,
1341 hover_bounds: None,
1342 };
1343
1344 self.paint_background(gutter_bounds, text_bounds, layout, cx);
1345 if layout.gutter_size.x() > 0. {
1346 self.paint_gutter(gutter_bounds, visible_bounds, layout, cx);
1347 }
1348 self.paint_text(text_bounds, visible_bounds, layout, &mut paint_state, cx);
1349
1350 if !layout.blocks.is_empty() {
1351 cx.scene.push_layer(Some(bounds));
1352 self.paint_blocks(bounds, visible_bounds, layout, cx);
1353 cx.scene.pop_layer();
1354 }
1355
1356 cx.scene.pop_layer();
1357
1358 paint_state
1359 }
1360
1361 fn dispatch_event(
1362 &mut self,
1363 event: &Event,
1364 _: RectF,
1365 _: RectF,
1366 layout: &mut LayoutState,
1367 paint: &mut PaintState,
1368 cx: &mut EventContext,
1369 ) -> bool {
1370 if let Some((_, context_menu)) = &mut layout.context_menu {
1371 if context_menu.dispatch_event(event, cx) {
1372 return true;
1373 }
1374 }
1375
1376 if let Some((_, indicator)) = &mut layout.code_actions_indicator {
1377 if indicator.dispatch_event(event, cx) {
1378 return true;
1379 }
1380 }
1381
1382 if let Some((_, hover)) = &mut layout.hover {
1383 if hover.dispatch_event(event, cx) {
1384 return true;
1385 }
1386 }
1387
1388 for block in &mut layout.blocks {
1389 if block.element.dispatch_event(event, cx) {
1390 return true;
1391 }
1392 }
1393
1394 match event {
1395 Event::LeftMouseDown {
1396 position,
1397 cmd,
1398 alt,
1399 shift,
1400 click_count,
1401 ..
1402 } => self.mouse_down(
1403 *position,
1404 *cmd,
1405 *alt,
1406 *shift,
1407 *click_count,
1408 layout,
1409 paint,
1410 cx,
1411 ),
1412 Event::LeftMouseUp { position, .. } => self.mouse_up(*position, cx),
1413 Event::LeftMouseDragged { position } => {
1414 self.mouse_dragged(*position, layout, paint, cx)
1415 }
1416 Event::ScrollWheel {
1417 position,
1418 delta,
1419 precise,
1420 } => self.scroll(*position, *delta, *precise, layout, paint, cx),
1421 Event::KeyDown { input, .. } => self.key_down(input.as_deref(), cx),
1422 Event::MouseMoved { position, .. } => {
1423 if paint
1424 .hover_bounds
1425 .map_or(false, |hover_bounds| hover_bounds.contains_point(*position))
1426 {
1427 return false;
1428 }
1429
1430 let point = if paint.text_bounds.contains_point(*position) {
1431 let (point, overshoot) =
1432 paint.point_for_position(&self.snapshot(cx), layout, *position);
1433 if overshoot.is_zero() {
1434 Some(point)
1435 } else {
1436 None
1437 }
1438 } else {
1439 None
1440 };
1441
1442 cx.dispatch_action(HoverAt { point });
1443 true
1444 }
1445 _ => false,
1446 }
1447 }
1448
1449 fn debug(
1450 &self,
1451 bounds: RectF,
1452 _: &Self::LayoutState,
1453 _: &Self::PaintState,
1454 _: &gpui::DebugContext,
1455 ) -> json::Value {
1456 json!({
1457 "type": "BufferElement",
1458 "bounds": bounds.to_json()
1459 })
1460 }
1461}
1462
1463pub struct LayoutState {
1464 size: Vector2F,
1465 scroll_max: Vector2F,
1466 gutter_size: Vector2F,
1467 gutter_padding: f32,
1468 gutter_margin: f32,
1469 text_size: Vector2F,
1470 snapshot: EditorSnapshot,
1471 active_rows: BTreeMap<u32, bool>,
1472 highlighted_rows: Option<Range<u32>>,
1473 line_layouts: Vec<text_layout::Line>,
1474 line_number_layouts: Vec<Option<text_layout::Line>>,
1475 blocks: Vec<BlockLayout>,
1476 line_height: f32,
1477 em_width: f32,
1478 em_advance: f32,
1479 highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
1480 selections: Vec<(ReplicaId, Vec<SelectionLayout>)>,
1481 context_menu: Option<(DisplayPoint, ElementBox)>,
1482 code_actions_indicator: Option<(u32, ElementBox)>,
1483 hover: Option<(DisplayPoint, ElementBox)>,
1484}
1485
1486struct BlockLayout {
1487 row: u32,
1488 element: ElementBox,
1489 style: BlockStyle,
1490}
1491
1492fn layout_line(
1493 row: u32,
1494 snapshot: &EditorSnapshot,
1495 style: &EditorStyle,
1496 layout_cache: &TextLayoutCache,
1497) -> text_layout::Line {
1498 let mut line = snapshot.line(row);
1499
1500 if line.len() > MAX_LINE_LEN {
1501 let mut len = MAX_LINE_LEN;
1502 while !line.is_char_boundary(len) {
1503 len -= 1;
1504 }
1505
1506 line.truncate(len);
1507 }
1508
1509 layout_cache.layout_str(
1510 &line,
1511 style.text.font_size,
1512 &[(
1513 snapshot.line_len(row) as usize,
1514 RunStyle {
1515 font_id: style.text.font_id,
1516 color: Color::black(),
1517 underline: Default::default(),
1518 },
1519 )],
1520 )
1521}
1522
1523pub struct PaintState {
1524 bounds: RectF,
1525 gutter_bounds: RectF,
1526 text_bounds: RectF,
1527 hover_bounds: Option<RectF>,
1528}
1529
1530impl PaintState {
1531 /// Returns two display points. The first is the nearest valid
1532 /// position in the current buffer and the second is the distance to the
1533 /// nearest valid position if there was overshoot.
1534 fn point_for_position(
1535 &self,
1536 snapshot: &EditorSnapshot,
1537 layout: &LayoutState,
1538 position: Vector2F,
1539 ) -> (DisplayPoint, DisplayPoint) {
1540 let scroll_position = snapshot.scroll_position();
1541 let position = position - self.text_bounds.origin();
1542 let y = position.y().max(0.0).min(layout.size.y());
1543 let row = ((y / layout.line_height) + scroll_position.y()) as u32;
1544 let row_overshoot = row.saturating_sub(snapshot.max_point().row());
1545 let row = cmp::min(row, snapshot.max_point().row());
1546 let line = &layout.line_layouts[(row - scroll_position.y() as u32) as usize];
1547 let x = position.x() + (scroll_position.x() * layout.em_width);
1548
1549 let column = if x >= 0.0 {
1550 line.index_for_x(x)
1551 .map(|ix| ix as u32)
1552 .unwrap_or_else(|| snapshot.line_len(row))
1553 } else {
1554 0
1555 };
1556 let column_overshoot = (0f32.max(x - line.width()) / layout.em_advance) as u32;
1557
1558 (
1559 DisplayPoint::new(row, column),
1560 DisplayPoint::new(row_overshoot, column_overshoot),
1561 )
1562 }
1563}
1564
1565#[derive(Copy, Clone, PartialEq, Eq)]
1566pub enum CursorShape {
1567 Bar,
1568 Block,
1569 Underscore,
1570}
1571
1572impl Default for CursorShape {
1573 fn default() -> Self {
1574 CursorShape::Bar
1575 }
1576}
1577
1578struct Cursor {
1579 origin: Vector2F,
1580 block_width: f32,
1581 line_height: f32,
1582 color: Color,
1583 shape: CursorShape,
1584 block_text: Option<Line>,
1585}
1586
1587impl Cursor {
1588 fn paint(&self, cx: &mut PaintContext) {
1589 let bounds = match self.shape {
1590 CursorShape::Bar => RectF::new(self.origin, vec2f(2.0, self.line_height)),
1591 CursorShape::Block => {
1592 RectF::new(self.origin, vec2f(self.block_width, self.line_height))
1593 }
1594 CursorShape::Underscore => RectF::new(
1595 self.origin + Vector2F::new(0.0, self.line_height - 2.0),
1596 vec2f(self.block_width, 2.0),
1597 ),
1598 };
1599
1600 cx.scene.push_quad(Quad {
1601 bounds,
1602 background: Some(self.color),
1603 border: Border::new(0., Color::black()),
1604 corner_radius: 0.,
1605 });
1606
1607 if let Some(block_text) = &self.block_text {
1608 block_text.paint(self.origin, bounds, self.line_height, cx);
1609 }
1610 }
1611}
1612
1613#[derive(Debug)]
1614struct HighlightedRange {
1615 start_y: f32,
1616 line_height: f32,
1617 lines: Vec<HighlightedRangeLine>,
1618 color: Color,
1619 corner_radius: f32,
1620}
1621
1622#[derive(Debug)]
1623struct HighlightedRangeLine {
1624 start_x: f32,
1625 end_x: f32,
1626}
1627
1628impl HighlightedRange {
1629 fn paint(&self, bounds: RectF, scene: &mut Scene) {
1630 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
1631 self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
1632 self.paint_lines(
1633 self.start_y + self.line_height,
1634 &self.lines[1..],
1635 bounds,
1636 scene,
1637 );
1638 } else {
1639 self.paint_lines(self.start_y, &self.lines, bounds, scene);
1640 }
1641 }
1642
1643 fn paint_lines(
1644 &self,
1645 start_y: f32,
1646 lines: &[HighlightedRangeLine],
1647 bounds: RectF,
1648 scene: &mut Scene,
1649 ) {
1650 if lines.is_empty() {
1651 return;
1652 }
1653
1654 let mut path = PathBuilder::new();
1655 let first_line = lines.first().unwrap();
1656 let last_line = lines.last().unwrap();
1657
1658 let first_top_left = vec2f(first_line.start_x, start_y);
1659 let first_top_right = vec2f(first_line.end_x, start_y);
1660
1661 let curve_height = vec2f(0., self.corner_radius);
1662 let curve_width = |start_x: f32, end_x: f32| {
1663 let max = (end_x - start_x) / 2.;
1664 let width = if max < self.corner_radius {
1665 max
1666 } else {
1667 self.corner_radius
1668 };
1669
1670 vec2f(width, 0.)
1671 };
1672
1673 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
1674 path.reset(first_top_right - top_curve_width);
1675 path.curve_to(first_top_right + curve_height, first_top_right);
1676
1677 let mut iter = lines.iter().enumerate().peekable();
1678 while let Some((ix, line)) = iter.next() {
1679 let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
1680
1681 if let Some((_, next_line)) = iter.peek() {
1682 let next_top_right = vec2f(next_line.end_x, bottom_right.y());
1683
1684 match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
1685 Ordering::Equal => {
1686 path.line_to(bottom_right);
1687 }
1688 Ordering::Less => {
1689 let curve_width = curve_width(next_top_right.x(), bottom_right.x());
1690 path.line_to(bottom_right - curve_height);
1691 if self.corner_radius > 0. {
1692 path.curve_to(bottom_right - curve_width, bottom_right);
1693 }
1694 path.line_to(next_top_right + curve_width);
1695 if self.corner_radius > 0. {
1696 path.curve_to(next_top_right + curve_height, next_top_right);
1697 }
1698 }
1699 Ordering::Greater => {
1700 let curve_width = curve_width(bottom_right.x(), next_top_right.x());
1701 path.line_to(bottom_right - curve_height);
1702 if self.corner_radius > 0. {
1703 path.curve_to(bottom_right + curve_width, bottom_right);
1704 }
1705 path.line_to(next_top_right - curve_width);
1706 if self.corner_radius > 0. {
1707 path.curve_to(next_top_right + curve_height, next_top_right);
1708 }
1709 }
1710 }
1711 } else {
1712 let curve_width = curve_width(line.start_x, line.end_x);
1713 path.line_to(bottom_right - curve_height);
1714 if self.corner_radius > 0. {
1715 path.curve_to(bottom_right - curve_width, bottom_right);
1716 }
1717
1718 let bottom_left = vec2f(line.start_x, bottom_right.y());
1719 path.line_to(bottom_left + curve_width);
1720 if self.corner_radius > 0. {
1721 path.curve_to(bottom_left - curve_height, bottom_left);
1722 }
1723 }
1724 }
1725
1726 if first_line.start_x > last_line.start_x {
1727 let curve_width = curve_width(last_line.start_x, first_line.start_x);
1728 let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
1729 path.line_to(second_top_left + curve_height);
1730 if self.corner_radius > 0. {
1731 path.curve_to(second_top_left + curve_width, second_top_left);
1732 }
1733 let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
1734 path.line_to(first_bottom_left - curve_width);
1735 if self.corner_radius > 0. {
1736 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
1737 }
1738 }
1739
1740 path.line_to(first_top_left + curve_height);
1741 if self.corner_radius > 0. {
1742 path.curve_to(first_top_left + top_curve_width, first_top_left);
1743 }
1744 path.line_to(first_top_right - top_curve_width);
1745
1746 scene.push_path(path.build(self.color, Some(bounds)));
1747 }
1748}
1749
1750fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
1751 delta.powf(1.5) / 100.0
1752}
1753
1754fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
1755 delta.powf(1.2) / 300.0
1756}
1757
1758#[cfg(test)]
1759mod tests {
1760 use std::sync::Arc;
1761
1762 use super::*;
1763 use crate::{
1764 display_map::{BlockDisposition, BlockProperties},
1765 Editor, MultiBuffer,
1766 };
1767 use settings::Settings;
1768 use util::test::sample_text;
1769
1770 #[gpui::test]
1771 fn test_layout_line_numbers(cx: &mut gpui::MutableAppContext) {
1772 cx.set_global(Settings::test(cx));
1773 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
1774 let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1775 Editor::new(EditorMode::Full, buffer, None, None, None, cx)
1776 });
1777 let element = EditorElement::new(
1778 editor.downgrade(),
1779 editor.read(cx).style(cx),
1780 CursorShape::Bar,
1781 );
1782
1783 let layouts = editor.update(cx, |editor, cx| {
1784 let snapshot = editor.snapshot(cx);
1785 let mut presenter = cx.build_presenter(window_id, 30.);
1786 let mut layout_cx = presenter.build_layout_context(Vector2F::zero(), false, cx);
1787 element.layout_line_numbers(0..6, &Default::default(), &snapshot, &mut layout_cx)
1788 });
1789 assert_eq!(layouts.len(), 6);
1790 }
1791
1792 #[gpui::test]
1793 fn test_layout_with_placeholder_text_and_blocks(cx: &mut gpui::MutableAppContext) {
1794 cx.set_global(Settings::test(cx));
1795 let buffer = MultiBuffer::build_simple("", cx);
1796 let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1797 Editor::new(EditorMode::Full, buffer, None, None, None, cx)
1798 });
1799
1800 editor.update(cx, |editor, cx| {
1801 editor.set_placeholder_text("hello", cx);
1802 editor.insert_blocks(
1803 [BlockProperties {
1804 style: BlockStyle::Fixed,
1805 disposition: BlockDisposition::Above,
1806 height: 3,
1807 position: Anchor::min(),
1808 render: Arc::new(|_| Empty::new().boxed()),
1809 }],
1810 cx,
1811 );
1812
1813 // Blur the editor so that it displays placeholder text.
1814 cx.blur();
1815 });
1816
1817 let mut element = EditorElement::new(
1818 editor.downgrade(),
1819 editor.read(cx).style(cx),
1820 CursorShape::Bar,
1821 );
1822
1823 let mut scene = Scene::new(1.0);
1824 let mut presenter = cx.build_presenter(window_id, 30.);
1825 let mut layout_cx = presenter.build_layout_context(Vector2F::zero(), false, cx);
1826 let (size, mut state) = element.layout(
1827 SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
1828 &mut layout_cx,
1829 );
1830
1831 assert_eq!(state.line_layouts.len(), 4);
1832 assert_eq!(
1833 state
1834 .line_number_layouts
1835 .iter()
1836 .map(Option::is_some)
1837 .collect::<Vec<_>>(),
1838 &[false, false, false, true]
1839 );
1840
1841 // Don't panic.
1842 let bounds = RectF::new(Default::default(), size);
1843 let mut paint_cx = presenter.build_paint_context(&mut scene, bounds.size(), cx);
1844 element.paint(bounds, bounds, &mut state, &mut paint_cx);
1845 }
1846}