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