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