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