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