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