1use super::{
2 display_map::{BlockContext, ToDisplayPoint},
3 Anchor, DisplayPoint, Editor, EditorMode, EditorSnapshot, SelectPhase, SoftWrap, ToPoint,
4 MAX_LINE_LEN,
5};
6use crate::{
7 display_map::{BlockStyle, DisplaySnapshot, FoldStatus, InlayOffset, TransformBlock},
8 editor_settings::ShowScrollbar,
9 git::{diff_hunk_to_display, DisplayDiffHunk},
10 hover_popover::{
11 hide_hover, hover_at, HOVER_POPOVER_GAP, MIN_POPOVER_CHARACTER_WIDTH,
12 MIN_POPOVER_LINE_HEIGHT,
13 },
14 link_go_to_definition::{
15 go_to_fetched_definition, go_to_fetched_type_definition, update_go_to_definition_link,
16 },
17 mouse_context_menu, EditorSettings, EditorStyle, GutterHover, UnfoldAt,
18};
19use clock::ReplicaId;
20use collections::{BTreeMap, HashMap};
21use git::diff::DiffHunkStatus;
22use gpui::{
23 color::Color,
24 elements::*,
25 fonts::{HighlightStyle, TextStyle, Underline},
26 geometry::{
27 rect::RectF,
28 vector::{vec2f, Vector2F},
29 PathBuilder,
30 },
31 json::{self, ToJson},
32 platform::{CursorStyle, Modifiers, MouseButton, MouseButtonEvent, MouseMovedEvent},
33 text_layout::{self, Line, RunStyle, TextLayoutCache},
34 AnyElement, Axis, Border, CursorRegion, Element, EventContext, FontCache, LayoutContext,
35 MouseRegion, PaintContext, Quad, SceneBuilder, SizeConstraint, ViewContext, WindowContext,
36};
37use itertools::Itertools;
38use json::json;
39use language::{
40 language_settings::ShowWhitespaceSetting, Bias, CursorShape, DiagnosticSeverity, OffsetUtf16,
41 Selection,
42};
43use project::{
44 project_settings::{GitGutterSetting, ProjectSettings},
45 InlayHintLabelPart, ProjectPath,
46};
47use smallvec::SmallVec;
48use std::{
49 borrow::Cow,
50 cmp::{self, Ordering},
51 fmt::Write,
52 iter,
53 ops::Range,
54 sync::Arc,
55};
56use text::Point;
57use workspace::item::Item;
58
59enum FoldMarkers {}
60
61struct SelectionLayout {
62 head: DisplayPoint,
63 cursor_shape: CursorShape,
64 is_newest: bool,
65 is_local: bool,
66 range: Range<DisplayPoint>,
67 active_rows: Range<u32>,
68}
69
70impl SelectionLayout {
71 fn new<T: ToPoint + ToDisplayPoint + Clone>(
72 selection: Selection<T>,
73 line_mode: bool,
74 cursor_shape: CursorShape,
75 map: &DisplaySnapshot,
76 is_newest: bool,
77 is_local: bool,
78 ) -> Self {
79 let point_selection = selection.map(|p| p.to_point(&map.buffer_snapshot));
80 let display_selection = point_selection.map(|p| p.to_display_point(map));
81 let mut range = display_selection.range();
82 let mut head = display_selection.head();
83 let mut active_rows = map.prev_line_boundary(point_selection.start).1.row()
84 ..map.next_line_boundary(point_selection.end).1.row();
85
86 // vim visual line mode
87 if line_mode {
88 let point_range = map.expand_to_line(point_selection.range());
89 range = point_range.start.to_display_point(map)..point_range.end.to_display_point(map);
90 }
91
92 // any vim visual mode (including line mode)
93 if cursor_shape == CursorShape::Block && !range.is_empty() && !selection.reversed {
94 if head.column() > 0 {
95 head = map.clip_point(DisplayPoint::new(head.row(), head.column() - 1), Bias::Left)
96 } else if head.row() > 0 && head != map.max_point() {
97 head = map.clip_point(
98 DisplayPoint::new(head.row() - 1, map.line_len(head.row() - 1)),
99 Bias::Left,
100 );
101 // updating range.end is a no-op unless you're cursor is
102 // on the newline containing a multi-buffer divider
103 // in which case the clip_point may have moved the head up
104 // an additional row.
105 range.end = DisplayPoint::new(head.row() + 1, 0);
106 active_rows.end = head.row();
107 }
108 }
109
110 Self {
111 head,
112 cursor_shape,
113 is_newest,
114 is_local,
115 range,
116 active_rows,
117 }
118 }
119}
120
121pub struct EditorElement {
122 style: Arc<EditorStyle>,
123}
124
125impl EditorElement {
126 pub fn new(style: EditorStyle) -> Self {
127 Self {
128 style: Arc::new(style),
129 }
130 }
131
132 fn attach_mouse_handlers(
133 scene: &mut SceneBuilder,
134 position_map: &Arc<PositionMap>,
135 has_popovers: bool,
136 visible_bounds: RectF,
137 text_bounds: RectF,
138 gutter_bounds: RectF,
139 bounds: RectF,
140 cx: &mut ViewContext<Editor>,
141 ) {
142 enum EditorElementMouseHandlers {}
143 scene.push_mouse_region(
144 MouseRegion::new::<EditorElementMouseHandlers>(
145 cx.view_id(),
146 cx.view_id(),
147 visible_bounds,
148 )
149 .on_down(MouseButton::Left, {
150 let position_map = position_map.clone();
151 move |event, editor, cx| {
152 if !Self::mouse_down(
153 editor,
154 event.platform_event,
155 position_map.as_ref(),
156 text_bounds,
157 gutter_bounds,
158 cx,
159 ) {
160 cx.propagate_event();
161 }
162 }
163 })
164 .on_down(MouseButton::Right, {
165 let position_map = position_map.clone();
166 move |event, editor, cx| {
167 if !Self::mouse_right_down(
168 editor,
169 event.position,
170 position_map.as_ref(),
171 text_bounds,
172 cx,
173 ) {
174 cx.propagate_event();
175 }
176 }
177 })
178 .on_up(MouseButton::Left, {
179 let position_map = position_map.clone();
180 move |event, editor, cx| {
181 if !Self::mouse_up(
182 editor,
183 event.position,
184 event.cmd,
185 event.shift,
186 event.alt,
187 position_map.as_ref(),
188 text_bounds,
189 cx,
190 ) {
191 cx.propagate_event()
192 }
193 }
194 })
195 .on_drag(MouseButton::Left, {
196 let position_map = position_map.clone();
197 move |event, editor, cx| {
198 if event.end {
199 return;
200 }
201
202 if !Self::mouse_dragged(
203 editor,
204 event.platform_event,
205 position_map.as_ref(),
206 text_bounds,
207 cx,
208 ) {
209 cx.propagate_event()
210 }
211 }
212 })
213 .on_move({
214 let position_map = position_map.clone();
215 move |event, editor, cx| {
216 if !Self::mouse_moved(
217 editor,
218 event.platform_event,
219 &position_map,
220 text_bounds,
221 cx,
222 ) {
223 cx.propagate_event()
224 }
225 }
226 })
227 .on_move_out(move |_, editor: &mut Editor, cx| {
228 if has_popovers {
229 hide_hover(editor, cx);
230 }
231 })
232 .on_scroll({
233 let position_map = position_map.clone();
234 move |event, editor, cx| {
235 if !Self::scroll(
236 editor,
237 event.position,
238 *event.delta.raw(),
239 event.delta.precise(),
240 &position_map,
241 bounds,
242 cx,
243 ) {
244 cx.propagate_event()
245 }
246 }
247 }),
248 );
249
250 enum GutterHandlers {}
251 scene.push_mouse_region(
252 MouseRegion::new::<GutterHandlers>(cx.view_id(), cx.view_id() + 1, gutter_bounds)
253 .on_hover(|hover, editor: &mut Editor, cx| {
254 editor.gutter_hover(
255 &GutterHover {
256 hovered: hover.started,
257 },
258 cx,
259 );
260 }),
261 )
262 }
263
264 fn mouse_down(
265 editor: &mut Editor,
266 MouseButtonEvent {
267 position,
268 modifiers:
269 Modifiers {
270 shift,
271 ctrl,
272 alt,
273 cmd,
274 ..
275 },
276 mut click_count,
277 ..
278 }: MouseButtonEvent,
279 position_map: &PositionMap,
280 text_bounds: RectF,
281 gutter_bounds: RectF,
282 cx: &mut EventContext<Editor>,
283 ) -> bool {
284 if gutter_bounds.contains_point(position) {
285 click_count = 3; // Simulate triple-click when clicking the gutter to select lines
286 } else if !text_bounds.contains_point(position) {
287 return false;
288 }
289
290 let point_for_position = position_map.point_for_position(text_bounds, position);
291 let position = point_for_position.previous_valid;
292 if shift && alt {
293 editor.select(
294 SelectPhase::BeginColumnar {
295 position,
296 goal_column: point_for_position.exact_unclipped.column(),
297 },
298 cx,
299 );
300 } else if shift && !ctrl && !alt && !cmd {
301 editor.select(
302 SelectPhase::Extend {
303 position,
304 click_count,
305 },
306 cx,
307 );
308 } else {
309 editor.select(
310 SelectPhase::Begin {
311 position,
312 add: alt,
313 click_count,
314 },
315 cx,
316 );
317 }
318
319 true
320 }
321
322 fn mouse_right_down(
323 editor: &mut Editor,
324 position: Vector2F,
325 position_map: &PositionMap,
326 text_bounds: RectF,
327 cx: &mut EventContext<Editor>,
328 ) -> bool {
329 if !text_bounds.contains_point(position) {
330 return false;
331 }
332 let point_for_position = position_map.point_for_position(text_bounds, position);
333 mouse_context_menu::deploy_context_menu(
334 editor,
335 position,
336 point_for_position.previous_valid,
337 cx,
338 );
339 true
340 }
341
342 fn mouse_up(
343 editor: &mut Editor,
344 position: Vector2F,
345 cmd: bool,
346 shift: bool,
347 alt: bool,
348 position_map: &PositionMap,
349 text_bounds: RectF,
350 cx: &mut EventContext<Editor>,
351 ) -> bool {
352 let end_selection = editor.has_pending_selection();
353 let pending_nonempty_selections = editor.has_pending_nonempty_selection();
354
355 if end_selection {
356 editor.select(SelectPhase::End, cx);
357 }
358
359 if !pending_nonempty_selections && cmd && text_bounds.contains_point(position) {
360 if let Some(point) = position_map
361 .point_for_position(text_bounds, position)
362 .as_valid()
363 {
364 if shift {
365 go_to_fetched_type_definition(editor, point, alt, cx);
366 } else {
367 go_to_fetched_definition(editor, point, alt, cx);
368 }
369
370 return true;
371 }
372 }
373
374 end_selection
375 }
376
377 fn mouse_dragged(
378 editor: &mut Editor,
379 MouseMovedEvent {
380 modifiers: Modifiers { cmd, shift, .. },
381 position,
382 ..
383 }: MouseMovedEvent,
384 position_map: &PositionMap,
385 text_bounds: RectF,
386 cx: &mut EventContext<Editor>,
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 position_map
392 .point_for_position(text_bounds, position)
393 .as_valid()
394 } else {
395 None
396 };
397
398 update_go_to_definition_link(editor, point, cmd, shift, cx);
399
400 if editor.has_pending_selection() {
401 let mut scroll_delta = Vector2F::zero();
402
403 let vertical_margin = position_map.line_height.min(text_bounds.height() / 3.0);
404 let top = text_bounds.origin_y() + vertical_margin;
405 let bottom = text_bounds.lower_left().y() - vertical_margin;
406 if position.y() < top {
407 scroll_delta.set_y(-scale_vertical_mouse_autoscroll_delta(top - position.y()))
408 }
409 if position.y() > bottom {
410 scroll_delta.set_y(scale_vertical_mouse_autoscroll_delta(position.y() - bottom))
411 }
412
413 let horizontal_margin = position_map.line_height.min(text_bounds.width() / 3.0);
414 let left = text_bounds.origin_x() + horizontal_margin;
415 let right = text_bounds.upper_right().x() - horizontal_margin;
416 if position.x() < left {
417 scroll_delta.set_x(-scale_horizontal_mouse_autoscroll_delta(
418 left - position.x(),
419 ))
420 }
421 if position.x() > right {
422 scroll_delta.set_x(scale_horizontal_mouse_autoscroll_delta(
423 position.x() - right,
424 ))
425 }
426
427 let point_for_position = position_map.point_for_position(text_bounds, position);
428
429 editor.select(
430 SelectPhase::Update {
431 position: point_for_position.previous_valid,
432 goal_column: point_for_position.exact_unclipped.column(),
433 scroll_position: (position_map.snapshot.scroll_position() + scroll_delta)
434 .clamp(Vector2F::zero(), position_map.scroll_max),
435 },
436 cx,
437 );
438 hover_at(editor, point, cx);
439 true
440 } else {
441 hover_at(editor, point, cx);
442 false
443 }
444 }
445
446 fn mouse_moved(
447 editor: &mut Editor,
448 MouseMovedEvent {
449 modifiers: Modifiers { shift, cmd, .. },
450 position,
451 ..
452 }: MouseMovedEvent,
453 position_map: &PositionMap,
454 text_bounds: RectF,
455 cx: &mut ViewContext<Editor>,
456 ) -> bool {
457 // This will be handled more correctly once https://github.com/zed-industries/zed/issues/1218 is completed
458 // Don't trigger hover popover if mouse is hovering over context menu
459 if text_bounds.contains_point(position) {
460 let point_for_position = position_map.point_for_position(text_bounds, position);
461 if let Some(point) = point_for_position.as_valid() {
462 update_go_to_definition_link(editor, Some(point), cmd, shift, cx);
463 hover_at(editor, Some(point), cx);
464 return true;
465 } else {
466 let hint_start_offset = position_map
467 .snapshot
468 .display_point_to_inlay_offset(point_for_position.previous_valid, Bias::Left);
469 let hint_end_offset = position_map
470 .snapshot
471 .display_point_to_inlay_offset(point_for_position.next_valid, Bias::Right);
472 let offset_overshoot = point_for_position.column_overshoot_after_line_end as usize;
473 let hovered_offset = if offset_overshoot == 0 {
474 Some(position_map.snapshot.display_point_to_inlay_offset(
475 point_for_position.exact_unclipped,
476 Bias::Left,
477 ))
478 } else if (hint_end_offset - hint_start_offset).0 >= offset_overshoot {
479 Some(InlayOffset(hint_start_offset.0 + offset_overshoot))
480 } else {
481 None
482 };
483 if let Some(hovered_offset) = hovered_offset {
484 let buffer = editor.buffer().read(cx);
485 let snapshot = buffer.snapshot(cx);
486 let previous_valid_anchor = snapshot.anchor_at(
487 point_for_position
488 .previous_valid
489 .to_point(&position_map.snapshot.display_snapshot),
490 Bias::Left,
491 );
492 let next_valid_anchor = snapshot.anchor_at(
493 point_for_position
494 .next_valid
495 .to_point(&position_map.snapshot.display_snapshot),
496 Bias::Right,
497 );
498 if let Some(hovered_hint) = editor
499 .visible_inlay_hints(cx)
500 .into_iter()
501 .skip_while(|hint| {
502 hint.position.cmp(&previous_valid_anchor, &snapshot).is_lt()
503 })
504 .take_while(|hint| hint.position.cmp(&next_valid_anchor, &snapshot).is_le())
505 .max_by_key(|hint| hint.id)
506 {
507 if let Some(cached_hint) = editor
508 .inlay_hint_cache()
509 .hint_by_id(previous_valid_anchor.excerpt_id, hovered_hint.id)
510 {
511 match &cached_hint.label {
512 project::InlayHintLabel::String(regular_label) => {
513 // TODO kb remove + check for tooltip for hover and resolve, if needed
514 eprintln!("regular string: {regular_label}");
515 }
516 project::InlayHintLabel::LabelParts(label_parts) => {
517 if let Some(hovered_hint_part) = find_hovered_hint_part(
518 &label_parts,
519 hint_start_offset..hint_end_offset,
520 hovered_offset,
521 ) {
522 // TODO kb remove + check for tooltip and location and resolve, if needed
523 eprintln!("hint_part: {hovered_hint_part:?}");
524 }
525 }
526 };
527 }
528 }
529 }
530 }
531 };
532
533 update_go_to_definition_link(editor, None, cmd, shift, cx);
534 hover_at(editor, None, cx);
535 true
536 }
537
538 fn scroll(
539 editor: &mut Editor,
540 position: Vector2F,
541 mut delta: Vector2F,
542 precise: bool,
543 position_map: &PositionMap,
544 bounds: RectF,
545 cx: &mut ViewContext<Editor>,
546 ) -> bool {
547 if !bounds.contains_point(position) {
548 return false;
549 }
550
551 let line_height = position_map.line_height;
552 let max_glyph_width = position_map.em_width;
553
554 let axis = if precise {
555 //Trackpad
556 position_map.snapshot.ongoing_scroll.filter(&mut delta)
557 } else {
558 //Not trackpad
559 delta *= vec2f(max_glyph_width, line_height);
560 None //Resets ongoing scroll
561 };
562
563 let scroll_position = position_map.snapshot.scroll_position();
564 let x = (scroll_position.x() * max_glyph_width - delta.x()) / max_glyph_width;
565 let y = (scroll_position.y() * line_height - delta.y()) / line_height;
566 let scroll_position = vec2f(x, y).clamp(Vector2F::zero(), position_map.scroll_max);
567 editor.scroll(scroll_position, axis, cx);
568
569 true
570 }
571
572 fn paint_background(
573 &self,
574 scene: &mut SceneBuilder,
575 gutter_bounds: RectF,
576 text_bounds: RectF,
577 layout: &LayoutState,
578 ) {
579 let bounds = gutter_bounds.union_rect(text_bounds);
580 let scroll_top =
581 layout.position_map.snapshot.scroll_position().y() * layout.position_map.line_height;
582 scene.push_quad(Quad {
583 bounds: gutter_bounds,
584 background: Some(self.style.gutter_background),
585 border: Border::new(0., Color::transparent_black()),
586 corner_radii: Default::default(),
587 });
588 scene.push_quad(Quad {
589 bounds: text_bounds,
590 background: Some(self.style.background),
591 border: Border::new(0., Color::transparent_black()),
592 corner_radii: Default::default(),
593 });
594
595 if let EditorMode::Full = layout.mode {
596 let mut active_rows = layout.active_rows.iter().peekable();
597 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
598 let mut end_row = *start_row;
599 while active_rows.peek().map_or(false, |r| {
600 *r.0 == end_row + 1 && r.1 == contains_non_empty_selection
601 }) {
602 active_rows.next().unwrap();
603 end_row += 1;
604 }
605
606 if !contains_non_empty_selection {
607 let origin = vec2f(
608 bounds.origin_x(),
609 bounds.origin_y() + (layout.position_map.line_height * *start_row as f32)
610 - scroll_top,
611 );
612 let size = vec2f(
613 bounds.width(),
614 layout.position_map.line_height * (end_row - start_row + 1) as f32,
615 );
616 scene.push_quad(Quad {
617 bounds: RectF::new(origin, size),
618 background: Some(self.style.active_line_background),
619 border: Border::default(),
620 corner_radii: Default::default(),
621 });
622 }
623 }
624
625 if let Some(highlighted_rows) = &layout.highlighted_rows {
626 let origin = vec2f(
627 bounds.origin_x(),
628 bounds.origin_y()
629 + (layout.position_map.line_height * highlighted_rows.start as f32)
630 - scroll_top,
631 );
632 let size = vec2f(
633 bounds.width(),
634 layout.position_map.line_height * highlighted_rows.len() as f32,
635 );
636 scene.push_quad(Quad {
637 bounds: RectF::new(origin, size),
638 background: Some(self.style.highlighted_line_background),
639 border: Border::default(),
640 corner_radii: Default::default(),
641 });
642 }
643
644 let scroll_left =
645 layout.position_map.snapshot.scroll_position().x() * layout.position_map.em_width;
646
647 for (wrap_position, active) in layout.wrap_guides.iter() {
648 let x =
649 (text_bounds.origin_x() + wrap_position + layout.position_map.em_width / 2.)
650 - scroll_left;
651
652 if x < text_bounds.origin_x()
653 || (layout.show_scrollbars && x > self.scrollbar_left(&bounds))
654 {
655 continue;
656 }
657
658 let color = if *active {
659 self.style.active_wrap_guide
660 } else {
661 self.style.wrap_guide
662 };
663 scene.push_quad(Quad {
664 bounds: RectF::new(
665 vec2f(x, text_bounds.origin_y()),
666 vec2f(1., text_bounds.height()),
667 ),
668 background: Some(color),
669 border: Border::new(0., Color::transparent_black()),
670 corner_radii: Default::default(),
671 });
672 }
673 }
674 }
675
676 fn paint_gutter(
677 &mut self,
678 scene: &mut SceneBuilder,
679 bounds: RectF,
680 visible_bounds: RectF,
681 layout: &mut LayoutState,
682 editor: &mut Editor,
683 cx: &mut PaintContext<Editor>,
684 ) {
685 let line_height = layout.position_map.line_height;
686
687 let scroll_position = layout.position_map.snapshot.scroll_position();
688 let scroll_top = scroll_position.y() * line_height;
689
690 let show_gutter = matches!(
691 settings::get::<ProjectSettings>(cx).git.git_gutter,
692 Some(GitGutterSetting::TrackedFiles)
693 );
694
695 if show_gutter {
696 Self::paint_diff_hunks(scene, bounds, layout, cx);
697 }
698
699 for (ix, line) in layout.line_number_layouts.iter().enumerate() {
700 if let Some(line) = line {
701 let line_origin = bounds.origin()
702 + vec2f(
703 bounds.width() - line.width() - layout.gutter_padding,
704 ix as f32 * line_height - (scroll_top % line_height),
705 );
706
707 line.paint(scene, line_origin, visible_bounds, line_height, cx);
708 }
709 }
710
711 for (ix, fold_indicator) in layout.fold_indicators.iter_mut().enumerate() {
712 if let Some(indicator) = fold_indicator.as_mut() {
713 let position = vec2f(
714 bounds.width() - layout.gutter_padding,
715 ix as f32 * line_height - (scroll_top % line_height),
716 );
717 let centering_offset = vec2f(
718 (layout.gutter_padding + layout.gutter_margin - indicator.size().x()) / 2.,
719 (line_height - indicator.size().y()) / 2.,
720 );
721
722 let indicator_origin = bounds.origin() + position + centering_offset;
723
724 indicator.paint(scene, indicator_origin, visible_bounds, editor, cx);
725 }
726 }
727
728 if let Some((row, indicator)) = layout.code_actions_indicator.as_mut() {
729 let mut x = 0.;
730 let mut y = *row as f32 * line_height - scroll_top;
731 x += ((layout.gutter_padding + layout.gutter_margin) - indicator.size().x()) / 2.;
732 y += (line_height - indicator.size().y()) / 2.;
733 indicator.paint(
734 scene,
735 bounds.origin() + vec2f(x, y),
736 visible_bounds,
737 editor,
738 cx,
739 );
740 }
741 }
742
743 fn paint_diff_hunks(
744 scene: &mut SceneBuilder,
745 bounds: RectF,
746 layout: &mut LayoutState,
747 cx: &mut ViewContext<Editor>,
748 ) {
749 let diff_style = &theme::current(cx).editor.diff.clone();
750 let line_height = layout.position_map.line_height;
751
752 let scroll_position = layout.position_map.snapshot.scroll_position();
753 let scroll_top = scroll_position.y() * line_height;
754
755 for hunk in &layout.display_hunks {
756 let (display_row_range, status) = match hunk {
757 //TODO: This rendering is entirely a horrible hack
758 &DisplayDiffHunk::Folded { display_row: row } => {
759 let start_y = row as f32 * line_height - scroll_top;
760 let end_y = start_y + line_height;
761
762 let width = diff_style.removed_width_em * line_height;
763 let highlight_origin = bounds.origin() + vec2f(-width, start_y);
764 let highlight_size = vec2f(width * 2., end_y - start_y);
765 let highlight_bounds = RectF::new(highlight_origin, highlight_size);
766
767 scene.push_quad(Quad {
768 bounds: highlight_bounds,
769 background: Some(diff_style.modified),
770 border: Border::new(0., Color::transparent_black()),
771 corner_radii: (1. * line_height).into(),
772 });
773
774 continue;
775 }
776
777 DisplayDiffHunk::Unfolded {
778 display_row_range,
779 status,
780 } => (display_row_range, status),
781 };
782
783 let color = match status {
784 DiffHunkStatus::Added => diff_style.inserted,
785 DiffHunkStatus::Modified => diff_style.modified,
786
787 //TODO: This rendering is entirely a horrible hack
788 DiffHunkStatus::Removed => {
789 let row = display_row_range.start;
790
791 let offset = line_height / 2.;
792 let start_y = row as f32 * line_height - offset - scroll_top;
793 let end_y = start_y + line_height;
794
795 let width = diff_style.removed_width_em * line_height;
796 let highlight_origin = bounds.origin() + vec2f(-width, start_y);
797 let highlight_size = vec2f(width * 2., end_y - start_y);
798 let highlight_bounds = RectF::new(highlight_origin, highlight_size);
799
800 scene.push_quad(Quad {
801 bounds: highlight_bounds,
802 background: Some(diff_style.deleted),
803 border: Border::new(0., Color::transparent_black()),
804 corner_radii: (1. * line_height).into(),
805 });
806
807 continue;
808 }
809 };
810
811 let start_row = display_row_range.start;
812 let end_row = display_row_range.end;
813
814 let start_y = start_row as f32 * line_height - scroll_top;
815 let end_y = end_row as f32 * line_height - scroll_top;
816
817 let width = diff_style.width_em * line_height;
818 let highlight_origin = bounds.origin() + vec2f(-width, start_y);
819 let highlight_size = vec2f(width * 2., end_y - start_y);
820 let highlight_bounds = RectF::new(highlight_origin, highlight_size);
821
822 scene.push_quad(Quad {
823 bounds: highlight_bounds,
824 background: Some(color),
825 border: Border::new(0., Color::transparent_black()),
826 corner_radii: (diff_style.corner_radius * line_height).into(),
827 });
828 }
829 }
830
831 fn paint_text(
832 &mut self,
833 scene: &mut SceneBuilder,
834 bounds: RectF,
835 visible_bounds: RectF,
836 layout: &mut LayoutState,
837 editor: &mut Editor,
838 cx: &mut PaintContext<Editor>,
839 ) {
840 let style = &self.style;
841 let scroll_position = layout.position_map.snapshot.scroll_position();
842 let start_row = layout.visible_display_row_range.start;
843 let scroll_top = scroll_position.y() * layout.position_map.line_height;
844 let max_glyph_width = layout.position_map.em_width;
845 let scroll_left = scroll_position.x() * max_glyph_width;
846 let content_origin = bounds.origin() + vec2f(layout.gutter_margin, 0.);
847 let line_end_overshoot = 0.15 * layout.position_map.line_height;
848 let whitespace_setting = editor.buffer.read(cx).settings_at(0, cx).show_whitespaces;
849
850 scene.push_layer(Some(bounds));
851
852 scene.push_cursor_region(CursorRegion {
853 bounds,
854 style: if !editor.link_go_to_definition_state.definitions.is_empty() {
855 CursorStyle::PointingHand
856 } else {
857 CursorStyle::IBeam
858 },
859 });
860
861 let fold_corner_radius =
862 self.style.folds.ellipses.corner_radius_factor * layout.position_map.line_height;
863 for (id, range, color) in layout.fold_ranges.iter() {
864 self.paint_highlighted_range(
865 scene,
866 range.clone(),
867 *color,
868 fold_corner_radius,
869 fold_corner_radius * 2.,
870 layout,
871 content_origin,
872 scroll_top,
873 scroll_left,
874 bounds,
875 );
876
877 for bound in range_to_bounds(
878 &range,
879 content_origin,
880 scroll_left,
881 scroll_top,
882 &layout.visible_display_row_range,
883 line_end_overshoot,
884 &layout.position_map,
885 ) {
886 scene.push_cursor_region(CursorRegion {
887 bounds: bound,
888 style: CursorStyle::PointingHand,
889 });
890
891 let display_row = range.start.row();
892
893 let buffer_row = DisplayPoint::new(display_row, 0)
894 .to_point(&layout.position_map.snapshot.display_snapshot)
895 .row;
896
897 scene.push_mouse_region(
898 MouseRegion::new::<FoldMarkers>(cx.view_id(), *id as usize, bound)
899 .on_click(MouseButton::Left, move |_, editor: &mut Editor, cx| {
900 editor.unfold_at(&UnfoldAt { buffer_row }, cx)
901 })
902 .with_notify_on_hover(true)
903 .with_notify_on_click(true),
904 )
905 }
906 }
907
908 for (range, color) in &layout.highlighted_ranges {
909 self.paint_highlighted_range(
910 scene,
911 range.clone(),
912 *color,
913 0.,
914 line_end_overshoot,
915 layout,
916 content_origin,
917 scroll_top,
918 scroll_left,
919 bounds,
920 );
921 }
922
923 let mut cursors = SmallVec::<[Cursor; 32]>::new();
924 let corner_radius = 0.15 * layout.position_map.line_height;
925 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
926
927 for (replica_id, selections) in &layout.selections {
928 let replica_id = *replica_id;
929 let selection_style = if let Some(replica_id) = replica_id {
930 style.replica_selection_style(replica_id)
931 } else {
932 &style.absent_selection
933 };
934
935 for selection in selections {
936 self.paint_highlighted_range(
937 scene,
938 selection.range.clone(),
939 selection_style.selection,
940 corner_radius,
941 corner_radius * 2.,
942 layout,
943 content_origin,
944 scroll_top,
945 scroll_left,
946 bounds,
947 );
948
949 if selection.is_local && !selection.range.is_empty() {
950 invisible_display_ranges.push(selection.range.clone());
951 }
952 if !selection.is_local || editor.show_local_cursors(cx) {
953 let cursor_position = selection.head;
954 if layout
955 .visible_display_row_range
956 .contains(&cursor_position.row())
957 {
958 let cursor_row_layout = &layout.position_map.line_layouts
959 [(cursor_position.row() - start_row) as usize]
960 .line;
961 let cursor_column = cursor_position.column() as usize;
962
963 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
964 let mut block_width =
965 cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
966 if block_width == 0.0 {
967 block_width = layout.position_map.em_width;
968 }
969 let block_text = if let CursorShape::Block = selection.cursor_shape {
970 layout
971 .position_map
972 .snapshot
973 .chars_at(cursor_position)
974 .next()
975 .and_then(|(character, _)| {
976 let font_id =
977 cursor_row_layout.font_for_index(cursor_column)?;
978 let text = character.to_string();
979
980 Some(cx.text_layout_cache().layout_str(
981 &text,
982 cursor_row_layout.font_size(),
983 &[(
984 text.chars().count(),
985 RunStyle {
986 font_id,
987 color: style.background,
988 underline: Default::default(),
989 },
990 )],
991 ))
992 })
993 } else {
994 None
995 };
996
997 let x = cursor_character_x - scroll_left;
998 let y = cursor_position.row() as f32 * layout.position_map.line_height
999 - scroll_top;
1000 if selection.is_newest {
1001 editor.pixel_position_of_newest_cursor = Some(vec2f(
1002 bounds.origin_x() + x + block_width / 2.,
1003 bounds.origin_y() + y + layout.position_map.line_height / 2.,
1004 ));
1005 }
1006 cursors.push(Cursor {
1007 color: selection_style.cursor,
1008 block_width,
1009 origin: vec2f(x, y),
1010 line_height: layout.position_map.line_height,
1011 shape: selection.cursor_shape,
1012 block_text,
1013 });
1014 }
1015 }
1016 }
1017 }
1018
1019 if let Some(visible_text_bounds) = bounds.intersection(visible_bounds) {
1020 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
1021 let row = start_row + ix as u32;
1022 line_with_invisibles.draw(
1023 layout,
1024 row,
1025 scroll_top,
1026 scene,
1027 content_origin,
1028 scroll_left,
1029 visible_text_bounds,
1030 whitespace_setting,
1031 &invisible_display_ranges,
1032 visible_bounds,
1033 cx,
1034 )
1035 }
1036 }
1037
1038 scene.paint_layer(Some(bounds), |scene| {
1039 for cursor in cursors {
1040 cursor.paint(scene, content_origin, cx);
1041 }
1042 });
1043
1044 if let Some((position, context_menu)) = layout.context_menu.as_mut() {
1045 scene.push_stacking_context(None, None);
1046 let cursor_row_layout =
1047 &layout.position_map.line_layouts[(position.row() - start_row) as usize].line;
1048 let x = cursor_row_layout.x_for_index(position.column() as usize) - scroll_left;
1049 let y = (position.row() + 1) as f32 * layout.position_map.line_height - scroll_top;
1050 let mut list_origin = content_origin + vec2f(x, y);
1051 let list_width = context_menu.size().x();
1052 let list_height = context_menu.size().y();
1053
1054 // Snap the right edge of the list to the right edge of the window if
1055 // its horizontal bounds overflow.
1056 if list_origin.x() + list_width > cx.window_size().x() {
1057 list_origin.set_x((cx.window_size().x() - list_width).max(0.));
1058 }
1059
1060 if list_origin.y() + list_height > bounds.max_y() {
1061 list_origin.set_y(list_origin.y() - layout.position_map.line_height - list_height);
1062 }
1063
1064 context_menu.paint(
1065 scene,
1066 list_origin,
1067 RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
1068 editor,
1069 cx,
1070 );
1071
1072 scene.pop_stacking_context();
1073 }
1074
1075 if let Some((position, hover_popovers)) = layout.hover_popovers.as_mut() {
1076 scene.push_stacking_context(None, None);
1077
1078 // This is safe because we check on layout whether the required row is available
1079 let hovered_row_layout =
1080 &layout.position_map.line_layouts[(position.row() - start_row) as usize].line;
1081
1082 // Minimum required size: Take the first popover, and add 1.5 times the minimum popover
1083 // height. This is the size we will use to decide whether to render popovers above or below
1084 // the hovered line.
1085 let first_size = hover_popovers[0].size();
1086 let height_to_reserve = first_size.y()
1087 + 1.5 * MIN_POPOVER_LINE_HEIGHT as f32 * layout.position_map.line_height;
1088
1089 // Compute Hovered Point
1090 let x = hovered_row_layout.x_for_index(position.column() as usize) - scroll_left;
1091 let y = position.row() as f32 * layout.position_map.line_height - scroll_top;
1092 let hovered_point = content_origin + vec2f(x, y);
1093
1094 if hovered_point.y() - height_to_reserve > 0.0 {
1095 // There is enough space above. Render popovers above the hovered point
1096 let mut current_y = hovered_point.y();
1097 for hover_popover in hover_popovers {
1098 let size = hover_popover.size();
1099 let mut popover_origin = vec2f(hovered_point.x(), current_y - size.y());
1100
1101 let x_out_of_bounds = bounds.max_x() - (popover_origin.x() + size.x());
1102 if x_out_of_bounds < 0.0 {
1103 popover_origin.set_x(popover_origin.x() + x_out_of_bounds);
1104 }
1105
1106 hover_popover.paint(
1107 scene,
1108 popover_origin,
1109 RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
1110 editor,
1111 cx,
1112 );
1113
1114 current_y = popover_origin.y() - HOVER_POPOVER_GAP;
1115 }
1116 } else {
1117 // There is not enough space above. Render popovers below the hovered point
1118 let mut current_y = hovered_point.y() + layout.position_map.line_height;
1119 for hover_popover in hover_popovers {
1120 let size = hover_popover.size();
1121 let mut popover_origin = vec2f(hovered_point.x(), current_y);
1122
1123 let x_out_of_bounds = bounds.max_x() - (popover_origin.x() + size.x());
1124 if x_out_of_bounds < 0.0 {
1125 popover_origin.set_x(popover_origin.x() + x_out_of_bounds);
1126 }
1127
1128 hover_popover.paint(
1129 scene,
1130 popover_origin,
1131 RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
1132 editor,
1133 cx,
1134 );
1135
1136 current_y = popover_origin.y() + size.y() + HOVER_POPOVER_GAP;
1137 }
1138 }
1139
1140 scene.pop_stacking_context();
1141 }
1142
1143 scene.pop_layer();
1144 }
1145
1146 fn scrollbar_left(&self, bounds: &RectF) -> f32 {
1147 bounds.max_x() - self.style.theme.scrollbar.width
1148 }
1149
1150 fn paint_scrollbar(
1151 &mut self,
1152 scene: &mut SceneBuilder,
1153 bounds: RectF,
1154 layout: &mut LayoutState,
1155 cx: &mut ViewContext<Editor>,
1156 editor: &Editor,
1157 ) {
1158 enum ScrollbarMouseHandlers {}
1159 if layout.mode != EditorMode::Full {
1160 return;
1161 }
1162
1163 let style = &self.style.theme.scrollbar;
1164
1165 let top = bounds.min_y();
1166 let bottom = bounds.max_y();
1167 let right = bounds.max_x();
1168 let left = self.scrollbar_left(&bounds);
1169 let row_range = &layout.scrollbar_row_range;
1170 let max_row = layout.max_row as f32 + (row_range.end - row_range.start);
1171
1172 let mut height = bounds.height();
1173 let mut first_row_y_offset = 0.0;
1174
1175 // Impose a minimum height on the scrollbar thumb
1176 let row_height = height / max_row;
1177 let min_thumb_height =
1178 style.min_height_factor * cx.font_cache.line_height(self.style.text.font_size);
1179 let thumb_height = (row_range.end - row_range.start) * row_height;
1180 if thumb_height < min_thumb_height {
1181 first_row_y_offset = (min_thumb_height - thumb_height) / 2.0;
1182 height -= min_thumb_height - thumb_height;
1183 }
1184
1185 let y_for_row = |row: f32| -> f32 { top + first_row_y_offset + row * row_height };
1186
1187 let thumb_top = y_for_row(row_range.start) - first_row_y_offset;
1188 let thumb_bottom = y_for_row(row_range.end) + first_row_y_offset;
1189 let track_bounds = RectF::from_points(vec2f(left, top), vec2f(right, bottom));
1190 let thumb_bounds = RectF::from_points(vec2f(left, thumb_top), vec2f(right, thumb_bottom));
1191
1192 if layout.show_scrollbars {
1193 scene.push_quad(Quad {
1194 bounds: track_bounds,
1195 border: style.track.border,
1196 background: style.track.background_color,
1197 ..Default::default()
1198 });
1199 let scrollbar_settings = settings::get::<EditorSettings>(cx).scrollbar;
1200 let theme = theme::current(cx);
1201 let scrollbar_theme = &theme.editor.scrollbar;
1202 if layout.is_singleton && scrollbar_settings.selections {
1203 let start_anchor = Anchor::min();
1204 let end_anchor = Anchor::max();
1205 let color = scrollbar_theme.selections;
1206 let border = Border {
1207 width: 1.,
1208 color: style.thumb.border.color,
1209 overlay: false,
1210 top: false,
1211 right: true,
1212 bottom: false,
1213 left: true,
1214 };
1215 let mut push_region = |start: DisplayPoint, end: DisplayPoint| {
1216 let start_y = y_for_row(start.row() as f32);
1217 let mut end_y = y_for_row(end.row() as f32);
1218 if end_y - start_y < 1. {
1219 end_y = start_y + 1.;
1220 }
1221 let bounds = RectF::from_points(vec2f(left, start_y), vec2f(right, end_y));
1222
1223 scene.push_quad(Quad {
1224 bounds,
1225 background: Some(color),
1226 border,
1227 corner_radii: style.thumb.corner_radii.into(),
1228 })
1229 };
1230 let background_ranges = editor
1231 .background_highlight_row_ranges::<crate::items::BufferSearchHighlights>(
1232 start_anchor..end_anchor,
1233 &layout.position_map.snapshot,
1234 50000,
1235 );
1236 for row in background_ranges {
1237 let start = row.start();
1238 let end = row.end();
1239 push_region(*start, *end);
1240 }
1241 }
1242
1243 if layout.is_singleton && scrollbar_settings.git_diff {
1244 let diff_style = scrollbar_theme.git.clone();
1245 for hunk in layout
1246 .position_map
1247 .snapshot
1248 .buffer_snapshot
1249 .git_diff_hunks_in_range(0..(max_row.floor() as u32))
1250 {
1251 let start_display = Point::new(hunk.buffer_range.start, 0)
1252 .to_display_point(&layout.position_map.snapshot.display_snapshot);
1253 let end_display = Point::new(hunk.buffer_range.end, 0)
1254 .to_display_point(&layout.position_map.snapshot.display_snapshot);
1255 let start_y = y_for_row(start_display.row() as f32);
1256 let mut end_y = if hunk.buffer_range.start == hunk.buffer_range.end {
1257 y_for_row((end_display.row() + 1) as f32)
1258 } else {
1259 y_for_row((end_display.row()) as f32)
1260 };
1261
1262 if end_y - start_y < 1. {
1263 end_y = start_y + 1.;
1264 }
1265 let bounds = RectF::from_points(vec2f(left, start_y), vec2f(right, end_y));
1266
1267 let color = match hunk.status() {
1268 DiffHunkStatus::Added => diff_style.inserted,
1269 DiffHunkStatus::Modified => diff_style.modified,
1270 DiffHunkStatus::Removed => diff_style.deleted,
1271 };
1272
1273 let border = Border {
1274 width: 1.,
1275 color: style.thumb.border.color,
1276 overlay: false,
1277 top: false,
1278 right: true,
1279 bottom: false,
1280 left: true,
1281 };
1282
1283 scene.push_quad(Quad {
1284 bounds,
1285 background: Some(color),
1286 border,
1287 corner_radii: style.thumb.corner_radii.into(),
1288 })
1289 }
1290 }
1291
1292 scene.push_quad(Quad {
1293 bounds: thumb_bounds,
1294 border: style.thumb.border,
1295 background: style.thumb.background_color,
1296 corner_radii: style.thumb.corner_radii.into(),
1297 });
1298 }
1299
1300 scene.push_cursor_region(CursorRegion {
1301 bounds: track_bounds,
1302 style: CursorStyle::Arrow,
1303 });
1304 scene.push_mouse_region(
1305 MouseRegion::new::<ScrollbarMouseHandlers>(cx.view_id(), cx.view_id(), track_bounds)
1306 .on_move(move |event, editor: &mut Editor, cx| {
1307 if event.pressed_button.is_none() {
1308 editor.scroll_manager.show_scrollbar(cx);
1309 }
1310 })
1311 .on_down(MouseButton::Left, {
1312 let row_range = row_range.clone();
1313 move |event, editor: &mut Editor, cx| {
1314 let y = event.position.y();
1315 if y < thumb_top || thumb_bottom < y {
1316 let center_row = ((y - top) * max_row as f32 / height).round() as u32;
1317 let top_row = center_row
1318 .saturating_sub((row_range.end - row_range.start) as u32 / 2);
1319 let mut position = editor.scroll_position(cx);
1320 position.set_y(top_row as f32);
1321 editor.set_scroll_position(position, cx);
1322 } else {
1323 editor.scroll_manager.show_scrollbar(cx);
1324 }
1325 }
1326 })
1327 .on_drag(MouseButton::Left, {
1328 move |event, editor: &mut Editor, cx| {
1329 if event.end {
1330 return;
1331 }
1332
1333 let y = event.prev_mouse_position.y();
1334 let new_y = event.position.y();
1335 if thumb_top < y && y < thumb_bottom {
1336 let mut position = editor.scroll_position(cx);
1337 position.set_y(position.y() + (new_y - y) * (max_row as f32) / height);
1338 if position.y() < 0.0 {
1339 position.set_y(0.);
1340 }
1341 editor.set_scroll_position(position, cx);
1342 }
1343 }
1344 }),
1345 );
1346 }
1347
1348 #[allow(clippy::too_many_arguments)]
1349 fn paint_highlighted_range(
1350 &self,
1351 scene: &mut SceneBuilder,
1352 range: Range<DisplayPoint>,
1353 color: Color,
1354 corner_radius: f32,
1355 line_end_overshoot: f32,
1356 layout: &LayoutState,
1357 content_origin: Vector2F,
1358 scroll_top: f32,
1359 scroll_left: f32,
1360 bounds: RectF,
1361 ) {
1362 let start_row = layout.visible_display_row_range.start;
1363 let end_row = layout.visible_display_row_range.end;
1364 if range.start != range.end {
1365 let row_range = if range.end.column() == 0 {
1366 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
1367 } else {
1368 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
1369 };
1370
1371 let highlighted_range = HighlightedRange {
1372 color,
1373 line_height: layout.position_map.line_height,
1374 corner_radius,
1375 start_y: content_origin.y()
1376 + row_range.start as f32 * layout.position_map.line_height
1377 - scroll_top,
1378 lines: row_range
1379 .into_iter()
1380 .map(|row| {
1381 let line_layout =
1382 &layout.position_map.line_layouts[(row - start_row) as usize].line;
1383 HighlightedRangeLine {
1384 start_x: if row == range.start.row() {
1385 content_origin.x()
1386 + line_layout.x_for_index(range.start.column() as usize)
1387 - scroll_left
1388 } else {
1389 content_origin.x() - scroll_left
1390 },
1391 end_x: if row == range.end.row() {
1392 content_origin.x()
1393 + line_layout.x_for_index(range.end.column() as usize)
1394 - scroll_left
1395 } else {
1396 content_origin.x() + line_layout.width() + line_end_overshoot
1397 - scroll_left
1398 },
1399 }
1400 })
1401 .collect(),
1402 };
1403
1404 highlighted_range.paint(bounds, scene);
1405 }
1406 }
1407
1408 fn paint_blocks(
1409 &mut self,
1410 scene: &mut SceneBuilder,
1411 bounds: RectF,
1412 visible_bounds: RectF,
1413 layout: &mut LayoutState,
1414 editor: &mut Editor,
1415 cx: &mut PaintContext<Editor>,
1416 ) {
1417 let scroll_position = layout.position_map.snapshot.scroll_position();
1418 let scroll_left = scroll_position.x() * layout.position_map.em_width;
1419 let scroll_top = scroll_position.y() * layout.position_map.line_height;
1420
1421 for block in &mut layout.blocks {
1422 let mut origin = bounds.origin()
1423 + vec2f(
1424 0.,
1425 block.row as f32 * layout.position_map.line_height - scroll_top,
1426 );
1427 if !matches!(block.style, BlockStyle::Sticky) {
1428 origin += vec2f(-scroll_left, 0.);
1429 }
1430 block
1431 .element
1432 .paint(scene, origin, visible_bounds, editor, cx);
1433 }
1434 }
1435
1436 fn column_pixels(&self, column: usize, cx: &ViewContext<Editor>) -> f32 {
1437 let style = &self.style;
1438
1439 cx.text_layout_cache()
1440 .layout_str(
1441 " ".repeat(column).as_str(),
1442 style.text.font_size,
1443 &[(
1444 column,
1445 RunStyle {
1446 font_id: style.text.font_id,
1447 color: Color::black(),
1448 underline: Default::default(),
1449 },
1450 )],
1451 )
1452 .width()
1453 }
1454
1455 fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &ViewContext<Editor>) -> f32 {
1456 let digit_count = (snapshot.max_buffer_row() as f32 + 1.).log10().floor() as usize + 1;
1457 self.column_pixels(digit_count, cx)
1458 }
1459
1460 //Folds contained in a hunk are ignored apart from shrinking visual size
1461 //If a fold contains any hunks then that fold line is marked as modified
1462 fn layout_git_gutters(
1463 &self,
1464 display_rows: Range<u32>,
1465 snapshot: &EditorSnapshot,
1466 ) -> Vec<DisplayDiffHunk> {
1467 let buffer_snapshot = &snapshot.buffer_snapshot;
1468
1469 let buffer_start_row = DisplayPoint::new(display_rows.start, 0)
1470 .to_point(snapshot)
1471 .row;
1472 let buffer_end_row = DisplayPoint::new(display_rows.end, 0)
1473 .to_point(snapshot)
1474 .row;
1475
1476 buffer_snapshot
1477 .git_diff_hunks_in_range(buffer_start_row..buffer_end_row)
1478 .map(|hunk| diff_hunk_to_display(hunk, snapshot))
1479 .dedup()
1480 .collect()
1481 }
1482
1483 fn layout_line_numbers(
1484 &self,
1485 rows: Range<u32>,
1486 active_rows: &BTreeMap<u32, bool>,
1487 is_singleton: bool,
1488 snapshot: &EditorSnapshot,
1489 cx: &ViewContext<Editor>,
1490 ) -> (
1491 Vec<Option<text_layout::Line>>,
1492 Vec<Option<(FoldStatus, BufferRow, bool)>>,
1493 ) {
1494 let style = &self.style;
1495 let include_line_numbers = snapshot.mode == EditorMode::Full;
1496 let mut line_number_layouts = Vec::with_capacity(rows.len());
1497 let mut fold_statuses = Vec::with_capacity(rows.len());
1498 let mut line_number = String::new();
1499 for (ix, row) in snapshot
1500 .buffer_rows(rows.start)
1501 .take((rows.end - rows.start) as usize)
1502 .enumerate()
1503 {
1504 let display_row = rows.start + ix as u32;
1505 let (active, color) = if active_rows.contains_key(&display_row) {
1506 (true, style.line_number_active)
1507 } else {
1508 (false, style.line_number)
1509 };
1510 if let Some(buffer_row) = row {
1511 if include_line_numbers {
1512 line_number.clear();
1513 write!(&mut line_number, "{}", buffer_row + 1).unwrap();
1514 line_number_layouts.push(Some(cx.text_layout_cache().layout_str(
1515 &line_number,
1516 style.text.font_size,
1517 &[(
1518 line_number.len(),
1519 RunStyle {
1520 font_id: style.text.font_id,
1521 color,
1522 underline: Default::default(),
1523 },
1524 )],
1525 )));
1526 fold_statuses.push(
1527 is_singleton
1528 .then(|| {
1529 snapshot
1530 .fold_for_line(buffer_row)
1531 .map(|fold_status| (fold_status, buffer_row, active))
1532 })
1533 .flatten(),
1534 )
1535 }
1536 } else {
1537 fold_statuses.push(None);
1538 line_number_layouts.push(None);
1539 }
1540 }
1541
1542 (line_number_layouts, fold_statuses)
1543 }
1544
1545 fn layout_lines(
1546 &mut self,
1547 rows: Range<u32>,
1548 line_number_layouts: &[Option<Line>],
1549 snapshot: &EditorSnapshot,
1550 cx: &ViewContext<Editor>,
1551 ) -> Vec<LineWithInvisibles> {
1552 if rows.start >= rows.end {
1553 return Vec::new();
1554 }
1555
1556 // When the editor is empty and unfocused, then show the placeholder.
1557 if snapshot.is_empty() {
1558 let placeholder_style = self
1559 .style
1560 .placeholder_text
1561 .as_ref()
1562 .unwrap_or(&self.style.text);
1563 let placeholder_text = snapshot.placeholder_text();
1564 let placeholder_lines = placeholder_text
1565 .as_ref()
1566 .map_or("", AsRef::as_ref)
1567 .split('\n')
1568 .skip(rows.start as usize)
1569 .chain(iter::repeat(""))
1570 .take(rows.len());
1571 placeholder_lines
1572 .map(|line| {
1573 cx.text_layout_cache().layout_str(
1574 line,
1575 placeholder_style.font_size,
1576 &[(
1577 line.len(),
1578 RunStyle {
1579 font_id: placeholder_style.font_id,
1580 color: placeholder_style.color,
1581 underline: Default::default(),
1582 },
1583 )],
1584 )
1585 })
1586 .map(|line| LineWithInvisibles {
1587 line,
1588 invisibles: Vec::new(),
1589 })
1590 .collect()
1591 } else {
1592 let style = &self.style;
1593 let chunks = snapshot
1594 .chunks(
1595 rows.clone(),
1596 true,
1597 Some(style.theme.hint),
1598 Some(style.theme.suggestion),
1599 )
1600 .map(|chunk| {
1601 let mut highlight_style = chunk
1602 .syntax_highlight_id
1603 .and_then(|id| id.style(&style.syntax));
1604
1605 if let Some(chunk_highlight) = chunk.highlight_style {
1606 if let Some(highlight_style) = highlight_style.as_mut() {
1607 highlight_style.highlight(chunk_highlight);
1608 } else {
1609 highlight_style = Some(chunk_highlight);
1610 }
1611 }
1612
1613 let mut diagnostic_highlight = HighlightStyle::default();
1614
1615 if chunk.is_unnecessary {
1616 diagnostic_highlight.fade_out = Some(style.unnecessary_code_fade);
1617 }
1618
1619 if let Some(severity) = chunk.diagnostic_severity {
1620 // Omit underlines for HINT/INFO diagnostics on 'unnecessary' code.
1621 if severity <= DiagnosticSeverity::WARNING || !chunk.is_unnecessary {
1622 let diagnostic_style = super::diagnostic_style(severity, true, style);
1623 diagnostic_highlight.underline = Some(Underline {
1624 color: Some(diagnostic_style.message.text.color),
1625 thickness: 1.0.into(),
1626 squiggly: true,
1627 });
1628 }
1629 }
1630
1631 if let Some(highlight_style) = highlight_style.as_mut() {
1632 highlight_style.highlight(diagnostic_highlight);
1633 } else {
1634 highlight_style = Some(diagnostic_highlight);
1635 }
1636
1637 HighlightedChunk {
1638 chunk: chunk.text,
1639 style: highlight_style,
1640 is_tab: chunk.is_tab,
1641 }
1642 });
1643
1644 LineWithInvisibles::from_chunks(
1645 chunks,
1646 &style.text,
1647 cx.text_layout_cache(),
1648 cx.font_cache(),
1649 MAX_LINE_LEN,
1650 rows.len() as usize,
1651 line_number_layouts,
1652 snapshot.mode,
1653 )
1654 }
1655 }
1656
1657 #[allow(clippy::too_many_arguments)]
1658 fn layout_blocks(
1659 &mut self,
1660 rows: Range<u32>,
1661 snapshot: &EditorSnapshot,
1662 editor_width: f32,
1663 scroll_width: f32,
1664 gutter_padding: f32,
1665 gutter_width: f32,
1666 em_width: f32,
1667 text_x: f32,
1668 line_height: f32,
1669 style: &EditorStyle,
1670 line_layouts: &[LineWithInvisibles],
1671 editor: &mut Editor,
1672 cx: &mut LayoutContext<Editor>,
1673 ) -> (f32, Vec<BlockLayout>) {
1674 let mut block_id = 0;
1675 let scroll_x = snapshot.scroll_anchor.offset.x();
1676 let (fixed_blocks, non_fixed_blocks) = snapshot
1677 .blocks_in_range(rows.clone())
1678 .partition::<Vec<_>, _>(|(_, block)| match block {
1679 TransformBlock::ExcerptHeader { .. } => false,
1680 TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
1681 });
1682 let mut render_block = |block: &TransformBlock, width: f32, block_id: usize| {
1683 let mut element = match block {
1684 TransformBlock::Custom(block) => {
1685 let align_to = block
1686 .position()
1687 .to_point(&snapshot.buffer_snapshot)
1688 .to_display_point(snapshot);
1689 let anchor_x = text_x
1690 + if rows.contains(&align_to.row()) {
1691 line_layouts[(align_to.row() - rows.start) as usize]
1692 .line
1693 .x_for_index(align_to.column() as usize)
1694 } else {
1695 layout_line(align_to.row(), snapshot, style, cx.text_layout_cache())
1696 .x_for_index(align_to.column() as usize)
1697 };
1698
1699 block.render(&mut BlockContext {
1700 view_context: cx,
1701 anchor_x,
1702 gutter_padding,
1703 line_height,
1704 scroll_x,
1705 gutter_width,
1706 em_width,
1707 block_id,
1708 })
1709 }
1710 TransformBlock::ExcerptHeader {
1711 id,
1712 buffer,
1713 range,
1714 starts_new_buffer,
1715 ..
1716 } => {
1717 let tooltip_style = theme::current(cx).tooltip.clone();
1718 let include_root = editor
1719 .project
1720 .as_ref()
1721 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
1722 .unwrap_or_default();
1723 let jump_icon = project::File::from_dyn(buffer.file()).map(|file| {
1724 let jump_path = ProjectPath {
1725 worktree_id: file.worktree_id(cx),
1726 path: file.path.clone(),
1727 };
1728 let jump_anchor = range
1729 .primary
1730 .as_ref()
1731 .map_or(range.context.start, |primary| primary.start);
1732 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
1733
1734 enum JumpIcon {}
1735 MouseEventHandler::new::<JumpIcon, _>((*id).into(), cx, |state, _| {
1736 let style = style.jump_icon.style_for(state);
1737 Svg::new("icons/arrow_up_right_8.svg")
1738 .with_color(style.color)
1739 .constrained()
1740 .with_width(style.icon_width)
1741 .aligned()
1742 .contained()
1743 .with_style(style.container)
1744 .constrained()
1745 .with_width(style.button_width)
1746 .with_height(style.button_width)
1747 })
1748 .with_cursor_style(CursorStyle::PointingHand)
1749 .on_click(MouseButton::Left, move |_, editor, cx| {
1750 if let Some(workspace) = editor
1751 .workspace
1752 .as_ref()
1753 .and_then(|(workspace, _)| workspace.upgrade(cx))
1754 {
1755 workspace.update(cx, |workspace, cx| {
1756 Editor::jump(
1757 workspace,
1758 jump_path.clone(),
1759 jump_position,
1760 jump_anchor,
1761 cx,
1762 );
1763 });
1764 }
1765 })
1766 .with_tooltip::<JumpIcon>(
1767 (*id).into(),
1768 "Jump to Buffer".to_string(),
1769 Some(Box::new(crate::OpenExcerpts)),
1770 tooltip_style.clone(),
1771 cx,
1772 )
1773 .aligned()
1774 .flex_float()
1775 });
1776
1777 if *starts_new_buffer {
1778 let editor_font_size = style.text.font_size;
1779 let style = &style.diagnostic_path_header;
1780 let font_size = (style.text_scale_factor * editor_font_size).round();
1781
1782 let path = buffer.resolve_file_path(cx, include_root);
1783 let mut filename = None;
1784 let mut parent_path = None;
1785 // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
1786 if let Some(path) = path {
1787 filename = path.file_name().map(|f| f.to_string_lossy().to_string());
1788 parent_path =
1789 path.parent().map(|p| p.to_string_lossy().to_string() + "/");
1790 }
1791
1792 Flex::row()
1793 .with_child(
1794 Label::new(
1795 filename.unwrap_or_else(|| "untitled".to_string()),
1796 style.filename.text.clone().with_font_size(font_size),
1797 )
1798 .contained()
1799 .with_style(style.filename.container)
1800 .aligned(),
1801 )
1802 .with_children(parent_path.map(|path| {
1803 Label::new(path, style.path.text.clone().with_font_size(font_size))
1804 .contained()
1805 .with_style(style.path.container)
1806 .aligned()
1807 }))
1808 .with_children(jump_icon)
1809 .contained()
1810 .with_style(style.container)
1811 .with_padding_left(gutter_padding)
1812 .with_padding_right(gutter_padding)
1813 .expanded()
1814 .into_any_named("path header block")
1815 } else {
1816 let text_style = style.text.clone();
1817 Flex::row()
1818 .with_child(Label::new("⋯", text_style))
1819 .with_children(jump_icon)
1820 .contained()
1821 .with_padding_left(gutter_padding)
1822 .with_padding_right(gutter_padding)
1823 .expanded()
1824 .into_any_named("collapsed context")
1825 }
1826 }
1827 };
1828
1829 element.layout(
1830 SizeConstraint {
1831 min: Vector2F::zero(),
1832 max: vec2f(width, block.height() as f32 * line_height),
1833 },
1834 editor,
1835 cx,
1836 );
1837 element
1838 };
1839
1840 let mut fixed_block_max_width = 0f32;
1841 let mut blocks = Vec::new();
1842 for (row, block) in fixed_blocks {
1843 let element = render_block(block, f32::INFINITY, block_id);
1844 block_id += 1;
1845 fixed_block_max_width = fixed_block_max_width.max(element.size().x() + em_width);
1846 blocks.push(BlockLayout {
1847 row,
1848 element,
1849 style: BlockStyle::Fixed,
1850 });
1851 }
1852 for (row, block) in non_fixed_blocks {
1853 let style = match block {
1854 TransformBlock::Custom(block) => block.style(),
1855 TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
1856 };
1857 let width = match style {
1858 BlockStyle::Sticky => editor_width,
1859 BlockStyle::Flex => editor_width
1860 .max(fixed_block_max_width)
1861 .max(gutter_width + scroll_width),
1862 BlockStyle::Fixed => unreachable!(),
1863 };
1864 let element = render_block(block, width, block_id);
1865 block_id += 1;
1866 blocks.push(BlockLayout {
1867 row,
1868 element,
1869 style,
1870 });
1871 }
1872 (
1873 scroll_width.max(fixed_block_max_width - gutter_width),
1874 blocks,
1875 )
1876 }
1877}
1878
1879fn find_hovered_hint_part<'a>(
1880 label_parts: &'a [InlayHintLabelPart],
1881 hint_range: Range<InlayOffset>,
1882 hovered_offset: InlayOffset,
1883) -> Option<&'a InlayHintLabelPart> {
1884 if hovered_offset >= hint_range.start && hovered_offset <= hint_range.end {
1885 let mut hovered_character = (hovered_offset - hint_range.start).0;
1886 for part in label_parts {
1887 let part_len = part.value.chars().count();
1888 if hovered_character >= part_len {
1889 hovered_character -= part_len;
1890 } else {
1891 return Some(part);
1892 }
1893 }
1894 }
1895 None
1896}
1897
1898struct HighlightedChunk<'a> {
1899 chunk: &'a str,
1900 style: Option<HighlightStyle>,
1901 is_tab: bool,
1902}
1903
1904#[derive(Debug)]
1905pub struct LineWithInvisibles {
1906 pub line: Line,
1907 invisibles: Vec<Invisible>,
1908}
1909
1910impl LineWithInvisibles {
1911 fn from_chunks<'a>(
1912 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
1913 text_style: &TextStyle,
1914 text_layout_cache: &TextLayoutCache,
1915 font_cache: &Arc<FontCache>,
1916 max_line_len: usize,
1917 max_line_count: usize,
1918 line_number_layouts: &[Option<Line>],
1919 editor_mode: EditorMode,
1920 ) -> Vec<Self> {
1921 let mut layouts = Vec::with_capacity(max_line_count);
1922 let mut line = String::new();
1923 let mut invisibles = Vec::new();
1924 let mut styles = Vec::new();
1925 let mut non_whitespace_added = false;
1926 let mut row = 0;
1927 let mut line_exceeded_max_len = false;
1928 for highlighted_chunk in chunks.chain([HighlightedChunk {
1929 chunk: "\n",
1930 style: None,
1931 is_tab: false,
1932 }]) {
1933 for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
1934 if ix > 0 {
1935 layouts.push(Self {
1936 line: text_layout_cache.layout_str(&line, text_style.font_size, &styles),
1937 invisibles: invisibles.drain(..).collect(),
1938 });
1939
1940 line.clear();
1941 styles.clear();
1942 row += 1;
1943 line_exceeded_max_len = false;
1944 non_whitespace_added = false;
1945 if row == max_line_count {
1946 return layouts;
1947 }
1948 }
1949
1950 if !line_chunk.is_empty() && !line_exceeded_max_len {
1951 let text_style = if let Some(style) = highlighted_chunk.style {
1952 text_style
1953 .clone()
1954 .highlight(style, font_cache)
1955 .map(Cow::Owned)
1956 .unwrap_or_else(|_| Cow::Borrowed(text_style))
1957 } else {
1958 Cow::Borrowed(text_style)
1959 };
1960
1961 if line.len() + line_chunk.len() > max_line_len {
1962 let mut chunk_len = max_line_len - line.len();
1963 while !line_chunk.is_char_boundary(chunk_len) {
1964 chunk_len -= 1;
1965 }
1966 line_chunk = &line_chunk[..chunk_len];
1967 line_exceeded_max_len = true;
1968 }
1969
1970 styles.push((
1971 line_chunk.len(),
1972 RunStyle {
1973 font_id: text_style.font_id,
1974 color: text_style.color,
1975 underline: text_style.underline,
1976 },
1977 ));
1978
1979 if editor_mode == EditorMode::Full {
1980 // Line wrap pads its contents with fake whitespaces,
1981 // avoid printing them
1982 let inside_wrapped_string = line_number_layouts
1983 .get(row)
1984 .and_then(|layout| layout.as_ref())
1985 .is_none();
1986 if highlighted_chunk.is_tab {
1987 if non_whitespace_added || !inside_wrapped_string {
1988 invisibles.push(Invisible::Tab {
1989 line_start_offset: line.len(),
1990 });
1991 }
1992 } else {
1993 invisibles.extend(
1994 line_chunk
1995 .chars()
1996 .enumerate()
1997 .filter(|(_, line_char)| {
1998 let is_whitespace = line_char.is_whitespace();
1999 non_whitespace_added |= !is_whitespace;
2000 is_whitespace
2001 && (non_whitespace_added || !inside_wrapped_string)
2002 })
2003 .map(|(whitespace_index, _)| Invisible::Whitespace {
2004 line_offset: line.len() + whitespace_index,
2005 }),
2006 )
2007 }
2008 }
2009
2010 line.push_str(line_chunk);
2011 }
2012 }
2013 }
2014
2015 layouts
2016 }
2017
2018 fn draw(
2019 &self,
2020 layout: &LayoutState,
2021 row: u32,
2022 scroll_top: f32,
2023 scene: &mut SceneBuilder,
2024 content_origin: Vector2F,
2025 scroll_left: f32,
2026 visible_text_bounds: RectF,
2027 whitespace_setting: ShowWhitespaceSetting,
2028 selection_ranges: &[Range<DisplayPoint>],
2029 visible_bounds: RectF,
2030 cx: &mut ViewContext<Editor>,
2031 ) {
2032 let line_height = layout.position_map.line_height;
2033 let line_y = row as f32 * line_height - scroll_top;
2034
2035 self.line.paint(
2036 scene,
2037 content_origin + vec2f(-scroll_left, line_y),
2038 visible_text_bounds,
2039 line_height,
2040 cx,
2041 );
2042
2043 self.draw_invisibles(
2044 &selection_ranges,
2045 layout,
2046 content_origin,
2047 scroll_left,
2048 line_y,
2049 row,
2050 scene,
2051 visible_bounds,
2052 line_height,
2053 whitespace_setting,
2054 cx,
2055 );
2056 }
2057
2058 fn draw_invisibles(
2059 &self,
2060 selection_ranges: &[Range<DisplayPoint>],
2061 layout: &LayoutState,
2062 content_origin: Vector2F,
2063 scroll_left: f32,
2064 line_y: f32,
2065 row: u32,
2066 scene: &mut SceneBuilder,
2067 visible_bounds: RectF,
2068 line_height: f32,
2069 whitespace_setting: ShowWhitespaceSetting,
2070 cx: &mut ViewContext<Editor>,
2071 ) {
2072 let allowed_invisibles_regions = match whitespace_setting {
2073 ShowWhitespaceSetting::None => return,
2074 ShowWhitespaceSetting::Selection => Some(selection_ranges),
2075 ShowWhitespaceSetting::All => None,
2076 };
2077
2078 for invisible in &self.invisibles {
2079 let (&token_offset, invisible_symbol) = match invisible {
2080 Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
2081 Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
2082 };
2083
2084 let x_offset = self.line.x_for_index(token_offset);
2085 let invisible_offset =
2086 (layout.position_map.em_width - invisible_symbol.width()).max(0.0) / 2.0;
2087 let origin = content_origin + vec2f(-scroll_left + x_offset + invisible_offset, line_y);
2088
2089 if let Some(allowed_regions) = allowed_invisibles_regions {
2090 let invisible_point = DisplayPoint::new(row, token_offset as u32);
2091 if !allowed_regions
2092 .iter()
2093 .any(|region| region.start <= invisible_point && invisible_point < region.end)
2094 {
2095 continue;
2096 }
2097 }
2098 invisible_symbol.paint(scene, origin, visible_bounds, line_height, cx);
2099 }
2100 }
2101}
2102
2103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2104enum Invisible {
2105 Tab { line_start_offset: usize },
2106 Whitespace { line_offset: usize },
2107}
2108
2109impl Element<Editor> for EditorElement {
2110 type LayoutState = LayoutState;
2111 type PaintState = ();
2112
2113 fn layout(
2114 &mut self,
2115 constraint: SizeConstraint,
2116 editor: &mut Editor,
2117 cx: &mut LayoutContext<Editor>,
2118 ) -> (Vector2F, Self::LayoutState) {
2119 let mut size = constraint.max;
2120 if size.x().is_infinite() {
2121 unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
2122 }
2123
2124 let snapshot = editor.snapshot(cx);
2125 let style = self.style.clone();
2126
2127 let line_height = (style.text.font_size * style.line_height_scalar).round();
2128
2129 let gutter_padding;
2130 let gutter_width;
2131 let gutter_margin;
2132 if snapshot.show_gutter {
2133 let em_width = style.text.em_width(cx.font_cache());
2134 gutter_padding = (em_width * style.gutter_padding_factor).round();
2135 gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
2136 gutter_margin = -style.text.descent(cx.font_cache());
2137 } else {
2138 gutter_padding = 0.0;
2139 gutter_width = 0.0;
2140 gutter_margin = 0.0;
2141 };
2142
2143 let text_width = size.x() - gutter_width;
2144 let em_width = style.text.em_width(cx.font_cache());
2145 let em_advance = style.text.em_advance(cx.font_cache());
2146 let overscroll = vec2f(em_width, 0.);
2147 let snapshot = {
2148 editor.set_visible_line_count(size.y() / line_height, cx);
2149
2150 let editor_width = text_width - gutter_margin - overscroll.x() - em_width;
2151 let wrap_width = match editor.soft_wrap_mode(cx) {
2152 SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
2153 SoftWrap::EditorWidth => editor_width,
2154 SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
2155 };
2156
2157 if editor.set_wrap_width(Some(wrap_width), cx) {
2158 editor.snapshot(cx)
2159 } else {
2160 snapshot
2161 }
2162 };
2163
2164 let wrap_guides = editor
2165 .wrap_guides(cx)
2166 .iter()
2167 .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
2168 .collect();
2169
2170 let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
2171 if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
2172 size.set_y(
2173 scroll_height
2174 .min(constraint.max_along(Axis::Vertical))
2175 .max(constraint.min_along(Axis::Vertical))
2176 .min(line_height * max_lines as f32),
2177 )
2178 } else if let EditorMode::SingleLine = snapshot.mode {
2179 size.set_y(
2180 line_height
2181 .min(constraint.max_along(Axis::Vertical))
2182 .max(constraint.min_along(Axis::Vertical)),
2183 )
2184 } else if size.y().is_infinite() {
2185 size.set_y(scroll_height);
2186 }
2187 let gutter_size = vec2f(gutter_width, size.y());
2188 let text_size = vec2f(text_width, size.y());
2189
2190 let autoscroll_horizontally = editor.autoscroll_vertically(size.y(), line_height, cx);
2191 let mut snapshot = editor.snapshot(cx);
2192
2193 let scroll_position = snapshot.scroll_position();
2194 // The scroll position is a fractional point, the whole number of which represents
2195 // the top of the window in terms of display rows.
2196 let start_row = scroll_position.y() as u32;
2197 let height_in_lines = size.y() / line_height;
2198 let max_row = snapshot.max_point().row();
2199
2200 // Add 1 to ensure selections bleed off screen
2201 let end_row = 1 + cmp::min(
2202 (scroll_position.y() + height_in_lines).ceil() as u32,
2203 max_row,
2204 );
2205
2206 let start_anchor = if start_row == 0 {
2207 Anchor::min()
2208 } else {
2209 snapshot
2210 .buffer_snapshot
2211 .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
2212 };
2213 let end_anchor = if end_row > max_row {
2214 Anchor::max()
2215 } else {
2216 snapshot
2217 .buffer_snapshot
2218 .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
2219 };
2220
2221 let mut selections: Vec<(Option<ReplicaId>, Vec<SelectionLayout>)> = Vec::new();
2222 let mut active_rows = BTreeMap::new();
2223 let mut fold_ranges = Vec::new();
2224 let is_singleton = editor.is_singleton(cx);
2225
2226 let highlighted_rows = editor.highlighted_rows();
2227 let theme = theme::current(cx);
2228 let highlighted_ranges = editor.background_highlights_in_range(
2229 start_anchor..end_anchor,
2230 &snapshot.display_snapshot,
2231 theme.as_ref(),
2232 );
2233
2234 fold_ranges.extend(
2235 snapshot
2236 .folds_in_range(start_anchor..end_anchor)
2237 .map(|anchor| {
2238 let start = anchor.start.to_point(&snapshot.buffer_snapshot);
2239 (
2240 start.row,
2241 start.to_display_point(&snapshot.display_snapshot)
2242 ..anchor.end.to_display_point(&snapshot),
2243 )
2244 }),
2245 );
2246
2247 let mut remote_selections = HashMap::default();
2248 for (replica_id, line_mode, cursor_shape, selection) in snapshot
2249 .buffer_snapshot
2250 .remote_selections_in_range(&(start_anchor..end_anchor))
2251 {
2252 let replica_id = if let Some(mapping) = &editor.replica_id_mapping {
2253 mapping.get(&replica_id).copied()
2254 } else {
2255 None
2256 };
2257
2258 // The local selections match the leader's selections.
2259 if replica_id.is_some() && replica_id == editor.leader_replica_id {
2260 continue;
2261 }
2262 remote_selections
2263 .entry(replica_id)
2264 .or_insert(Vec::new())
2265 .push(SelectionLayout::new(
2266 selection,
2267 line_mode,
2268 cursor_shape,
2269 &snapshot.display_snapshot,
2270 false,
2271 false,
2272 ));
2273 }
2274 selections.extend(remote_selections);
2275
2276 let mut newest_selection_head = None;
2277
2278 if editor.show_local_selections {
2279 let mut local_selections: Vec<Selection<Point>> = editor
2280 .selections
2281 .disjoint_in_range(start_anchor..end_anchor, cx);
2282 local_selections.extend(editor.selections.pending(cx));
2283 let mut layouts = Vec::new();
2284 let newest = editor.selections.newest(cx);
2285 for selection in local_selections.drain(..) {
2286 let is_empty = selection.start == selection.end;
2287 let is_newest = selection == newest;
2288
2289 let layout = SelectionLayout::new(
2290 selection,
2291 editor.selections.line_mode,
2292 editor.cursor_shape,
2293 &snapshot.display_snapshot,
2294 is_newest,
2295 true,
2296 );
2297 if is_newest {
2298 newest_selection_head = Some(layout.head);
2299 }
2300
2301 for row in cmp::max(layout.active_rows.start, start_row)
2302 ..=cmp::min(layout.active_rows.end, end_row)
2303 {
2304 let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
2305 *contains_non_empty_selection |= !is_empty;
2306 }
2307 layouts.push(layout);
2308 }
2309
2310 // Render the local selections in the leader's color when following.
2311 let local_replica_id = if let Some(leader_replica_id) = editor.leader_replica_id {
2312 leader_replica_id
2313 } else {
2314 let replica_id = editor.replica_id(cx);
2315 if let Some(mapping) = &editor.replica_id_mapping {
2316 mapping.get(&replica_id).copied().unwrap_or(replica_id)
2317 } else {
2318 replica_id
2319 }
2320 };
2321
2322 selections.push((Some(local_replica_id), layouts));
2323 }
2324
2325 let scrollbar_settings = &settings::get::<EditorSettings>(cx).scrollbar;
2326 let show_scrollbars = match scrollbar_settings.show {
2327 ShowScrollbar::Auto => {
2328 // Git
2329 (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_git_diffs())
2330 ||
2331 // Selections
2332 (is_singleton && scrollbar_settings.selections && !highlighted_ranges.is_empty())
2333 // Scrollmanager
2334 || editor.scroll_manager.scrollbars_visible()
2335 }
2336 ShowScrollbar::System => editor.scroll_manager.scrollbars_visible(),
2337 ShowScrollbar::Always => true,
2338 ShowScrollbar::Never => false,
2339 };
2340
2341 let fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)> = fold_ranges
2342 .into_iter()
2343 .map(|(id, fold)| {
2344 let color = self
2345 .style
2346 .folds
2347 .ellipses
2348 .background
2349 .style_for(&mut cx.mouse_state::<FoldMarkers>(id as usize))
2350 .color;
2351
2352 (id, fold, color)
2353 })
2354 .collect();
2355
2356 let (line_number_layouts, fold_statuses) = self.layout_line_numbers(
2357 start_row..end_row,
2358 &active_rows,
2359 is_singleton,
2360 &snapshot,
2361 cx,
2362 );
2363
2364 let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
2365
2366 let scrollbar_row_range = scroll_position.y()..(scroll_position.y() + height_in_lines);
2367
2368 let mut max_visible_line_width = 0.0;
2369 let line_layouts =
2370 self.layout_lines(start_row..end_row, &line_number_layouts, &snapshot, cx);
2371 for line_with_invisibles in &line_layouts {
2372 if line_with_invisibles.line.width() > max_visible_line_width {
2373 max_visible_line_width = line_with_invisibles.line.width();
2374 }
2375 }
2376
2377 let style = self.style.clone();
2378 let longest_line_width = layout_line(
2379 snapshot.longest_row(),
2380 &snapshot,
2381 &style,
2382 cx.text_layout_cache(),
2383 )
2384 .width();
2385 let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
2386 let em_width = style.text.em_width(cx.font_cache());
2387 let (scroll_width, blocks) = self.layout_blocks(
2388 start_row..end_row,
2389 &snapshot,
2390 size.x(),
2391 scroll_width,
2392 gutter_padding,
2393 gutter_width,
2394 em_width,
2395 gutter_width + gutter_margin,
2396 line_height,
2397 &style,
2398 &line_layouts,
2399 editor,
2400 cx,
2401 );
2402
2403 let scroll_max = vec2f(
2404 ((scroll_width - text_size.x()) / em_width).max(0.0),
2405 max_row as f32,
2406 );
2407
2408 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x());
2409
2410 let autoscrolled = if autoscroll_horizontally {
2411 editor.autoscroll_horizontally(
2412 start_row,
2413 text_size.x(),
2414 scroll_width,
2415 em_width,
2416 &line_layouts,
2417 cx,
2418 )
2419 } else {
2420 false
2421 };
2422
2423 if clamped || autoscrolled {
2424 snapshot = editor.snapshot(cx);
2425 }
2426
2427 let style = editor.style(cx);
2428
2429 let mut context_menu = None;
2430 let mut code_actions_indicator = None;
2431 if let Some(newest_selection_head) = newest_selection_head {
2432 if (start_row..end_row).contains(&newest_selection_head.row()) {
2433 if editor.context_menu_visible() {
2434 context_menu =
2435 editor.render_context_menu(newest_selection_head, style.clone(), cx);
2436 }
2437
2438 let active = matches!(
2439 editor.context_menu,
2440 Some(crate::ContextMenu::CodeActions(_))
2441 );
2442
2443 code_actions_indicator = editor
2444 .render_code_actions_indicator(&style, active, cx)
2445 .map(|indicator| (newest_selection_head.row(), indicator));
2446 }
2447 }
2448
2449 let visible_rows = start_row..start_row + line_layouts.len() as u32;
2450 let mut hover = editor
2451 .hover_state
2452 .render(&snapshot, &style, visible_rows, cx);
2453 let mode = editor.mode;
2454
2455 let mut fold_indicators = editor.render_fold_indicators(
2456 fold_statuses,
2457 &style,
2458 editor.gutter_hovered,
2459 line_height,
2460 gutter_margin,
2461 cx,
2462 );
2463
2464 if let Some((_, context_menu)) = context_menu.as_mut() {
2465 context_menu.layout(
2466 SizeConstraint {
2467 min: Vector2F::zero(),
2468 max: vec2f(
2469 cx.window_size().x() * 0.7,
2470 (12. * line_height).min((size.y() - line_height) / 2.),
2471 ),
2472 },
2473 editor,
2474 cx,
2475 );
2476 }
2477
2478 if let Some((_, indicator)) = code_actions_indicator.as_mut() {
2479 indicator.layout(
2480 SizeConstraint::strict_along(
2481 Axis::Vertical,
2482 line_height * style.code_actions.vertical_scale,
2483 ),
2484 editor,
2485 cx,
2486 );
2487 }
2488
2489 for fold_indicator in fold_indicators.iter_mut() {
2490 if let Some(indicator) = fold_indicator.as_mut() {
2491 indicator.layout(
2492 SizeConstraint::strict_along(
2493 Axis::Vertical,
2494 line_height * style.code_actions.vertical_scale,
2495 ),
2496 editor,
2497 cx,
2498 );
2499 }
2500 }
2501
2502 if let Some((_, hover_popovers)) = hover.as_mut() {
2503 for hover_popover in hover_popovers.iter_mut() {
2504 hover_popover.layout(
2505 SizeConstraint {
2506 min: Vector2F::zero(),
2507 max: vec2f(
2508 (120. * em_width) // Default size
2509 .min(size.x() / 2.) // Shrink to half of the editor width
2510 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2511 (16. * line_height) // Default size
2512 .min(size.y() / 2.) // Shrink to half of the editor height
2513 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2514 ),
2515 },
2516 editor,
2517 cx,
2518 );
2519 }
2520 }
2521
2522 let invisible_symbol_font_size = self.style.text.font_size / 2.0;
2523 let invisible_symbol_style = RunStyle {
2524 color: self.style.whitespace,
2525 font_id: self.style.text.font_id,
2526 underline: Default::default(),
2527 };
2528
2529 (
2530 size,
2531 LayoutState {
2532 mode,
2533 position_map: Arc::new(PositionMap {
2534 size,
2535 scroll_max,
2536 line_layouts,
2537 line_height,
2538 em_width,
2539 em_advance,
2540 snapshot,
2541 }),
2542 visible_display_row_range: start_row..end_row,
2543 wrap_guides,
2544 gutter_size,
2545 gutter_padding,
2546 text_size,
2547 scrollbar_row_range,
2548 show_scrollbars,
2549 is_singleton,
2550 max_row,
2551 gutter_margin,
2552 active_rows,
2553 highlighted_rows,
2554 highlighted_ranges,
2555 fold_ranges,
2556 line_number_layouts,
2557 display_hunks,
2558 blocks,
2559 selections,
2560 context_menu,
2561 code_actions_indicator,
2562 fold_indicators,
2563 tab_invisible: cx.text_layout_cache().layout_str(
2564 "→",
2565 invisible_symbol_font_size,
2566 &[("→".len(), invisible_symbol_style)],
2567 ),
2568 space_invisible: cx.text_layout_cache().layout_str(
2569 "•",
2570 invisible_symbol_font_size,
2571 &[("•".len(), invisible_symbol_style)],
2572 ),
2573 hover_popovers: hover,
2574 },
2575 )
2576 }
2577
2578 fn paint(
2579 &mut self,
2580 scene: &mut SceneBuilder,
2581 bounds: RectF,
2582 visible_bounds: RectF,
2583 layout: &mut Self::LayoutState,
2584 editor: &mut Editor,
2585 cx: &mut PaintContext<Editor>,
2586 ) -> Self::PaintState {
2587 let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
2588 scene.push_layer(Some(visible_bounds));
2589
2590 let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
2591 let text_bounds = RectF::new(
2592 bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
2593 layout.text_size,
2594 );
2595
2596 Self::attach_mouse_handlers(
2597 scene,
2598 &layout.position_map,
2599 layout.hover_popovers.is_some(),
2600 visible_bounds,
2601 text_bounds,
2602 gutter_bounds,
2603 bounds,
2604 cx,
2605 );
2606
2607 self.paint_background(scene, gutter_bounds, text_bounds, layout);
2608 if layout.gutter_size.x() > 0. {
2609 self.paint_gutter(scene, gutter_bounds, visible_bounds, layout, editor, cx);
2610 }
2611 self.paint_text(scene, text_bounds, visible_bounds, layout, editor, cx);
2612
2613 scene.push_layer(Some(bounds));
2614 if !layout.blocks.is_empty() {
2615 self.paint_blocks(scene, bounds, visible_bounds, layout, editor, cx);
2616 }
2617 self.paint_scrollbar(scene, bounds, layout, cx, &editor);
2618 scene.pop_layer();
2619
2620 scene.pop_layer();
2621 }
2622
2623 fn rect_for_text_range(
2624 &self,
2625 range_utf16: Range<usize>,
2626 bounds: RectF,
2627 _: RectF,
2628 layout: &Self::LayoutState,
2629 _: &Self::PaintState,
2630 _: &Editor,
2631 _: &ViewContext<Editor>,
2632 ) -> Option<RectF> {
2633 let text_bounds = RectF::new(
2634 bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
2635 layout.text_size,
2636 );
2637 let content_origin = text_bounds.origin() + vec2f(layout.gutter_margin, 0.);
2638 let scroll_position = layout.position_map.snapshot.scroll_position();
2639 let start_row = scroll_position.y() as u32;
2640 let scroll_top = scroll_position.y() * layout.position_map.line_height;
2641 let scroll_left = scroll_position.x() * layout.position_map.em_width;
2642
2643 let range_start = OffsetUtf16(range_utf16.start)
2644 .to_display_point(&layout.position_map.snapshot.display_snapshot);
2645 if range_start.row() < start_row {
2646 return None;
2647 }
2648
2649 let line = &layout
2650 .position_map
2651 .line_layouts
2652 .get((range_start.row() - start_row) as usize)?
2653 .line;
2654 let range_start_x = line.x_for_index(range_start.column() as usize);
2655 let range_start_y = range_start.row() as f32 * layout.position_map.line_height;
2656 Some(RectF::new(
2657 content_origin
2658 + vec2f(
2659 range_start_x,
2660 range_start_y + layout.position_map.line_height,
2661 )
2662 - vec2f(scroll_left, scroll_top),
2663 vec2f(
2664 layout.position_map.em_width,
2665 layout.position_map.line_height,
2666 ),
2667 ))
2668 }
2669
2670 fn debug(
2671 &self,
2672 bounds: RectF,
2673 _: &Self::LayoutState,
2674 _: &Self::PaintState,
2675 _: &Editor,
2676 _: &ViewContext<Editor>,
2677 ) -> json::Value {
2678 json!({
2679 "type": "BufferElement",
2680 "bounds": bounds.to_json()
2681 })
2682 }
2683}
2684
2685type BufferRow = u32;
2686
2687pub struct LayoutState {
2688 position_map: Arc<PositionMap>,
2689 gutter_size: Vector2F,
2690 gutter_padding: f32,
2691 gutter_margin: f32,
2692 text_size: Vector2F,
2693 mode: EditorMode,
2694 wrap_guides: SmallVec<[(f32, bool); 2]>,
2695 visible_display_row_range: Range<u32>,
2696 active_rows: BTreeMap<u32, bool>,
2697 highlighted_rows: Option<Range<u32>>,
2698 line_number_layouts: Vec<Option<text_layout::Line>>,
2699 display_hunks: Vec<DisplayDiffHunk>,
2700 blocks: Vec<BlockLayout>,
2701 highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
2702 fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)>,
2703 selections: Vec<(Option<ReplicaId>, Vec<SelectionLayout>)>,
2704 scrollbar_row_range: Range<f32>,
2705 show_scrollbars: bool,
2706 is_singleton: bool,
2707 max_row: u32,
2708 context_menu: Option<(DisplayPoint, AnyElement<Editor>)>,
2709 code_actions_indicator: Option<(u32, AnyElement<Editor>)>,
2710 hover_popovers: Option<(DisplayPoint, Vec<AnyElement<Editor>>)>,
2711 fold_indicators: Vec<Option<AnyElement<Editor>>>,
2712 tab_invisible: Line,
2713 space_invisible: Line,
2714}
2715
2716struct PositionMap {
2717 size: Vector2F,
2718 line_height: f32,
2719 scroll_max: Vector2F,
2720 em_width: f32,
2721 em_advance: f32,
2722 line_layouts: Vec<LineWithInvisibles>,
2723 snapshot: EditorSnapshot,
2724}
2725
2726#[derive(Debug)]
2727struct PointForPosition {
2728 previous_valid: DisplayPoint,
2729 next_valid: DisplayPoint,
2730 exact_unclipped: DisplayPoint,
2731 column_overshoot_after_line_end: u32,
2732}
2733
2734impl PointForPosition {
2735 fn as_valid(&self) -> Option<DisplayPoint> {
2736 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
2737 Some(self.previous_valid)
2738 } else {
2739 None
2740 }
2741 }
2742}
2743
2744impl PositionMap {
2745 fn point_for_position(&self, text_bounds: RectF, position: Vector2F) -> PointForPosition {
2746 let scroll_position = self.snapshot.scroll_position();
2747 let position = position - text_bounds.origin();
2748 let y = position.y().max(0.0).min(self.size.y());
2749 let x = position.x() + (scroll_position.x() * self.em_width);
2750 let row = (y / self.line_height + scroll_position.y()) as u32;
2751 let (column, x_overshoot_after_line_end) = if let Some(line) = self
2752 .line_layouts
2753 .get(row as usize - scroll_position.y() as usize)
2754 .map(|line_with_spaces| &line_with_spaces.line)
2755 {
2756 if let Some(ix) = line.index_for_x(x) {
2757 (ix as u32, 0.0)
2758 } else {
2759 (line.len() as u32, 0f32.max(x - line.width()))
2760 }
2761 } else {
2762 (0, x)
2763 };
2764
2765 let mut exact_unclipped = DisplayPoint::new(row, column);
2766 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
2767 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
2768
2769 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
2770 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
2771 PointForPosition {
2772 previous_valid,
2773 next_valid,
2774 exact_unclipped,
2775 column_overshoot_after_line_end,
2776 }
2777 }
2778}
2779
2780struct BlockLayout {
2781 row: u32,
2782 element: AnyElement<Editor>,
2783 style: BlockStyle,
2784}
2785
2786fn layout_line(
2787 row: u32,
2788 snapshot: &EditorSnapshot,
2789 style: &EditorStyle,
2790 layout_cache: &TextLayoutCache,
2791) -> text_layout::Line {
2792 let mut line = snapshot.line(row);
2793
2794 if line.len() > MAX_LINE_LEN {
2795 let mut len = MAX_LINE_LEN;
2796 while !line.is_char_boundary(len) {
2797 len -= 1;
2798 }
2799
2800 line.truncate(len);
2801 }
2802
2803 layout_cache.layout_str(
2804 &line,
2805 style.text.font_size,
2806 &[(
2807 snapshot.line_len(row) as usize,
2808 RunStyle {
2809 font_id: style.text.font_id,
2810 color: Color::black(),
2811 underline: Default::default(),
2812 },
2813 )],
2814 )
2815}
2816
2817#[derive(Debug)]
2818pub struct Cursor {
2819 origin: Vector2F,
2820 block_width: f32,
2821 line_height: f32,
2822 color: Color,
2823 shape: CursorShape,
2824 block_text: Option<Line>,
2825}
2826
2827impl Cursor {
2828 pub fn new(
2829 origin: Vector2F,
2830 block_width: f32,
2831 line_height: f32,
2832 color: Color,
2833 shape: CursorShape,
2834 block_text: Option<Line>,
2835 ) -> Cursor {
2836 Cursor {
2837 origin,
2838 block_width,
2839 line_height,
2840 color,
2841 shape,
2842 block_text,
2843 }
2844 }
2845
2846 pub fn bounding_rect(&self, origin: Vector2F) -> RectF {
2847 RectF::new(
2848 self.origin + origin,
2849 vec2f(self.block_width, self.line_height),
2850 )
2851 }
2852
2853 pub fn paint(&self, scene: &mut SceneBuilder, origin: Vector2F, cx: &mut WindowContext) {
2854 let bounds = match self.shape {
2855 CursorShape::Bar => RectF::new(self.origin + origin, vec2f(2.0, self.line_height)),
2856 CursorShape::Block | CursorShape::Hollow => RectF::new(
2857 self.origin + origin,
2858 vec2f(self.block_width, self.line_height),
2859 ),
2860 CursorShape::Underscore => RectF::new(
2861 self.origin + origin + Vector2F::new(0.0, self.line_height - 2.0),
2862 vec2f(self.block_width, 2.0),
2863 ),
2864 };
2865
2866 //Draw background or border quad
2867 if matches!(self.shape, CursorShape::Hollow) {
2868 scene.push_quad(Quad {
2869 bounds,
2870 background: None,
2871 border: Border::all(1., self.color),
2872 corner_radii: Default::default(),
2873 });
2874 } else {
2875 scene.push_quad(Quad {
2876 bounds,
2877 background: Some(self.color),
2878 border: Default::default(),
2879 corner_radii: Default::default(),
2880 });
2881 }
2882
2883 if let Some(block_text) = &self.block_text {
2884 block_text.paint(scene, self.origin + origin, bounds, self.line_height, cx);
2885 }
2886 }
2887
2888 pub fn shape(&self) -> CursorShape {
2889 self.shape
2890 }
2891}
2892
2893#[derive(Debug)]
2894pub struct HighlightedRange {
2895 pub start_y: f32,
2896 pub line_height: f32,
2897 pub lines: Vec<HighlightedRangeLine>,
2898 pub color: Color,
2899 pub corner_radius: f32,
2900}
2901
2902#[derive(Debug)]
2903pub struct HighlightedRangeLine {
2904 pub start_x: f32,
2905 pub end_x: f32,
2906}
2907
2908impl HighlightedRange {
2909 pub fn paint(&self, bounds: RectF, scene: &mut SceneBuilder) {
2910 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
2911 self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
2912 self.paint_lines(
2913 self.start_y + self.line_height,
2914 &self.lines[1..],
2915 bounds,
2916 scene,
2917 );
2918 } else {
2919 self.paint_lines(self.start_y, &self.lines, bounds, scene);
2920 }
2921 }
2922
2923 fn paint_lines(
2924 &self,
2925 start_y: f32,
2926 lines: &[HighlightedRangeLine],
2927 bounds: RectF,
2928 scene: &mut SceneBuilder,
2929 ) {
2930 if lines.is_empty() {
2931 return;
2932 }
2933
2934 let mut path = PathBuilder::new();
2935 let first_line = lines.first().unwrap();
2936 let last_line = lines.last().unwrap();
2937
2938 let first_top_left = vec2f(first_line.start_x, start_y);
2939 let first_top_right = vec2f(first_line.end_x, start_y);
2940
2941 let curve_height = vec2f(0., self.corner_radius);
2942 let curve_width = |start_x: f32, end_x: f32| {
2943 let max = (end_x - start_x) / 2.;
2944 let width = if max < self.corner_radius {
2945 max
2946 } else {
2947 self.corner_radius
2948 };
2949
2950 vec2f(width, 0.)
2951 };
2952
2953 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
2954 path.reset(first_top_right - top_curve_width);
2955 path.curve_to(first_top_right + curve_height, first_top_right);
2956
2957 let mut iter = lines.iter().enumerate().peekable();
2958 while let Some((ix, line)) = iter.next() {
2959 let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
2960
2961 if let Some((_, next_line)) = iter.peek() {
2962 let next_top_right = vec2f(next_line.end_x, bottom_right.y());
2963
2964 match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
2965 Ordering::Equal => {
2966 path.line_to(bottom_right);
2967 }
2968 Ordering::Less => {
2969 let curve_width = curve_width(next_top_right.x(), bottom_right.x());
2970 path.line_to(bottom_right - curve_height);
2971 if self.corner_radius > 0. {
2972 path.curve_to(bottom_right - curve_width, bottom_right);
2973 }
2974 path.line_to(next_top_right + curve_width);
2975 if self.corner_radius > 0. {
2976 path.curve_to(next_top_right + curve_height, next_top_right);
2977 }
2978 }
2979 Ordering::Greater => {
2980 let curve_width = curve_width(bottom_right.x(), next_top_right.x());
2981 path.line_to(bottom_right - curve_height);
2982 if self.corner_radius > 0. {
2983 path.curve_to(bottom_right + curve_width, bottom_right);
2984 }
2985 path.line_to(next_top_right - curve_width);
2986 if self.corner_radius > 0. {
2987 path.curve_to(next_top_right + curve_height, next_top_right);
2988 }
2989 }
2990 }
2991 } else {
2992 let curve_width = curve_width(line.start_x, line.end_x);
2993 path.line_to(bottom_right - curve_height);
2994 if self.corner_radius > 0. {
2995 path.curve_to(bottom_right - curve_width, bottom_right);
2996 }
2997
2998 let bottom_left = vec2f(line.start_x, bottom_right.y());
2999 path.line_to(bottom_left + curve_width);
3000 if self.corner_radius > 0. {
3001 path.curve_to(bottom_left - curve_height, bottom_left);
3002 }
3003 }
3004 }
3005
3006 if first_line.start_x > last_line.start_x {
3007 let curve_width = curve_width(last_line.start_x, first_line.start_x);
3008 let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
3009 path.line_to(second_top_left + curve_height);
3010 if self.corner_radius > 0. {
3011 path.curve_to(second_top_left + curve_width, second_top_left);
3012 }
3013 let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
3014 path.line_to(first_bottom_left - curve_width);
3015 if self.corner_radius > 0. {
3016 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
3017 }
3018 }
3019
3020 path.line_to(first_top_left + curve_height);
3021 if self.corner_radius > 0. {
3022 path.curve_to(first_top_left + top_curve_width, first_top_left);
3023 }
3024 path.line_to(first_top_right - top_curve_width);
3025
3026 scene.push_path(path.build(self.color, Some(bounds)));
3027 }
3028}
3029
3030fn range_to_bounds(
3031 range: &Range<DisplayPoint>,
3032 content_origin: Vector2F,
3033 scroll_left: f32,
3034 scroll_top: f32,
3035 visible_row_range: &Range<u32>,
3036 line_end_overshoot: f32,
3037 position_map: &PositionMap,
3038) -> impl Iterator<Item = RectF> {
3039 let mut bounds: SmallVec<[RectF; 1]> = SmallVec::new();
3040
3041 if range.start == range.end {
3042 return bounds.into_iter();
3043 }
3044
3045 let start_row = visible_row_range.start;
3046 let end_row = visible_row_range.end;
3047
3048 let row_range = if range.end.column() == 0 {
3049 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
3050 } else {
3051 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
3052 };
3053
3054 let first_y =
3055 content_origin.y() + row_range.start as f32 * position_map.line_height - scroll_top;
3056
3057 for (idx, row) in row_range.enumerate() {
3058 let line_layout = &position_map.line_layouts[(row - start_row) as usize].line;
3059
3060 let start_x = if row == range.start.row() {
3061 content_origin.x() + line_layout.x_for_index(range.start.column() as usize)
3062 - scroll_left
3063 } else {
3064 content_origin.x() - scroll_left
3065 };
3066
3067 let end_x = if row == range.end.row() {
3068 content_origin.x() + line_layout.x_for_index(range.end.column() as usize) - scroll_left
3069 } else {
3070 content_origin.x() + line_layout.width() + line_end_overshoot - scroll_left
3071 };
3072
3073 bounds.push(RectF::from_points(
3074 vec2f(start_x, first_y + position_map.line_height * idx as f32),
3075 vec2f(end_x, first_y + position_map.line_height * (idx + 1) as f32),
3076 ))
3077 }
3078
3079 bounds.into_iter()
3080}
3081
3082pub fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
3083 delta.powf(1.5) / 100.0
3084}
3085
3086fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
3087 delta.powf(1.2) / 300.0
3088}
3089
3090#[cfg(test)]
3091mod tests {
3092 use super::*;
3093 use crate::{
3094 display_map::{BlockDisposition, BlockProperties},
3095 editor_tests::{init_test, update_test_language_settings},
3096 Editor, MultiBuffer,
3097 };
3098 use gpui::TestAppContext;
3099 use language::language_settings;
3100 use log::info;
3101 use std::{num::NonZeroU32, sync::Arc};
3102 use util::test::sample_text;
3103
3104 #[gpui::test]
3105 fn test_layout_line_numbers(cx: &mut TestAppContext) {
3106 init_test(cx, |_| {});
3107
3108 let editor = cx
3109 .add_window(|cx| {
3110 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
3111 Editor::new(EditorMode::Full, buffer, None, None, cx)
3112 })
3113 .root(cx);
3114 let element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3115
3116 let layouts = editor.update(cx, |editor, cx| {
3117 let snapshot = editor.snapshot(cx);
3118 element
3119 .layout_line_numbers(0..6, &Default::default(), false, &snapshot, cx)
3120 .0
3121 });
3122 assert_eq!(layouts.len(), 6);
3123 }
3124
3125 #[gpui::test]
3126 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
3127 init_test(cx, |_| {});
3128
3129 let editor = cx
3130 .add_window(|cx| {
3131 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
3132 Editor::new(EditorMode::Full, buffer, None, None, cx)
3133 })
3134 .root(cx);
3135 let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3136 let (_, state) = editor.update(cx, |editor, cx| {
3137 editor.cursor_shape = CursorShape::Block;
3138 editor.change_selections(None, cx, |s| {
3139 s.select_ranges([
3140 Point::new(0, 0)..Point::new(1, 0),
3141 Point::new(3, 2)..Point::new(3, 3),
3142 Point::new(5, 6)..Point::new(6, 0),
3143 ]);
3144 });
3145 let mut new_parents = Default::default();
3146 let mut notify_views_if_parents_change = Default::default();
3147 let mut layout_cx = LayoutContext::new(
3148 cx,
3149 &mut new_parents,
3150 &mut notify_views_if_parents_change,
3151 false,
3152 );
3153 element.layout(
3154 SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
3155 editor,
3156 &mut layout_cx,
3157 )
3158 });
3159 assert_eq!(state.selections.len(), 1);
3160 let local_selections = &state.selections[0].1;
3161 assert_eq!(local_selections.len(), 3);
3162 // moves cursor back one line
3163 assert_eq!(local_selections[0].head, DisplayPoint::new(0, 6));
3164 assert_eq!(
3165 local_selections[0].range,
3166 DisplayPoint::new(0, 0)..DisplayPoint::new(1, 0)
3167 );
3168
3169 // moves cursor back one column
3170 assert_eq!(
3171 local_selections[1].range,
3172 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 3)
3173 );
3174 assert_eq!(local_selections[1].head, DisplayPoint::new(3, 2));
3175
3176 // leaves cursor on the max point
3177 assert_eq!(
3178 local_selections[2].range,
3179 DisplayPoint::new(5, 6)..DisplayPoint::new(6, 0)
3180 );
3181 assert_eq!(local_selections[2].head, DisplayPoint::new(6, 0));
3182
3183 // active lines does not include 1 (even though the range of the selection does)
3184 assert_eq!(
3185 state.active_rows.keys().cloned().collect::<Vec<u32>>(),
3186 vec![0, 3, 5, 6]
3187 );
3188
3189 // multi-buffer support
3190 // in DisplayPoint co-ordinates, this is what we're dealing with:
3191 // 0: [[file
3192 // 1: header]]
3193 // 2: aaaaaa
3194 // 3: bbbbbb
3195 // 4: cccccc
3196 // 5:
3197 // 6: ...
3198 // 7: ffffff
3199 // 8: gggggg
3200 // 9: hhhhhh
3201 // 10:
3202 // 11: [[file
3203 // 12: header]]
3204 // 13: bbbbbb
3205 // 14: cccccc
3206 // 15: dddddd
3207 let editor = cx
3208 .add_window(|cx| {
3209 let buffer = MultiBuffer::build_multi(
3210 [
3211 (
3212 &(sample_text(8, 6, 'a') + "\n"),
3213 vec![
3214 Point::new(0, 0)..Point::new(3, 0),
3215 Point::new(4, 0)..Point::new(7, 0),
3216 ],
3217 ),
3218 (
3219 &(sample_text(8, 6, 'a') + "\n"),
3220 vec![Point::new(1, 0)..Point::new(3, 0)],
3221 ),
3222 ],
3223 cx,
3224 );
3225 Editor::new(EditorMode::Full, buffer, None, None, cx)
3226 })
3227 .root(cx);
3228 let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3229 let (_, state) = editor.update(cx, |editor, cx| {
3230 editor.cursor_shape = CursorShape::Block;
3231 editor.change_selections(None, cx, |s| {
3232 s.select_display_ranges([
3233 DisplayPoint::new(4, 0)..DisplayPoint::new(7, 0),
3234 DisplayPoint::new(10, 0)..DisplayPoint::new(13, 0),
3235 ]);
3236 });
3237 let mut new_parents = Default::default();
3238 let mut notify_views_if_parents_change = Default::default();
3239 let mut layout_cx = LayoutContext::new(
3240 cx,
3241 &mut new_parents,
3242 &mut notify_views_if_parents_change,
3243 false,
3244 );
3245 element.layout(
3246 SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
3247 editor,
3248 &mut layout_cx,
3249 )
3250 });
3251
3252 assert_eq!(state.selections.len(), 1);
3253 let local_selections = &state.selections[0].1;
3254 assert_eq!(local_selections.len(), 2);
3255
3256 // moves cursor on excerpt boundary back a line
3257 // and doesn't allow selection to bleed through
3258 assert_eq!(
3259 local_selections[0].range,
3260 DisplayPoint::new(4, 0)..DisplayPoint::new(6, 0)
3261 );
3262 assert_eq!(local_selections[0].head, DisplayPoint::new(5, 0));
3263
3264 // moves cursor on buffer boundary back two lines
3265 // and doesn't allow selection to bleed through
3266 assert_eq!(
3267 local_selections[1].range,
3268 DisplayPoint::new(10, 0)..DisplayPoint::new(11, 0)
3269 );
3270 assert_eq!(local_selections[1].head, DisplayPoint::new(10, 0));
3271 }
3272
3273 #[gpui::test]
3274 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
3275 init_test(cx, |_| {});
3276
3277 let editor = cx
3278 .add_window(|cx| {
3279 let buffer = MultiBuffer::build_simple("", cx);
3280 Editor::new(EditorMode::Full, buffer, None, None, cx)
3281 })
3282 .root(cx);
3283
3284 editor.update(cx, |editor, cx| {
3285 editor.set_placeholder_text("hello", cx);
3286 editor.insert_blocks(
3287 [BlockProperties {
3288 style: BlockStyle::Fixed,
3289 disposition: BlockDisposition::Above,
3290 height: 3,
3291 position: Anchor::min(),
3292 render: Arc::new(|_| Empty::new().into_any()),
3293 }],
3294 None,
3295 cx,
3296 );
3297
3298 // Blur the editor so that it displays placeholder text.
3299 cx.blur();
3300 });
3301
3302 let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3303 let (size, mut state) = editor.update(cx, |editor, cx| {
3304 let mut new_parents = Default::default();
3305 let mut notify_views_if_parents_change = Default::default();
3306 let mut layout_cx = LayoutContext::new(
3307 cx,
3308 &mut new_parents,
3309 &mut notify_views_if_parents_change,
3310 false,
3311 );
3312 element.layout(
3313 SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
3314 editor,
3315 &mut layout_cx,
3316 )
3317 });
3318
3319 assert_eq!(state.position_map.line_layouts.len(), 4);
3320 assert_eq!(
3321 state
3322 .line_number_layouts
3323 .iter()
3324 .map(Option::is_some)
3325 .collect::<Vec<_>>(),
3326 &[false, false, false, true]
3327 );
3328
3329 // Don't panic.
3330 let mut scene = SceneBuilder::new(1.0);
3331 let bounds = RectF::new(Default::default(), size);
3332 editor.update(cx, |editor, cx| {
3333 element.paint(
3334 &mut scene,
3335 bounds,
3336 bounds,
3337 &mut state,
3338 editor,
3339 &mut PaintContext::new(cx),
3340 );
3341 });
3342 }
3343
3344 #[gpui::test]
3345 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
3346 const TAB_SIZE: u32 = 4;
3347
3348 let input_text = "\t \t|\t| a b";
3349 let expected_invisibles = vec![
3350 Invisible::Tab {
3351 line_start_offset: 0,
3352 },
3353 Invisible::Whitespace {
3354 line_offset: TAB_SIZE as usize,
3355 },
3356 Invisible::Tab {
3357 line_start_offset: TAB_SIZE as usize + 1,
3358 },
3359 Invisible::Tab {
3360 line_start_offset: TAB_SIZE as usize * 2 + 1,
3361 },
3362 Invisible::Whitespace {
3363 line_offset: TAB_SIZE as usize * 3 + 1,
3364 },
3365 Invisible::Whitespace {
3366 line_offset: TAB_SIZE as usize * 3 + 3,
3367 },
3368 ];
3369 assert_eq!(
3370 expected_invisibles.len(),
3371 input_text
3372 .chars()
3373 .filter(|initial_char| initial_char.is_whitespace())
3374 .count(),
3375 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
3376 );
3377
3378 init_test(cx, |s| {
3379 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3380 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
3381 });
3382
3383 let actual_invisibles =
3384 collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, 500.0);
3385
3386 assert_eq!(expected_invisibles, actual_invisibles);
3387 }
3388
3389 #[gpui::test]
3390 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
3391 init_test(cx, |s| {
3392 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3393 s.defaults.tab_size = NonZeroU32::new(4);
3394 });
3395
3396 for editor_mode_without_invisibles in [
3397 EditorMode::SingleLine,
3398 EditorMode::AutoHeight { max_lines: 100 },
3399 ] {
3400 let invisibles = collect_invisibles_from_new_editor(
3401 cx,
3402 editor_mode_without_invisibles,
3403 "\t\t\t| | a b",
3404 500.0,
3405 );
3406 assert!(invisibles.is_empty(),
3407 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
3408 }
3409 }
3410
3411 #[gpui::test]
3412 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
3413 let tab_size = 4;
3414 let input_text = "a\tbcd ".repeat(9);
3415 let repeated_invisibles = [
3416 Invisible::Tab {
3417 line_start_offset: 1,
3418 },
3419 Invisible::Whitespace {
3420 line_offset: tab_size as usize + 3,
3421 },
3422 Invisible::Whitespace {
3423 line_offset: tab_size as usize + 4,
3424 },
3425 Invisible::Whitespace {
3426 line_offset: tab_size as usize + 5,
3427 },
3428 ];
3429 let expected_invisibles = std::iter::once(repeated_invisibles)
3430 .cycle()
3431 .take(9)
3432 .flatten()
3433 .collect::<Vec<_>>();
3434 assert_eq!(
3435 expected_invisibles.len(),
3436 input_text
3437 .chars()
3438 .filter(|initial_char| initial_char.is_whitespace())
3439 .count(),
3440 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
3441 );
3442 info!("Expected invisibles: {expected_invisibles:?}");
3443
3444 init_test(cx, |_| {});
3445
3446 // Put the same string with repeating whitespace pattern into editors of various size,
3447 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
3448 let resize_step = 10.0;
3449 let mut editor_width = 200.0;
3450 while editor_width <= 1000.0 {
3451 update_test_language_settings(cx, |s| {
3452 s.defaults.tab_size = NonZeroU32::new(tab_size);
3453 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3454 s.defaults.preferred_line_length = Some(editor_width as u32);
3455 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
3456 });
3457
3458 let actual_invisibles =
3459 collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, editor_width);
3460
3461 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
3462 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
3463 let mut i = 0;
3464 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
3465 i = actual_index;
3466 match expected_invisibles.get(i) {
3467 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
3468 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
3469 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
3470 _ => {
3471 panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
3472 }
3473 },
3474 None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
3475 }
3476 }
3477 let missing_expected_invisibles = &expected_invisibles[i + 1..];
3478 assert!(
3479 missing_expected_invisibles.is_empty(),
3480 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
3481 );
3482
3483 editor_width += resize_step;
3484 }
3485 }
3486
3487 fn collect_invisibles_from_new_editor(
3488 cx: &mut TestAppContext,
3489 editor_mode: EditorMode,
3490 input_text: &str,
3491 editor_width: f32,
3492 ) -> Vec<Invisible> {
3493 info!(
3494 "Creating editor with mode {editor_mode:?}, width {editor_width} and text '{input_text}'"
3495 );
3496 let editor = cx
3497 .add_window(|cx| {
3498 let buffer = MultiBuffer::build_simple(&input_text, cx);
3499 Editor::new(editor_mode, buffer, None, None, cx)
3500 })
3501 .root(cx);
3502
3503 let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3504 let (_, layout_state) = editor.update(cx, |editor, cx| {
3505 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
3506 editor.set_wrap_width(Some(editor_width), cx);
3507
3508 let mut new_parents = Default::default();
3509 let mut notify_views_if_parents_change = Default::default();
3510 let mut layout_cx = LayoutContext::new(
3511 cx,
3512 &mut new_parents,
3513 &mut notify_views_if_parents_change,
3514 false,
3515 );
3516 element.layout(
3517 SizeConstraint::new(vec2f(editor_width, 500.), vec2f(editor_width, 500.)),
3518 editor,
3519 &mut layout_cx,
3520 )
3521 });
3522
3523 layout_state
3524 .position_map
3525 .line_layouts
3526 .iter()
3527 .map(|line_with_invisibles| &line_with_invisibles.invisibles)
3528 .flatten()
3529 .cloned()
3530 .collect()
3531 }
3532}