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