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 editor_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::<JumpIcon, _>(
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 fixed_block_max_width = 0f32;
963 let mut blocks = Vec::new();
964 for (row, block) in fixed_blocks {
965 let element = render_block(block, f32::INFINITY);
966 fixed_block_max_width = fixed_block_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::Sticky => editor_width,
980 BlockStyle::Flex => editor_width
981 .max(fixed_block_max_width)
982 .max(gutter_width + scroll_width),
983 BlockStyle::Fixed => unreachable!(),
984 };
985 let element = render_block(block, width);
986 blocks.push(BlockLayout {
987 row,
988 element,
989 style,
990 });
991 }
992 (
993 scroll_width.max(fixed_block_max_width - gutter_width),
994 blocks,
995 )
996 }
997}
998
999impl Element for EditorElement {
1000 type LayoutState = LayoutState;
1001 type PaintState = PaintState;
1002
1003 fn layout(
1004 &mut self,
1005 constraint: SizeConstraint,
1006 cx: &mut LayoutContext,
1007 ) -> (Vector2F, Self::LayoutState) {
1008 let mut size = constraint.max;
1009 if size.x().is_infinite() {
1010 unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
1011 }
1012
1013 let snapshot = self.snapshot(cx.app);
1014 let style = self.style.clone();
1015 let line_height = style.text.line_height(cx.font_cache);
1016
1017 let gutter_padding;
1018 let gutter_width;
1019 let gutter_margin;
1020 if snapshot.mode == EditorMode::Full {
1021 gutter_padding = style.text.em_width(cx.font_cache) * style.gutter_padding_factor;
1022 gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
1023 gutter_margin = -style.text.descent(cx.font_cache);
1024 } else {
1025 gutter_padding = 0.0;
1026 gutter_width = 0.0;
1027 gutter_margin = 0.0;
1028 };
1029
1030 let text_width = size.x() - gutter_width;
1031 let em_width = style.text.em_width(cx.font_cache);
1032 let em_advance = style.text.em_advance(cx.font_cache);
1033 let overscroll = vec2f(em_width, 0.);
1034 let snapshot = self.update_view(cx.app, |view, cx| {
1035 let wrap_width = match view.soft_wrap_mode(cx) {
1036 SoftWrap::None => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
1037 SoftWrap::EditorWidth => {
1038 Some(text_width - gutter_margin - overscroll.x() - em_width)
1039 }
1040 SoftWrap::Column(column) => Some(column as f32 * em_advance),
1041 };
1042
1043 if view.set_wrap_width(wrap_width, cx) {
1044 view.snapshot(cx)
1045 } else {
1046 snapshot
1047 }
1048 });
1049
1050 let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
1051 if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
1052 size.set_y(
1053 scroll_height
1054 .min(constraint.max_along(Axis::Vertical))
1055 .max(constraint.min_along(Axis::Vertical))
1056 .min(line_height * max_lines as f32),
1057 )
1058 } else if let EditorMode::SingleLine = snapshot.mode {
1059 size.set_y(
1060 line_height
1061 .min(constraint.max_along(Axis::Vertical))
1062 .max(constraint.min_along(Axis::Vertical)),
1063 )
1064 } else if size.y().is_infinite() {
1065 size.set_y(scroll_height);
1066 }
1067 let gutter_size = vec2f(gutter_width, size.y());
1068 let text_size = vec2f(text_width, size.y());
1069
1070 let (autoscroll_horizontally, mut snapshot) = self.update_view(cx.app, |view, cx| {
1071 let autoscroll_horizontally = view.autoscroll_vertically(size.y(), line_height, cx);
1072 let snapshot = view.snapshot(cx);
1073 (autoscroll_horizontally, snapshot)
1074 });
1075
1076 let scroll_position = snapshot.scroll_position();
1077 let start_row = scroll_position.y() as u32;
1078 let scroll_top = scroll_position.y() * line_height;
1079
1080 // Add 1 to ensure selections bleed off screen
1081 let end_row = 1 + cmp::min(
1082 ((scroll_top + size.y()) / line_height).ceil() as u32,
1083 snapshot.max_point().row(),
1084 );
1085
1086 let start_anchor = if start_row == 0 {
1087 Anchor::min()
1088 } else {
1089 snapshot
1090 .buffer_snapshot
1091 .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
1092 };
1093 let end_anchor = if end_row > snapshot.max_point().row() {
1094 Anchor::max()
1095 } else {
1096 snapshot
1097 .buffer_snapshot
1098 .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
1099 };
1100
1101 let mut selections: Vec<(ReplicaId, Vec<SelectionLayout>)> = Vec::new();
1102 let mut active_rows = BTreeMap::new();
1103 let mut highlighted_rows = None;
1104 let mut highlighted_ranges = Vec::new();
1105 self.update_view(cx.app, |view, cx| {
1106 let display_map = view.display_map.update(cx, |map, cx| map.snapshot(cx));
1107
1108 highlighted_rows = view.highlighted_rows();
1109 let theme = cx.global::<Settings>().theme.as_ref();
1110 highlighted_ranges = view.background_highlights_in_range(
1111 start_anchor.clone()..end_anchor.clone(),
1112 &display_map,
1113 theme,
1114 );
1115
1116 let mut remote_selections = HashMap::default();
1117 for (replica_id, line_mode, selection) in display_map
1118 .buffer_snapshot
1119 .remote_selections_in_range(&(start_anchor.clone()..end_anchor.clone()))
1120 {
1121 // The local selections match the leader's selections.
1122 if Some(replica_id) == view.leader_replica_id {
1123 continue;
1124 }
1125 remote_selections
1126 .entry(replica_id)
1127 .or_insert(Vec::new())
1128 .push(SelectionLayout::new(selection, line_mode, &display_map));
1129 }
1130 selections.extend(remote_selections);
1131
1132 if view.show_local_selections {
1133 let mut local_selections = view
1134 .selections
1135 .disjoint_in_range(start_anchor..end_anchor, cx);
1136 local_selections.extend(view.selections.pending(cx));
1137 for selection in &local_selections {
1138 let is_empty = selection.start == selection.end;
1139 let selection_start = snapshot.prev_line_boundary(selection.start).1;
1140 let selection_end = snapshot.next_line_boundary(selection.end).1;
1141 for row in cmp::max(selection_start.row(), start_row)
1142 ..=cmp::min(selection_end.row(), end_row)
1143 {
1144 let contains_non_empty_selection =
1145 active_rows.entry(row).or_insert(!is_empty);
1146 *contains_non_empty_selection |= !is_empty;
1147 }
1148 }
1149
1150 // Render the local selections in the leader's color when following.
1151 let local_replica_id = view.leader_replica_id.unwrap_or(view.replica_id(cx));
1152
1153 selections.push((
1154 local_replica_id,
1155 local_selections
1156 .into_iter()
1157 .map(|selection| {
1158 SelectionLayout::new(selection, view.selections.line_mode, &display_map)
1159 })
1160 .collect(),
1161 ));
1162 }
1163 });
1164
1165 let line_number_layouts =
1166 self.layout_line_numbers(start_row..end_row, &active_rows, &snapshot, cx);
1167
1168 let mut max_visible_line_width = 0.0;
1169 let line_layouts = self.layout_lines(start_row..end_row, &snapshot, cx);
1170 for line in &line_layouts {
1171 if line.width() > max_visible_line_width {
1172 max_visible_line_width = line.width();
1173 }
1174 }
1175
1176 let style = self.style.clone();
1177 let longest_line_width = layout_line(
1178 snapshot.longest_row(),
1179 &snapshot,
1180 &style,
1181 cx.text_layout_cache,
1182 )
1183 .width();
1184 let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
1185 let em_width = style.text.em_width(cx.font_cache);
1186 let (scroll_width, blocks) = self.layout_blocks(
1187 start_row..end_row,
1188 &snapshot,
1189 size.x(),
1190 scroll_width,
1191 gutter_padding,
1192 gutter_width,
1193 em_width,
1194 gutter_width + gutter_margin,
1195 line_height,
1196 &style,
1197 &line_layouts,
1198 cx,
1199 );
1200
1201 let max_row = snapshot.max_point().row();
1202 let scroll_max = vec2f(
1203 ((scroll_width - text_size.x()) / em_width).max(0.0),
1204 max_row.saturating_sub(1) as f32,
1205 );
1206
1207 self.update_view(cx.app, |view, cx| {
1208 let clamped = view.clamp_scroll_left(scroll_max.x());
1209 let autoscrolled;
1210 if autoscroll_horizontally {
1211 autoscrolled = view.autoscroll_horizontally(
1212 start_row,
1213 text_size.x(),
1214 scroll_width,
1215 em_width,
1216 &line_layouts,
1217 cx,
1218 );
1219 } else {
1220 autoscrolled = false;
1221 }
1222
1223 if clamped || autoscrolled {
1224 snapshot = view.snapshot(cx);
1225 }
1226 });
1227
1228 let mut context_menu = None;
1229 let mut code_actions_indicator = None;
1230 let mut hover = None;
1231 cx.render(&self.view.upgrade(cx).unwrap(), |view, cx| {
1232 let newest_selection_head = view
1233 .selections
1234 .newest::<usize>(cx)
1235 .head()
1236 .to_display_point(&snapshot);
1237
1238 let style = view.style(cx);
1239 if (start_row..end_row).contains(&newest_selection_head.row()) {
1240 if view.context_menu_visible() {
1241 context_menu =
1242 view.render_context_menu(newest_selection_head, style.clone(), cx);
1243 }
1244
1245 code_actions_indicator = view
1246 .render_code_actions_indicator(&style, cx)
1247 .map(|indicator| (newest_selection_head.row(), indicator));
1248 }
1249
1250 hover = view.hover_state.popover.clone().and_then(|hover| {
1251 let (point, rendered) = hover.render(&snapshot, style.clone(), cx);
1252 if point.row() >= snapshot.scroll_position().y() as u32 {
1253 if line_layouts.len() > (point.row() - start_row) as usize {
1254 return Some((point, rendered));
1255 }
1256 }
1257
1258 None
1259 });
1260 });
1261
1262 if let Some((_, context_menu)) = context_menu.as_mut() {
1263 context_menu.layout(
1264 SizeConstraint {
1265 min: Vector2F::zero(),
1266 max: vec2f(
1267 cx.window_size.x() * 0.7,
1268 (12. * line_height).min((size.y() - line_height) / 2.),
1269 ),
1270 },
1271 cx,
1272 );
1273 }
1274
1275 if let Some((_, indicator)) = code_actions_indicator.as_mut() {
1276 indicator.layout(
1277 SizeConstraint::strict_along(Axis::Vertical, line_height * 0.618),
1278 cx,
1279 );
1280 }
1281
1282 if let Some((_, hover)) = hover.as_mut() {
1283 hover.layout(
1284 SizeConstraint {
1285 min: Vector2F::zero(),
1286 max: vec2f(
1287 (120. * em_width) // Default size
1288 .min(size.x() / 2.) // Shrink to half of the editor width
1289 .max(20. * em_width), // Apply minimum width of 20 characters
1290 (16. * line_height) // Default size
1291 .min(size.y() / 2.) // Shrink to half of the editor height
1292 .max(4. * line_height), // Apply minimum height of 4 lines
1293 ),
1294 },
1295 cx,
1296 );
1297 }
1298
1299 (
1300 size,
1301 LayoutState {
1302 size,
1303 scroll_max,
1304 gutter_size,
1305 gutter_padding,
1306 text_size,
1307 gutter_margin,
1308 snapshot,
1309 active_rows,
1310 highlighted_rows,
1311 highlighted_ranges,
1312 line_layouts,
1313 line_number_layouts,
1314 blocks,
1315 line_height,
1316 em_width,
1317 em_advance,
1318 selections,
1319 context_menu,
1320 code_actions_indicator,
1321 hover,
1322 },
1323 )
1324 }
1325
1326 fn paint(
1327 &mut self,
1328 bounds: RectF,
1329 visible_bounds: RectF,
1330 layout: &mut Self::LayoutState,
1331 cx: &mut PaintContext,
1332 ) -> Self::PaintState {
1333 cx.scene.push_layer(Some(bounds));
1334
1335 let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
1336 let text_bounds = RectF::new(
1337 bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
1338 layout.text_size,
1339 );
1340
1341 let mut paint_state = PaintState {
1342 bounds,
1343 gutter_bounds,
1344 text_bounds,
1345 hover_bounds: None,
1346 };
1347
1348 self.paint_background(gutter_bounds, text_bounds, layout, cx);
1349 if layout.gutter_size.x() > 0. {
1350 self.paint_gutter(gutter_bounds, visible_bounds, layout, cx);
1351 }
1352 self.paint_text(text_bounds, visible_bounds, layout, &mut paint_state, cx);
1353
1354 if !layout.blocks.is_empty() {
1355 cx.scene.push_layer(Some(bounds));
1356 self.paint_blocks(bounds, visible_bounds, layout, cx);
1357 cx.scene.pop_layer();
1358 }
1359
1360 cx.scene.pop_layer();
1361
1362 paint_state
1363 }
1364
1365 fn dispatch_event(
1366 &mut self,
1367 event: &Event,
1368 _: RectF,
1369 _: RectF,
1370 layout: &mut LayoutState,
1371 paint: &mut PaintState,
1372 cx: &mut EventContext,
1373 ) -> bool {
1374 if let Some((_, context_menu)) = &mut layout.context_menu {
1375 if context_menu.dispatch_event(event, cx) {
1376 return true;
1377 }
1378 }
1379
1380 if let Some((_, indicator)) = &mut layout.code_actions_indicator {
1381 if indicator.dispatch_event(event, cx) {
1382 return true;
1383 }
1384 }
1385
1386 if let Some((_, hover)) = &mut layout.hover {
1387 if hover.dispatch_event(event, cx) {
1388 return true;
1389 }
1390 }
1391
1392 for block in &mut layout.blocks {
1393 if block.element.dispatch_event(event, cx) {
1394 return true;
1395 }
1396 }
1397
1398 match event {
1399 Event::LeftMouseDown {
1400 position,
1401 cmd,
1402 alt,
1403 shift,
1404 click_count,
1405 ..
1406 } => self.mouse_down(
1407 *position,
1408 *cmd,
1409 *alt,
1410 *shift,
1411 *click_count,
1412 layout,
1413 paint,
1414 cx,
1415 ),
1416 Event::LeftMouseUp { position, .. } => self.mouse_up(*position, cx),
1417 Event::LeftMouseDragged { position } => {
1418 self.mouse_dragged(*position, layout, paint, cx)
1419 }
1420 Event::ScrollWheel {
1421 position,
1422 delta,
1423 precise,
1424 } => self.scroll(*position, *delta, *precise, layout, paint, cx),
1425 Event::KeyDown { input, .. } => self.key_down(input.as_deref(), cx),
1426 Event::MouseMoved { position, .. } => {
1427 if paint
1428 .hover_bounds
1429 .map_or(false, |hover_bounds| hover_bounds.contains_point(*position))
1430 {
1431 return false;
1432 }
1433
1434 let point = if paint.text_bounds.contains_point(*position) {
1435 let (point, overshoot) =
1436 paint.point_for_position(&self.snapshot(cx), layout, *position);
1437 if overshoot.is_zero() {
1438 Some(point)
1439 } else {
1440 None
1441 }
1442 } else {
1443 None
1444 };
1445
1446 cx.dispatch_action(HoverAt { point });
1447 true
1448 }
1449 _ => false,
1450 }
1451 }
1452
1453 fn debug(
1454 &self,
1455 bounds: RectF,
1456 _: &Self::LayoutState,
1457 _: &Self::PaintState,
1458 _: &gpui::DebugContext,
1459 ) -> json::Value {
1460 json!({
1461 "type": "BufferElement",
1462 "bounds": bounds.to_json()
1463 })
1464 }
1465}
1466
1467pub struct LayoutState {
1468 size: Vector2F,
1469 scroll_max: Vector2F,
1470 gutter_size: Vector2F,
1471 gutter_padding: f32,
1472 gutter_margin: f32,
1473 text_size: Vector2F,
1474 snapshot: EditorSnapshot,
1475 active_rows: BTreeMap<u32, bool>,
1476 highlighted_rows: Option<Range<u32>>,
1477 line_layouts: Vec<text_layout::Line>,
1478 line_number_layouts: Vec<Option<text_layout::Line>>,
1479 blocks: Vec<BlockLayout>,
1480 line_height: f32,
1481 em_width: f32,
1482 em_advance: f32,
1483 highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
1484 selections: Vec<(ReplicaId, Vec<SelectionLayout>)>,
1485 context_menu: Option<(DisplayPoint, ElementBox)>,
1486 code_actions_indicator: Option<(u32, ElementBox)>,
1487 hover: Option<(DisplayPoint, ElementBox)>,
1488}
1489
1490struct BlockLayout {
1491 row: u32,
1492 element: ElementBox,
1493 style: BlockStyle,
1494}
1495
1496fn layout_line(
1497 row: u32,
1498 snapshot: &EditorSnapshot,
1499 style: &EditorStyle,
1500 layout_cache: &TextLayoutCache,
1501) -> text_layout::Line {
1502 let mut line = snapshot.line(row);
1503
1504 if line.len() > MAX_LINE_LEN {
1505 let mut len = MAX_LINE_LEN;
1506 while !line.is_char_boundary(len) {
1507 len -= 1;
1508 }
1509
1510 line.truncate(len);
1511 }
1512
1513 layout_cache.layout_str(
1514 &line,
1515 style.text.font_size,
1516 &[(
1517 snapshot.line_len(row) as usize,
1518 RunStyle {
1519 font_id: style.text.font_id,
1520 color: Color::black(),
1521 underline: Default::default(),
1522 },
1523 )],
1524 )
1525}
1526
1527pub struct PaintState {
1528 bounds: RectF,
1529 gutter_bounds: RectF,
1530 text_bounds: RectF,
1531 hover_bounds: Option<RectF>,
1532}
1533
1534impl PaintState {
1535 /// Returns two display points. The first is the nearest valid
1536 /// position in the current buffer and the second is the distance to the
1537 /// nearest valid position if there was overshoot.
1538 fn point_for_position(
1539 &self,
1540 snapshot: &EditorSnapshot,
1541 layout: &LayoutState,
1542 position: Vector2F,
1543 ) -> (DisplayPoint, DisplayPoint) {
1544 let scroll_position = snapshot.scroll_position();
1545 let position = position - self.text_bounds.origin();
1546 let y = position.y().max(0.0).min(layout.size.y());
1547 let row = ((y / layout.line_height) + scroll_position.y()) as u32;
1548 let row_overshoot = row.saturating_sub(snapshot.max_point().row());
1549 let row = cmp::min(row, snapshot.max_point().row());
1550 let line = &layout.line_layouts[(row - scroll_position.y() as u32) as usize];
1551 let x = position.x() + (scroll_position.x() * layout.em_width);
1552
1553 let column = if x >= 0.0 {
1554 line.index_for_x(x)
1555 .map(|ix| ix as u32)
1556 .unwrap_or_else(|| snapshot.line_len(row))
1557 } else {
1558 0
1559 };
1560 let column_overshoot = (0f32.max(x - line.width()) / layout.em_advance) as u32;
1561
1562 (
1563 DisplayPoint::new(row, column),
1564 DisplayPoint::new(row_overshoot, column_overshoot),
1565 )
1566 }
1567}
1568
1569#[derive(Copy, Clone, PartialEq, Eq)]
1570pub enum CursorShape {
1571 Bar,
1572 Block,
1573 Underscore,
1574}
1575
1576impl Default for CursorShape {
1577 fn default() -> Self {
1578 CursorShape::Bar
1579 }
1580}
1581
1582struct Cursor {
1583 origin: Vector2F,
1584 block_width: f32,
1585 line_height: f32,
1586 color: Color,
1587 shape: CursorShape,
1588 block_text: Option<Line>,
1589}
1590
1591impl Cursor {
1592 fn paint(&self, cx: &mut PaintContext) {
1593 let bounds = match self.shape {
1594 CursorShape::Bar => RectF::new(self.origin, vec2f(2.0, self.line_height)),
1595 CursorShape::Block => {
1596 RectF::new(self.origin, vec2f(self.block_width, self.line_height))
1597 }
1598 CursorShape::Underscore => RectF::new(
1599 self.origin + Vector2F::new(0.0, self.line_height - 2.0),
1600 vec2f(self.block_width, 2.0),
1601 ),
1602 };
1603
1604 cx.scene.push_quad(Quad {
1605 bounds,
1606 background: Some(self.color),
1607 border: Border::new(0., Color::black()),
1608 corner_radius: 0.,
1609 });
1610
1611 if let Some(block_text) = &self.block_text {
1612 block_text.paint(self.origin, bounds, self.line_height, cx);
1613 }
1614 }
1615}
1616
1617#[derive(Debug)]
1618struct HighlightedRange {
1619 start_y: f32,
1620 line_height: f32,
1621 lines: Vec<HighlightedRangeLine>,
1622 color: Color,
1623 corner_radius: f32,
1624}
1625
1626#[derive(Debug)]
1627struct HighlightedRangeLine {
1628 start_x: f32,
1629 end_x: f32,
1630}
1631
1632impl HighlightedRange {
1633 fn paint(&self, bounds: RectF, scene: &mut Scene) {
1634 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
1635 self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
1636 self.paint_lines(
1637 self.start_y + self.line_height,
1638 &self.lines[1..],
1639 bounds,
1640 scene,
1641 );
1642 } else {
1643 self.paint_lines(self.start_y, &self.lines, bounds, scene);
1644 }
1645 }
1646
1647 fn paint_lines(
1648 &self,
1649 start_y: f32,
1650 lines: &[HighlightedRangeLine],
1651 bounds: RectF,
1652 scene: &mut Scene,
1653 ) {
1654 if lines.is_empty() {
1655 return;
1656 }
1657
1658 let mut path = PathBuilder::new();
1659 let first_line = lines.first().unwrap();
1660 let last_line = lines.last().unwrap();
1661
1662 let first_top_left = vec2f(first_line.start_x, start_y);
1663 let first_top_right = vec2f(first_line.end_x, start_y);
1664
1665 let curve_height = vec2f(0., self.corner_radius);
1666 let curve_width = |start_x: f32, end_x: f32| {
1667 let max = (end_x - start_x) / 2.;
1668 let width = if max < self.corner_radius {
1669 max
1670 } else {
1671 self.corner_radius
1672 };
1673
1674 vec2f(width, 0.)
1675 };
1676
1677 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
1678 path.reset(first_top_right - top_curve_width);
1679 path.curve_to(first_top_right + curve_height, first_top_right);
1680
1681 let mut iter = lines.iter().enumerate().peekable();
1682 while let Some((ix, line)) = iter.next() {
1683 let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
1684
1685 if let Some((_, next_line)) = iter.peek() {
1686 let next_top_right = vec2f(next_line.end_x, bottom_right.y());
1687
1688 match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
1689 Ordering::Equal => {
1690 path.line_to(bottom_right);
1691 }
1692 Ordering::Less => {
1693 let curve_width = curve_width(next_top_right.x(), bottom_right.x());
1694 path.line_to(bottom_right - curve_height);
1695 if self.corner_radius > 0. {
1696 path.curve_to(bottom_right - curve_width, bottom_right);
1697 }
1698 path.line_to(next_top_right + curve_width);
1699 if self.corner_radius > 0. {
1700 path.curve_to(next_top_right + curve_height, next_top_right);
1701 }
1702 }
1703 Ordering::Greater => {
1704 let curve_width = curve_width(bottom_right.x(), next_top_right.x());
1705 path.line_to(bottom_right - curve_height);
1706 if self.corner_radius > 0. {
1707 path.curve_to(bottom_right + curve_width, bottom_right);
1708 }
1709 path.line_to(next_top_right - curve_width);
1710 if self.corner_radius > 0. {
1711 path.curve_to(next_top_right + curve_height, next_top_right);
1712 }
1713 }
1714 }
1715 } else {
1716 let curve_width = curve_width(line.start_x, line.end_x);
1717 path.line_to(bottom_right - curve_height);
1718 if self.corner_radius > 0. {
1719 path.curve_to(bottom_right - curve_width, bottom_right);
1720 }
1721
1722 let bottom_left = vec2f(line.start_x, bottom_right.y());
1723 path.line_to(bottom_left + curve_width);
1724 if self.corner_radius > 0. {
1725 path.curve_to(bottom_left - curve_height, bottom_left);
1726 }
1727 }
1728 }
1729
1730 if first_line.start_x > last_line.start_x {
1731 let curve_width = curve_width(last_line.start_x, first_line.start_x);
1732 let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
1733 path.line_to(second_top_left + curve_height);
1734 if self.corner_radius > 0. {
1735 path.curve_to(second_top_left + curve_width, second_top_left);
1736 }
1737 let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
1738 path.line_to(first_bottom_left - curve_width);
1739 if self.corner_radius > 0. {
1740 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
1741 }
1742 }
1743
1744 path.line_to(first_top_left + curve_height);
1745 if self.corner_radius > 0. {
1746 path.curve_to(first_top_left + top_curve_width, first_top_left);
1747 }
1748 path.line_to(first_top_right - top_curve_width);
1749
1750 scene.push_path(path.build(self.color, Some(bounds)));
1751 }
1752}
1753
1754fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
1755 delta.powf(1.5) / 100.0
1756}
1757
1758fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
1759 delta.powf(1.2) / 300.0
1760}
1761
1762#[cfg(test)]
1763mod tests {
1764 use std::sync::Arc;
1765
1766 use super::*;
1767 use crate::{
1768 display_map::{BlockDisposition, BlockProperties},
1769 Editor, MultiBuffer,
1770 };
1771 use settings::Settings;
1772 use util::test::sample_text;
1773
1774 #[gpui::test]
1775 fn test_layout_line_numbers(cx: &mut gpui::MutableAppContext) {
1776 cx.set_global(Settings::test(cx));
1777 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
1778 let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1779 Editor::new(EditorMode::Full, buffer, None, None, None, cx)
1780 });
1781 let element = EditorElement::new(
1782 editor.downgrade(),
1783 editor.read(cx).style(cx),
1784 CursorShape::Bar,
1785 );
1786
1787 let layouts = editor.update(cx, |editor, cx| {
1788 let snapshot = editor.snapshot(cx);
1789 let mut presenter = cx.build_presenter(window_id, 30.);
1790 let mut layout_cx = presenter.build_layout_context(Vector2F::zero(), false, cx);
1791 element.layout_line_numbers(0..6, &Default::default(), &snapshot, &mut layout_cx)
1792 });
1793 assert_eq!(layouts.len(), 6);
1794 }
1795
1796 #[gpui::test]
1797 fn test_layout_with_placeholder_text_and_blocks(cx: &mut gpui::MutableAppContext) {
1798 cx.set_global(Settings::test(cx));
1799 let buffer = MultiBuffer::build_simple("", cx);
1800 let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1801 Editor::new(EditorMode::Full, buffer, None, None, None, cx)
1802 });
1803
1804 editor.update(cx, |editor, cx| {
1805 editor.set_placeholder_text("hello", cx);
1806 editor.insert_blocks(
1807 [BlockProperties {
1808 style: BlockStyle::Fixed,
1809 disposition: BlockDisposition::Above,
1810 height: 3,
1811 position: Anchor::min(),
1812 render: Arc::new(|_| Empty::new().boxed()),
1813 }],
1814 cx,
1815 );
1816
1817 // Blur the editor so that it displays placeholder text.
1818 cx.blur();
1819 });
1820
1821 let mut element = EditorElement::new(
1822 editor.downgrade(),
1823 editor.read(cx).style(cx),
1824 CursorShape::Bar,
1825 );
1826
1827 let mut scene = Scene::new(1.0);
1828 let mut presenter = cx.build_presenter(window_id, 30.);
1829 let mut layout_cx = presenter.build_layout_context(Vector2F::zero(), false, cx);
1830 let (size, mut state) = element.layout(
1831 SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
1832 &mut layout_cx,
1833 );
1834
1835 assert_eq!(state.line_layouts.len(), 4);
1836 assert_eq!(
1837 state
1838 .line_number_layouts
1839 .iter()
1840 .map(Option::is_some)
1841 .collect::<Vec<_>>(),
1842 &[false, false, false, true]
1843 );
1844
1845 // Don't panic.
1846 let bounds = RectF::new(Default::default(), size);
1847 let mut paint_cx = presenter.build_paint_context(&mut scene, bounds.size(), cx);
1848 element.paint(bounds, bounds, &mut state, &mut paint_cx);
1849 }
1850}