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)> = fold_ranges
1687 .into_iter()
1688 .map(|(id, fold)| {
1689 todo!("folds!")
1690 // let color = self
1691 // .style
1692 // .folds
1693 // .ellipses
1694 // .background
1695 // .style_for(&mut cx.mouse_state::<FoldMarkers>(id as usize))
1696 // .color;
1697
1698 // (id, fold, color)
1699 })
1700 .collect();
1701
1702 let head_for_relative = newest_selection_head.unwrap_or_else(|| {
1703 let newest = editor.selections.newest::<Point>(cx);
1704 SelectionLayout::new(
1705 newest,
1706 editor.selections.line_mode,
1707 editor.cursor_shape,
1708 &snapshot.display_snapshot,
1709 true,
1710 true,
1711 )
1712 .head
1713 });
1714
1715 let (line_number_layouts, fold_statuses) = self.layout_line_numbers(
1716 start_row..end_row,
1717 &active_rows,
1718 head_for_relative,
1719 is_singleton,
1720 &snapshot,
1721 cx,
1722 );
1723
1724 let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
1725
1726 let scrollbar_row_range = scroll_position.y..(scroll_position.y + height_in_lines);
1727
1728 let mut max_visible_line_width = Pixels::ZERO;
1729 let line_layouts =
1730 self.layout_lines(start_row..end_row, &line_number_layouts, &snapshot, cx);
1731 for line_with_invisibles in &line_layouts {
1732 if line_with_invisibles.line.width > max_visible_line_width {
1733 max_visible_line_width = line_with_invisibles.line.width;
1734 }
1735 }
1736
1737 let longest_line_width = layout_line(snapshot.longest_row(), &snapshot, &style, cx)
1738 .unwrap()
1739 .width;
1740 let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.width;
1741 // todo!("blocks")
1742 // let (scroll_width, blocks) = self.layout_blocks(
1743 // start_row..end_row,
1744 // &snapshot,
1745 // size.x,
1746 // scroll_width,
1747 // gutter_padding,
1748 // gutter_width,
1749 // em_width,
1750 // gutter_width + gutter_margin,
1751 // line_height,
1752 // &style,
1753 // &line_layouts,
1754 // editor,
1755 // cx,
1756 // );
1757
1758 let scroll_max = point(
1759 f32::from((scroll_width - text_size.width) / em_width).max(0.0),
1760 max_row as f32,
1761 );
1762
1763 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
1764
1765 let autoscrolled = if autoscroll_horizontally {
1766 editor.autoscroll_horizontally(
1767 start_row,
1768 text_size.width,
1769 scroll_width,
1770 em_width,
1771 &line_layouts,
1772 cx,
1773 )
1774 } else {
1775 false
1776 };
1777
1778 if clamped || autoscrolled {
1779 snapshot = editor.snapshot(cx);
1780 }
1781
1782 let mut context_menu = None;
1783 let mut code_actions_indicator = None;
1784 if let Some(newest_selection_head) = newest_selection_head {
1785 if (start_row..end_row).contains(&newest_selection_head.row()) {
1786 if editor.context_menu_visible() {
1787 context_menu =
1788 editor.render_context_menu(newest_selection_head, &self.style, cx);
1789 }
1790
1791 let active = matches!(
1792 editor.context_menu.read().as_ref(),
1793 Some(crate::ContextMenu::CodeActions(_))
1794 );
1795
1796 code_actions_indicator = editor
1797 .render_code_actions_indicator(&style, active, cx)
1798 .map(|element| CodeActionsIndicator {
1799 row: newest_selection_head.row(),
1800 element,
1801 });
1802 }
1803 }
1804
1805 let visible_rows = start_row..start_row + line_layouts.len() as u32;
1806 // todo!("hover")
1807 // let mut hover = editor.hover_state.render(
1808 // &snapshot,
1809 // &style,
1810 // visible_rows,
1811 // editor.workspace.as_ref().map(|(w, _)| w.clone()),
1812 // cx,
1813 // );
1814 // let mode = editor.mode;
1815
1816 // todo!("fold_indicators")
1817 // let mut fold_indicators = editor.render_fold_indicators(
1818 // fold_statuses,
1819 // &style,
1820 // editor.gutter_hovered,
1821 // line_height,
1822 // gutter_margin,
1823 // cx,
1824 // );
1825
1826 // todo!("context_menu")
1827 // if let Some((_, context_menu)) = context_menu.as_mut() {
1828 // context_menu.layout(
1829 // SizeConstraint {
1830 // min: gpui::Point::<Pixels>::zero(),
1831 // max: point(
1832 // cx.window_size().x * 0.7,
1833 // (12. * line_height).min((size.y - line_height) / 2.),
1834 // ),
1835 // },
1836 // editor,
1837 // cx,
1838 // );
1839 // }
1840
1841 // todo!("fold indicators")
1842 // for fold_indicator in fold_indicators.iter_mut() {
1843 // if let Some(indicator) = fold_indicator.as_mut() {
1844 // indicator.layout(
1845 // SizeConstraint::strict_along(
1846 // Axis::Vertical,
1847 // line_height * style.code_actions.vertical_scale,
1848 // ),
1849 // editor,
1850 // cx,
1851 // );
1852 // }
1853 // }
1854
1855 // todo!("hover popovers")
1856 // if let Some((_, hover_popovers)) = hover.as_mut() {
1857 // for hover_popover in hover_popovers.iter_mut() {
1858 // hover_popover.layout(
1859 // SizeConstraint {
1860 // min: gpui::Point::<Pixels>::zero(),
1861 // max: point(
1862 // (120. * em_width) // Default size
1863 // .min(size.x / 2.) // Shrink to half of the editor width
1864 // .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
1865 // (16. * line_height) // Default size
1866 // .min(size.y / 2.) // Shrink to half of the editor height
1867 // .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
1868 // ),
1869 // },
1870 // editor,
1871 // cx,
1872 // );
1873 // }
1874 // }
1875
1876 let invisible_symbol_font_size = font_size / 2.;
1877 let tab_invisible = cx
1878 .text_system()
1879 .layout_text(
1880 "→",
1881 invisible_symbol_font_size,
1882 &[TextRun {
1883 len: "→".len(),
1884 font: self.style.text.font(),
1885 color: cx.theme().colors().editor_invisible,
1886 underline: None,
1887 }],
1888 None,
1889 )
1890 .unwrap()
1891 .pop()
1892 .unwrap();
1893 let space_invisible = cx
1894 .text_system()
1895 .layout_text(
1896 "•",
1897 invisible_symbol_font_size,
1898 &[TextRun {
1899 len: "•".len(),
1900 font: self.style.text.font(),
1901 color: cx.theme().colors().editor_invisible,
1902 underline: None,
1903 }],
1904 None,
1905 )
1906 .unwrap()
1907 .pop()
1908 .unwrap();
1909
1910 LayoutState {
1911 mode: editor_mode,
1912 position_map: Arc::new(PositionMap {
1913 size: bounds.size,
1914 scroll_max,
1915 line_layouts,
1916 line_height,
1917 em_width,
1918 em_advance,
1919 snapshot,
1920 }),
1921 visible_display_row_range: start_row..end_row,
1922 wrap_guides,
1923 gutter_size,
1924 gutter_padding,
1925 text_size,
1926 scrollbar_row_range,
1927 show_scrollbars,
1928 is_singleton,
1929 max_row,
1930 gutter_margin,
1931 active_rows,
1932 highlighted_rows,
1933 highlighted_ranges,
1934 fold_ranges,
1935 line_number_layouts,
1936 display_hunks,
1937 // blocks,
1938 selections,
1939 context_menu,
1940 code_actions_indicator,
1941 // fold_indicators,
1942 tab_invisible,
1943 space_invisible,
1944 // hover_popovers: hover,
1945 }
1946 }
1947
1948 // #[allow(clippy::too_many_arguments)]
1949 // fn layout_blocks(
1950 // &mut self,
1951 // rows: Range<u32>,
1952 // snapshot: &EditorSnapshot,
1953 // editor_width: f32,
1954 // scroll_width: f32,
1955 // gutter_padding: f32,
1956 // gutter_width: f32,
1957 // em_width: f32,
1958 // text_x: f32,
1959 // line_height: f32,
1960 // style: &EditorStyle,
1961 // line_layouts: &[LineWithInvisibles],
1962 // editor: &mut Editor,
1963 // cx: &mut ViewContext<Editor>,
1964 // ) -> (f32, Vec<BlockLayout>) {
1965 // let mut block_id = 0;
1966 // let scroll_x = snapshot.scroll_anchor.offset.x;
1967 // let (fixed_blocks, non_fixed_blocks) = snapshot
1968 // .blocks_in_range(rows.clone())
1969 // .partition::<Vec<_>, _>(|(_, block)| match block {
1970 // TransformBlock::ExcerptHeader { .. } => false,
1971 // TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
1972 // });
1973 // let mut render_block = |block: &TransformBlock, width: f32, block_id: usize| {
1974 // let mut element = match block {
1975 // TransformBlock::Custom(block) => {
1976 // let align_to = block
1977 // .position()
1978 // .to_point(&snapshot.buffer_snapshot)
1979 // .to_display_point(snapshot);
1980 // let anchor_x = text_x
1981 // + if rows.contains(&align_to.row()) {
1982 // line_layouts[(align_to.row() - rows.start) as usize]
1983 // .line
1984 // .x_for_index(align_to.column() as usize)
1985 // } else {
1986 // layout_line(align_to.row(), snapshot, style, cx.text_layout_cache())
1987 // .x_for_index(align_to.column() as usize)
1988 // };
1989
1990 // block.render(&mut BlockContext {
1991 // view_context: cx,
1992 // anchor_x,
1993 // gutter_padding,
1994 // line_height,
1995 // scroll_x,
1996 // gutter_width,
1997 // em_width,
1998 // block_id,
1999 // })
2000 // }
2001 // TransformBlock::ExcerptHeader {
2002 // id,
2003 // buffer,
2004 // range,
2005 // starts_new_buffer,
2006 // ..
2007 // } => {
2008 // let tooltip_style = theme::current(cx).tooltip.clone();
2009 // let include_root = editor
2010 // .project
2011 // .as_ref()
2012 // .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
2013 // .unwrap_or_default();
2014 // let jump_icon = project::File::from_dyn(buffer.file()).map(|file| {
2015 // let jump_path = ProjectPath {
2016 // worktree_id: file.worktree_id(cx),
2017 // path: file.path.clone(),
2018 // };
2019 // let jump_anchor = range
2020 // .primary
2021 // .as_ref()
2022 // .map_or(range.context.start, |primary| primary.start);
2023 // let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
2024
2025 // enum JumpIcon {}
2026 // MouseEventHandler::new::<JumpIcon, _>((*id).into(), cx, |state, _| {
2027 // let style = style.jump_icon.style_for(state);
2028 // Svg::new("icons/arrow_up_right.svg")
2029 // .with_color(style.color)
2030 // .constrained()
2031 // .with_width(style.icon_width)
2032 // .aligned()
2033 // .contained()
2034 // .with_style(style.container)
2035 // .constrained()
2036 // .with_width(style.button_width)
2037 // .with_height(style.button_width)
2038 // })
2039 // .with_cursor_style(CursorStyle::PointingHand)
2040 // .on_click(MouseButton::Left, move |_, editor, cx| {
2041 // if let Some(workspace) = editor
2042 // .workspace
2043 // .as_ref()
2044 // .and_then(|(workspace, _)| workspace.upgrade(cx))
2045 // {
2046 // workspace.update(cx, |workspace, cx| {
2047 // Editor::jump(
2048 // workspace,
2049 // jump_path.clone(),
2050 // jump_position,
2051 // jump_anchor,
2052 // cx,
2053 // );
2054 // });
2055 // }
2056 // })
2057 // .with_tooltip::<JumpIcon>(
2058 // (*id).into(),
2059 // "Jump to Buffer".to_string(),
2060 // Some(Box::new(crate::OpenExcerpts)),
2061 // tooltip_style.clone(),
2062 // cx,
2063 // )
2064 // .aligned()
2065 // .flex_float()
2066 // });
2067
2068 // if *starts_new_buffer {
2069 // let editor_font_size = style.text.font_size;
2070 // let style = &style.diagnostic_path_header;
2071 // let font_size = (style.text_scale_factor * editor_font_size).round();
2072
2073 // let path = buffer.resolve_file_path(cx, include_root);
2074 // let mut filename = None;
2075 // let mut parent_path = None;
2076 // // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
2077 // if let Some(path) = path {
2078 // filename = path.file_name().map(|f| f.to_string_lossy.to_string());
2079 // parent_path =
2080 // path.parent().map(|p| p.to_string_lossy.to_string() + "/");
2081 // }
2082
2083 // Flex::row()
2084 // .with_child(
2085 // Label::new(
2086 // filename.unwrap_or_else(|| "untitled".to_string()),
2087 // style.filename.text.clone().with_font_size(font_size),
2088 // )
2089 // .contained()
2090 // .with_style(style.filename.container)
2091 // .aligned(),
2092 // )
2093 // .with_children(parent_path.map(|path| {
2094 // Label::new(path, style.path.text.clone().with_font_size(font_size))
2095 // .contained()
2096 // .with_style(style.path.container)
2097 // .aligned()
2098 // }))
2099 // .with_children(jump_icon)
2100 // .contained()
2101 // .with_style(style.container)
2102 // .with_padding_left(gutter_padding)
2103 // .with_padding_right(gutter_padding)
2104 // .expanded()
2105 // .into_any_named("path header block")
2106 // } else {
2107 // let text_style = style.text.clone();
2108 // Flex::row()
2109 // .with_child(Label::new("⋯", text_style))
2110 // .with_children(jump_icon)
2111 // .contained()
2112 // .with_padding_left(gutter_padding)
2113 // .with_padding_right(gutter_padding)
2114 // .expanded()
2115 // .into_any_named("collapsed context")
2116 // }
2117 // }
2118 // };
2119
2120 // element.layout(
2121 // SizeConstraint {
2122 // min: gpui::Point::<Pixels>::zero(),
2123 // max: point(width, block.height() as f32 * line_height),
2124 // },
2125 // editor,
2126 // cx,
2127 // );
2128 // element
2129 // };
2130
2131 // let mut fixed_block_max_width = 0f32;
2132 // let mut blocks = Vec::new();
2133 // for (row, block) in fixed_blocks {
2134 // let element = render_block(block, f32::INFINITY, block_id);
2135 // block_id += 1;
2136 // fixed_block_max_width = fixed_block_max_width.max(element.size().x + em_width);
2137 // blocks.push(BlockLayout {
2138 // row,
2139 // element,
2140 // style: BlockStyle::Fixed,
2141 // });
2142 // }
2143 // for (row, block) in non_fixed_blocks {
2144 // let style = match block {
2145 // TransformBlock::Custom(block) => block.style(),
2146 // TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
2147 // };
2148 // let width = match style {
2149 // BlockStyle::Sticky => editor_width,
2150 // BlockStyle::Flex => editor_width
2151 // .max(fixed_block_max_width)
2152 // .max(gutter_width + scroll_width),
2153 // BlockStyle::Fixed => unreachable!(),
2154 // };
2155 // let element = render_block(block, width, block_id);
2156 // block_id += 1;
2157 // blocks.push(BlockLayout {
2158 // row,
2159 // element,
2160 // style,
2161 // });
2162 // }
2163 // (
2164 // scroll_width.max(fixed_block_max_width - gutter_width),
2165 // blocks,
2166 // )
2167 // }
2168
2169 fn paint_mouse_listeners(
2170 &mut self,
2171 bounds: Bounds<Pixels>,
2172 gutter_bounds: Bounds<Pixels>,
2173 text_bounds: Bounds<Pixels>,
2174 position_map: &Arc<PositionMap>,
2175 cx: &mut ViewContext<Editor>,
2176 ) {
2177 cx.on_mouse_event({
2178 let position_map = position_map.clone();
2179 move |editor, event: &ScrollWheelEvent, phase, cx| {
2180 if phase != DispatchPhase::Bubble {
2181 return;
2182 }
2183
2184 if Self::scroll(editor, event, &position_map, bounds, cx) {
2185 cx.stop_propagation();
2186 }
2187 }
2188 });
2189 cx.on_mouse_event({
2190 let position_map = position_map.clone();
2191 move |editor, event: &MouseDownEvent, phase, cx| {
2192 if phase != DispatchPhase::Bubble {
2193 return;
2194 }
2195
2196 if Self::mouse_down(editor, event, &position_map, text_bounds, gutter_bounds, cx) {
2197 cx.stop_propagation()
2198 }
2199 }
2200 });
2201 cx.on_mouse_event({
2202 let position_map = position_map.clone();
2203 move |editor, event: &MouseUpEvent, phase, cx| {
2204 if phase != DispatchPhase::Bubble {
2205 return;
2206 }
2207
2208 if Self::mouse_up(editor, event, &position_map, text_bounds, cx) {
2209 cx.stop_propagation()
2210 }
2211 }
2212 });
2213 // todo!()
2214 // on_down(MouseButton::Right, {
2215 // let position_map = position_map.clone();
2216 // move |event, editor, cx| {
2217 // if !Self::mouse_right_down(
2218 // editor,
2219 // event.position,
2220 // position_map.as_ref(),
2221 // text_bounds,
2222 // cx,
2223 // ) {
2224 // cx.propagate_event();
2225 // }
2226 // }
2227 // });
2228 cx.on_mouse_event({
2229 let position_map = position_map.clone();
2230 move |editor, event: &MouseMoveEvent, phase, cx| {
2231 if phase != DispatchPhase::Bubble {
2232 return;
2233 }
2234
2235 if Self::mouse_moved(editor, event, &position_map, text_bounds, gutter_bounds, cx) {
2236 cx.stop_propagation()
2237 }
2238 }
2239 });
2240 }
2241}
2242
2243#[derive(Debug)]
2244pub struct LineWithInvisibles {
2245 pub line: Line,
2246 invisibles: Vec<Invisible>,
2247}
2248
2249impl LineWithInvisibles {
2250 fn from_chunks<'a>(
2251 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
2252 text_style: &TextStyle,
2253 max_line_len: usize,
2254 max_line_count: usize,
2255 line_number_layouts: &[Option<Line>],
2256 editor_mode: EditorMode,
2257 cx: &WindowContext,
2258 ) -> Vec<Self> {
2259 let mut layouts = Vec::with_capacity(max_line_count);
2260 let mut line = String::new();
2261 let mut invisibles = Vec::new();
2262 let mut styles = Vec::new();
2263 let mut non_whitespace_added = false;
2264 let mut row = 0;
2265 let mut line_exceeded_max_len = false;
2266 let font_size = text_style.font_size.to_pixels(cx.rem_size());
2267
2268 for highlighted_chunk in chunks.chain([HighlightedChunk {
2269 chunk: "\n",
2270 style: None,
2271 is_tab: false,
2272 }]) {
2273 for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
2274 if ix > 0 {
2275 let layout = cx
2276 .text_system()
2277 .layout_text(&line, font_size, &styles, None);
2278 layouts.push(Self {
2279 line: layout.unwrap().pop().unwrap(),
2280 invisibles: invisibles.drain(..).collect(),
2281 });
2282
2283 line.clear();
2284 styles.clear();
2285 row += 1;
2286 line_exceeded_max_len = false;
2287 non_whitespace_added = false;
2288 if row == max_line_count {
2289 return layouts;
2290 }
2291 }
2292
2293 if !line_chunk.is_empty() && !line_exceeded_max_len {
2294 let text_style = if let Some(style) = highlighted_chunk.style {
2295 text_style
2296 .clone()
2297 .highlight(style)
2298 .map(Cow::Owned)
2299 .unwrap_or_else(|_| Cow::Borrowed(text_style))
2300 } else {
2301 Cow::Borrowed(text_style)
2302 };
2303
2304 if line.len() + line_chunk.len() > max_line_len {
2305 let mut chunk_len = max_line_len - line.len();
2306 while !line_chunk.is_char_boundary(chunk_len) {
2307 chunk_len -= 1;
2308 }
2309 line_chunk = &line_chunk[..chunk_len];
2310 line_exceeded_max_len = true;
2311 }
2312
2313 styles.push(TextRun {
2314 len: line_chunk.len(),
2315 font: text_style.font(),
2316 color: text_style.color,
2317 underline: text_style.underline,
2318 });
2319
2320 if editor_mode == EditorMode::Full {
2321 // Line wrap pads its contents with fake whitespaces,
2322 // avoid printing them
2323 let inside_wrapped_string = line_number_layouts
2324 .get(row)
2325 .and_then(|layout| layout.as_ref())
2326 .is_none();
2327 if highlighted_chunk.is_tab {
2328 if non_whitespace_added || !inside_wrapped_string {
2329 invisibles.push(Invisible::Tab {
2330 line_start_offset: line.len(),
2331 });
2332 }
2333 } else {
2334 invisibles.extend(
2335 line_chunk
2336 .chars()
2337 .enumerate()
2338 .filter(|(_, line_char)| {
2339 let is_whitespace = line_char.is_whitespace();
2340 non_whitespace_added |= !is_whitespace;
2341 is_whitespace
2342 && (non_whitespace_added || !inside_wrapped_string)
2343 })
2344 .map(|(whitespace_index, _)| Invisible::Whitespace {
2345 line_offset: line.len() + whitespace_index,
2346 }),
2347 )
2348 }
2349 }
2350
2351 line.push_str(line_chunk);
2352 }
2353 }
2354 }
2355
2356 layouts
2357 }
2358
2359 fn draw(
2360 &self,
2361 layout: &LayoutState,
2362 row: u32,
2363 scroll_top: Pixels,
2364 content_origin: gpui::Point<Pixels>,
2365 scroll_left: Pixels,
2366 whitespace_setting: ShowWhitespaceSetting,
2367 selection_ranges: &[Range<DisplayPoint>],
2368 cx: &mut ViewContext<Editor>,
2369 ) {
2370 let line_height = layout.position_map.line_height;
2371 let line_y = line_height * row as f32 - scroll_top;
2372
2373 self.line.paint(
2374 content_origin + gpui::point(-scroll_left, line_y),
2375 line_height,
2376 cx,
2377 );
2378
2379 self.draw_invisibles(
2380 &selection_ranges,
2381 layout,
2382 content_origin,
2383 scroll_left,
2384 line_y,
2385 row,
2386 line_height,
2387 whitespace_setting,
2388 cx,
2389 );
2390 }
2391
2392 fn draw_invisibles(
2393 &self,
2394 selection_ranges: &[Range<DisplayPoint>],
2395 layout: &LayoutState,
2396 content_origin: gpui::Point<Pixels>,
2397 scroll_left: Pixels,
2398 line_y: Pixels,
2399 row: u32,
2400 line_height: Pixels,
2401 whitespace_setting: ShowWhitespaceSetting,
2402 cx: &mut ViewContext<Editor>,
2403 ) {
2404 let allowed_invisibles_regions = match whitespace_setting {
2405 ShowWhitespaceSetting::None => return,
2406 ShowWhitespaceSetting::Selection => Some(selection_ranges),
2407 ShowWhitespaceSetting::All => None,
2408 };
2409
2410 for invisible in &self.invisibles {
2411 let (&token_offset, invisible_symbol) = match invisible {
2412 Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
2413 Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
2414 };
2415
2416 let x_offset = self.line.x_for_index(token_offset);
2417 let invisible_offset =
2418 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
2419 let origin =
2420 content_origin + gpui::point(-scroll_left + x_offset + invisible_offset, line_y);
2421
2422 if let Some(allowed_regions) = allowed_invisibles_regions {
2423 let invisible_point = DisplayPoint::new(row, token_offset as u32);
2424 if !allowed_regions
2425 .iter()
2426 .any(|region| region.start <= invisible_point && invisible_point < region.end)
2427 {
2428 continue;
2429 }
2430 }
2431 invisible_symbol.paint(origin, line_height, cx);
2432 }
2433 }
2434}
2435
2436#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2437enum Invisible {
2438 Tab { line_start_offset: usize },
2439 Whitespace { line_offset: usize },
2440}
2441
2442impl Element<Editor> for EditorElement {
2443 type ElementState = ();
2444
2445 fn id(&self) -> Option<gpui::ElementId> {
2446 None
2447 }
2448
2449 fn initialize(
2450 &mut self,
2451 editor: &mut Editor,
2452 element_state: Option<Self::ElementState>,
2453 cx: &mut gpui::ViewContext<Editor>,
2454 ) -> Self::ElementState {
2455 editor.style = Some(self.style.clone()); // Long-term, we'd like to eliminate this.
2456
2457 let dispatch_context = editor.dispatch_context(cx);
2458 cx.with_element_id(cx.view().entity_id(), |global_id, cx| {
2459 cx.with_key_dispatch_context(dispatch_context, |cx| {
2460 cx.with_key_listeners(build_key_listeners(global_id), |cx| {
2461 cx.with_focus(editor.focus_handle.clone(), |_| {})
2462 });
2463 })
2464 });
2465 }
2466
2467 fn layout(
2468 &mut self,
2469 editor: &mut Editor,
2470 element_state: &mut Self::ElementState,
2471 cx: &mut gpui::ViewContext<Editor>,
2472 ) -> gpui::LayoutId {
2473 let rem_size = cx.rem_size();
2474 let mut style = Style::default();
2475 style.size.width = relative(1.).into();
2476 style.size.height = match editor.mode {
2477 EditorMode::SingleLine => self.style.text.line_height_in_pixels(cx.rem_size()).into(),
2478 EditorMode::AutoHeight { .. } => todo!(),
2479 EditorMode::Full => relative(1.).into(),
2480 };
2481 cx.request_layout(&style, None)
2482 }
2483
2484 fn paint(
2485 &mut self,
2486 bounds: Bounds<gpui::Pixels>,
2487 editor: &mut Editor,
2488 element_state: &mut Self::ElementState,
2489 cx: &mut gpui::ViewContext<Editor>,
2490 ) {
2491 let mut layout = self.compute_layout(editor, cx, bounds);
2492 let gutter_bounds = Bounds {
2493 origin: bounds.origin,
2494 size: layout.gutter_size,
2495 };
2496 let text_bounds = Bounds {
2497 origin: gutter_bounds.upper_right(),
2498 size: layout.text_size,
2499 };
2500
2501 // We call with_z_index to establish a new stacking context.
2502 cx.with_z_index(0, |cx| {
2503 cx.with_content_mask(ContentMask { bounds }, |cx| {
2504 self.paint_mouse_listeners(
2505 bounds,
2506 gutter_bounds,
2507 text_bounds,
2508 &layout.position_map,
2509 cx,
2510 );
2511 self.paint_background(gutter_bounds, text_bounds, &layout, cx);
2512 if layout.gutter_size.width > Pixels::ZERO {
2513 self.paint_gutter(gutter_bounds, &mut layout, editor, cx);
2514 }
2515 self.paint_text(text_bounds, &mut layout, editor, cx);
2516 let input_handler = ElementInputHandler::new(bounds, cx);
2517 cx.handle_input(&editor.focus_handle, input_handler);
2518 });
2519 });
2520 }
2521}
2522
2523// impl EditorElement {
2524// type LayoutState = LayoutState;
2525// type PaintState = ();
2526
2527// fn layout(
2528// &mut self,
2529// constraint: SizeConstraint,
2530// editor: &mut Editor,
2531// cx: &mut ViewContext<Editor>,
2532// ) -> (gpui::Point<Pixels>, Self::LayoutState) {
2533// let mut size = constraint.max;
2534// if size.x.is_infinite() {
2535// unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
2536// }
2537
2538// let snapshot = editor.snapshot(cx);
2539// let style = self.style.clone();
2540
2541// let line_height = (style.text.font_size * style.line_height_scalar).round();
2542
2543// let gutter_padding;
2544// let gutter_width;
2545// let gutter_margin;
2546// if snapshot.show_gutter {
2547// let em_width = style.text.em_width(cx.font_cache());
2548// gutter_padding = (em_width * style.gutter_padding_factor).round();
2549// gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
2550// gutter_margin = -style.text.descent(cx.font_cache());
2551// } else {
2552// gutter_padding = 0.0;
2553// gutter_width = 0.0;
2554// gutter_margin = 0.0;
2555// };
2556
2557// let text_width = size.x - gutter_width;
2558// let em_width = style.text.em_width(cx.font_cache());
2559// let em_advance = style.text.em_advance(cx.font_cache());
2560// let overscroll = point(em_width, 0.);
2561// let snapshot = {
2562// editor.set_visible_line_count(size.y / line_height, cx);
2563
2564// let editor_width = text_width - gutter_margin - overscroll.x - em_width;
2565// let wrap_width = match editor.soft_wrap_mode(cx) {
2566// SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
2567// SoftWrap::EditorWidth => editor_width,
2568// SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
2569// };
2570
2571// if editor.set_wrap_width(Some(wrap_width), cx) {
2572// editor.snapshot(cx)
2573// } else {
2574// snapshot
2575// }
2576// };
2577
2578// let wrap_guides = editor
2579// .wrap_guides(cx)
2580// .iter()
2581// .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
2582// .collect();
2583
2584// let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
2585// if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
2586// size.set_y(
2587// scroll_height
2588// .min(constraint.max_along(Axis::Vertical))
2589// .max(constraint.min_along(Axis::Vertical))
2590// .max(line_height)
2591// .min(line_height * max_lines as f32),
2592// )
2593// } else if let EditorMode::SingleLine = snapshot.mode {
2594// size.set_y(line_height.max(constraint.min_along(Axis::Vertical)))
2595// } else if size.y.is_infinite() {
2596// size.set_y(scroll_height);
2597// }
2598// let gutter_size = point(gutter_width, size.y);
2599// let text_size = point(text_width, size.y);
2600
2601// let autoscroll_horizontally = editor.autoscroll_vertically(size.y, line_height, cx);
2602// let mut snapshot = editor.snapshot(cx);
2603
2604// let scroll_position = snapshot.scroll_position();
2605// // The scroll position is a fractional point, the whole number of which represents
2606// // the top of the window in terms of display rows.
2607// let start_row = scroll_position.y as u32;
2608// let height_in_lines = size.y / line_height;
2609// let max_row = snapshot.max_point().row();
2610
2611// // Add 1 to ensure selections bleed off screen
2612// let end_row = 1 + cmp::min(
2613// (scroll_position.y + height_in_lines).ceil() as u32,
2614// max_row,
2615// );
2616
2617// let start_anchor = if start_row == 0 {
2618// Anchor::min()
2619// } else {
2620// snapshot
2621// .buffer_snapshot
2622// .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
2623// };
2624// let end_anchor = if end_row > max_row {
2625// Anchor::max
2626// } else {
2627// snapshot
2628// .buffer_snapshot
2629// .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
2630// };
2631
2632// let mut selections: Vec<(SelectionStyle, Vec<SelectionLayout>)> = Vec::new();
2633// let mut active_rows = BTreeMap::new();
2634// let mut fold_ranges = Vec::new();
2635// let is_singleton = editor.is_singleton(cx);
2636
2637// let highlighted_rows = editor.highlighted_rows();
2638// let theme = theme::current(cx);
2639// let highlighted_ranges = editor.background_highlights_in_range(
2640// start_anchor..end_anchor,
2641// &snapshot.display_snapshot,
2642// theme.as_ref(),
2643// );
2644
2645// fold_ranges.extend(
2646// snapshot
2647// .folds_in_range(start_anchor..end_anchor)
2648// .map(|anchor| {
2649// let start = anchor.start.to_point(&snapshot.buffer_snapshot);
2650// (
2651// start.row,
2652// start.to_display_point(&snapshot.display_snapshot)
2653// ..anchor.end.to_display_point(&snapshot),
2654// )
2655// }),
2656// );
2657
2658// let mut newest_selection_head = None;
2659
2660// if editor.show_local_selections {
2661// let mut local_selections: Vec<Selection<Point>> = editor
2662// .selections
2663// .disjoint_in_range(start_anchor..end_anchor, cx);
2664// local_selections.extend(editor.selections.pending(cx));
2665// let mut layouts = Vec::new();
2666// let newest = editor.selections.newest(cx);
2667// for selection in local_selections.drain(..) {
2668// let is_empty = selection.start == selection.end;
2669// let is_newest = selection == newest;
2670
2671// let layout = SelectionLayout::new(
2672// selection,
2673// editor.selections.line_mode,
2674// editor.cursor_shape,
2675// &snapshot.display_snapshot,
2676// is_newest,
2677// true,
2678// );
2679// if is_newest {
2680// newest_selection_head = Some(layout.head);
2681// }
2682
2683// for row in cmp::max(layout.active_rows.start, start_row)
2684// ..=cmp::min(layout.active_rows.end, end_row)
2685// {
2686// let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
2687// *contains_non_empty_selection |= !is_empty;
2688// }
2689// layouts.push(layout);
2690// }
2691
2692// selections.push((style.selection, layouts));
2693// }
2694
2695// if let Some(collaboration_hub) = &editor.collaboration_hub {
2696// // When following someone, render the local selections in their color.
2697// if let Some(leader_id) = editor.leader_peer_id {
2698// if let Some(collaborator) = collaboration_hub.collaborators(cx).get(&leader_id) {
2699// if let Some(participant_index) = collaboration_hub
2700// .user_participant_indices(cx)
2701// .get(&collaborator.user_id)
2702// {
2703// if let Some((local_selection_style, _)) = selections.first_mut() {
2704// *local_selection_style =
2705// style.selection_style_for_room_participant(participant_index.0);
2706// }
2707// }
2708// }
2709// }
2710
2711// let mut remote_selections = HashMap::default();
2712// for selection in snapshot.remote_selections_in_range(
2713// &(start_anchor..end_anchor),
2714// collaboration_hub.as_ref(),
2715// cx,
2716// ) {
2717// let selection_style = if let Some(participant_index) = selection.participant_index {
2718// style.selection_style_for_room_participant(participant_index.0)
2719// } else {
2720// style.absent_selection
2721// };
2722
2723// // Don't re-render the leader's selections, since the local selections
2724// // match theirs.
2725// if Some(selection.peer_id) == editor.leader_peer_id {
2726// continue;
2727// }
2728
2729// remote_selections
2730// .entry(selection.replica_id)
2731// .or_insert((selection_style, Vec::new()))
2732// .1
2733// .push(SelectionLayout::new(
2734// selection.selection,
2735// selection.line_mode,
2736// selection.cursor_shape,
2737// &snapshot.display_snapshot,
2738// false,
2739// false,
2740// ));
2741// }
2742
2743// selections.extend(remote_selections.into_values());
2744// }
2745
2746// let scrollbar_settings = &settings::get::<EditorSettings>(cx).scrollbar;
2747// let show_scrollbars = match scrollbar_settings.show {
2748// ShowScrollbar::Auto => {
2749// // Git
2750// (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_git_diffs())
2751// ||
2752// // Selections
2753// (is_singleton && scrollbar_settings.selections && !highlighted_ranges.is_empty)
2754// // Scrollmanager
2755// || editor.scroll_manager.scrollbars_visible()
2756// }
2757// ShowScrollbar::System => editor.scroll_manager.scrollbars_visible(),
2758// ShowScrollbar::Always => true,
2759// ShowScrollbar::Never => false,
2760// };
2761
2762// let fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)> = fold_ranges
2763// .into_iter()
2764// .map(|(id, fold)| {
2765// let color = self
2766// .style
2767// .folds
2768// .ellipses
2769// .background
2770// .style_for(&mut cx.mouse_state::<FoldMarkers>(id as usize))
2771// .color;
2772
2773// (id, fold, color)
2774// })
2775// .collect();
2776
2777// let head_for_relative = newest_selection_head.unwrap_or_else(|| {
2778// let newest = editor.selections.newest::<Point>(cx);
2779// SelectionLayout::new(
2780// newest,
2781// editor.selections.line_mode,
2782// editor.cursor_shape,
2783// &snapshot.display_snapshot,
2784// true,
2785// true,
2786// )
2787// .head
2788// });
2789
2790// let (line_number_layouts, fold_statuses) = self.layout_line_numbers(
2791// start_row..end_row,
2792// &active_rows,
2793// head_for_relative,
2794// is_singleton,
2795// &snapshot,
2796// cx,
2797// );
2798
2799// let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
2800
2801// let scrollbar_row_range = scroll_position.y..(scroll_position.y + height_in_lines);
2802
2803// let mut max_visible_line_width = 0.0;
2804// let line_layouts =
2805// self.layout_lines(start_row..end_row, &line_number_layouts, &snapshot, cx);
2806// for line_with_invisibles in &line_layouts {
2807// if line_with_invisibles.line.width() > max_visible_line_width {
2808// max_visible_line_width = line_with_invisibles.line.width();
2809// }
2810// }
2811
2812// let style = self.style.clone();
2813// let longest_line_width = layout_line(
2814// snapshot.longest_row(),
2815// &snapshot,
2816// &style,
2817// cx.text_layout_cache(),
2818// )
2819// .width();
2820// let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x;
2821// let em_width = style.text.em_width(cx.font_cache());
2822// let (scroll_width, blocks) = self.layout_blocks(
2823// start_row..end_row,
2824// &snapshot,
2825// size.x,
2826// scroll_width,
2827// gutter_padding,
2828// gutter_width,
2829// em_width,
2830// gutter_width + gutter_margin,
2831// line_height,
2832// &style,
2833// &line_layouts,
2834// editor,
2835// cx,
2836// );
2837
2838// let scroll_max = point(
2839// ((scroll_width - text_size.x) / em_width).max(0.0),
2840// max_row as f32,
2841// );
2842
2843// let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
2844
2845// let autoscrolled = if autoscroll_horizontally {
2846// editor.autoscroll_horizontally(
2847// start_row,
2848// text_size.x,
2849// scroll_width,
2850// em_width,
2851// &line_layouts,
2852// cx,
2853// )
2854// } else {
2855// false
2856// };
2857
2858// if clamped || autoscrolled {
2859// snapshot = editor.snapshot(cx);
2860// }
2861
2862// let style = editor.style(cx);
2863
2864// let mut context_menu = None;
2865// let mut code_actions_indicator = None;
2866// if let Some(newest_selection_head) = newest_selection_head {
2867// if (start_row..end_row).contains(&newest_selection_head.row()) {
2868// if editor.context_menu_visible() {
2869// context_menu =
2870// editor.render_context_menu(newest_selection_head, style.clone(), cx);
2871// }
2872
2873// let active = matches!(
2874// editor.context_menu.read().as_ref(),
2875// Some(crate::ContextMenu::CodeActions(_))
2876// );
2877
2878// code_actions_indicator = editor
2879// .render_code_actions_indicator(&style, active, cx)
2880// .map(|indicator| (newest_selection_head.row(), indicator));
2881// }
2882// }
2883
2884// let visible_rows = start_row..start_row + line_layouts.len() as u32;
2885// let mut hover = editor.hover_state.render(
2886// &snapshot,
2887// &style,
2888// visible_rows,
2889// editor.workspace.as_ref().map(|(w, _)| w.clone()),
2890// cx,
2891// );
2892// let mode = editor.mode;
2893
2894// let mut fold_indicators = editor.render_fold_indicators(
2895// fold_statuses,
2896// &style,
2897// editor.gutter_hovered,
2898// line_height,
2899// gutter_margin,
2900// cx,
2901// );
2902
2903// if let Some((_, context_menu)) = context_menu.as_mut() {
2904// context_menu.layout(
2905// SizeConstraint {
2906// min: gpui::Point::<Pixels>::zero(),
2907// max: point(
2908// cx.window_size().x * 0.7,
2909// (12. * line_height).min((size.y - line_height) / 2.),
2910// ),
2911// },
2912// editor,
2913// cx,
2914// );
2915// }
2916
2917// if let Some((_, indicator)) = code_actions_indicator.as_mut() {
2918// indicator.layout(
2919// SizeConstraint::strict_along(
2920// Axis::Vertical,
2921// line_height * style.code_actions.vertical_scale,
2922// ),
2923// editor,
2924// cx,
2925// );
2926// }
2927
2928// for fold_indicator in fold_indicators.iter_mut() {
2929// if let Some(indicator) = fold_indicator.as_mut() {
2930// indicator.layout(
2931// SizeConstraint::strict_along(
2932// Axis::Vertical,
2933// line_height * style.code_actions.vertical_scale,
2934// ),
2935// editor,
2936// cx,
2937// );
2938// }
2939// }
2940
2941// if let Some((_, hover_popovers)) = hover.as_mut() {
2942// for hover_popover in hover_popovers.iter_mut() {
2943// hover_popover.layout(
2944// SizeConstraint {
2945// min: gpui::Point::<Pixels>::zero(),
2946// max: point(
2947// (120. * em_width) // Default size
2948// .min(size.x / 2.) // Shrink to half of the editor width
2949// .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2950// (16. * line_height) // Default size
2951// .min(size.y / 2.) // Shrink to half of the editor height
2952// .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2953// ),
2954// },
2955// editor,
2956// cx,
2957// );
2958// }
2959// }
2960
2961// let invisible_symbol_font_size = self.style.text.font_size / 2.0;
2962// let invisible_symbol_style = RunStyle {
2963// color: self.style.whitespace,
2964// font_id: self.style.text.font_id,
2965// underline: Default::default(),
2966// };
2967
2968// (
2969// size,
2970// LayoutState {
2971// mode,
2972// position_map: Arc::new(PositionMap {
2973// size,
2974// scroll_max,
2975// line_layouts,
2976// line_height,
2977// em_width,
2978// em_advance,
2979// snapshot,
2980// }),
2981// visible_display_row_range: start_row..end_row,
2982// wrap_guides,
2983// gutter_size,
2984// gutter_padding,
2985// text_size,
2986// scrollbar_row_range,
2987// show_scrollbars,
2988// is_singleton,
2989// max_row,
2990// gutter_margin,
2991// active_rows,
2992// highlighted_rows,
2993// highlighted_ranges,
2994// fold_ranges,
2995// line_number_layouts,
2996// display_hunks,
2997// blocks,
2998// selections,
2999// context_menu,
3000// code_actions_indicator,
3001// fold_indicators,
3002// tab_invisible: cx.text_layout_cache().layout_str(
3003// "→",
3004// invisible_symbol_font_size,
3005// &[("→".len(), invisible_symbol_style)],
3006// ),
3007// space_invisible: cx.text_layout_cache().layout_str(
3008// "•",
3009// invisible_symbol_font_size,
3010// &[("•".len(), invisible_symbol_style)],
3011// ),
3012// hover_popovers: hover,
3013// },
3014// )
3015// }
3016
3017// fn paint(
3018// &mut self,
3019// bounds: Bounds<Pixels>,
3020// visible_bounds: Bounds<Pixels>,
3021// layout: &mut Self::LayoutState,
3022// editor: &mut Editor,
3023// cx: &mut ViewContext<Editor>,
3024// ) -> Self::PaintState {
3025// let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
3026// cx.scene().push_layer(Some(visible_bounds));
3027
3028// let gutter_bounds = Bounds::<Pixels>::new(bounds.origin, layout.gutter_size);
3029// let text_bounds = Bounds::<Pixels>::new(
3030// bounds.origin + point(layout.gutter_size.x, 0.0),
3031// layout.text_size,
3032// );
3033
3034// Self::attach_mouse_handlers(
3035// &layout.position_map,
3036// layout.hover_popovers.is_some(),
3037// visible_bounds,
3038// text_bounds,
3039// gutter_bounds,
3040// bounds,
3041// cx,
3042// );
3043
3044// self.paint_background(gutter_bounds, text_bounds, layout, cx);
3045// if layout.gutter_size.x > 0. {
3046// self.paint_gutter(gutter_bounds, visible_bounds, layout, editor, cx);
3047// }
3048// self.paint_text(text_bounds, visible_bounds, layout, editor, cx);
3049
3050// cx.scene().push_layer(Some(bounds));
3051// if !layout.blocks.is_empty {
3052// self.paint_blocks(bounds, visible_bounds, layout, editor, cx);
3053// }
3054// self.paint_scrollbar(bounds, layout, &editor, cx);
3055// cx.scene().pop_layer();
3056// cx.scene().pop_layer();
3057// }
3058
3059// fn rect_for_text_range(
3060// &self,
3061// range_utf16: Range<usize>,
3062// bounds: Bounds<Pixels>,
3063// _: Bounds<Pixels>,
3064// layout: &Self::LayoutState,
3065// _: &Self::PaintState,
3066// _: &Editor,
3067// _: &ViewContext<Editor>,
3068// ) -> Option<Bounds<Pixels>> {
3069// let text_bounds = Bounds::<Pixels>::new(
3070// bounds.origin + point(layout.gutter_size.x, 0.0),
3071// layout.text_size,
3072// );
3073// let content_origin = text_bounds.origin + point(layout.gutter_margin, 0.);
3074// let scroll_position = layout.position_map.snapshot.scroll_position();
3075// let start_row = scroll_position.y as u32;
3076// let scroll_top = scroll_position.y * layout.position_map.line_height;
3077// let scroll_left = scroll_position.x * layout.position_map.em_width;
3078
3079// let range_start = OffsetUtf16(range_utf16.start)
3080// .to_display_point(&layout.position_map.snapshot.display_snapshot);
3081// if range_start.row() < start_row {
3082// return None;
3083// }
3084
3085// let line = &layout
3086// .position_map
3087// .line_layouts
3088// .get((range_start.row() - start_row) as usize)?
3089// .line;
3090// let range_start_x = line.x_for_index(range_start.column() as usize);
3091// let range_start_y = range_start.row() as f32 * layout.position_map.line_height;
3092// Some(Bounds::<Pixels>::new(
3093// content_origin
3094// + point(
3095// range_start_x,
3096// range_start_y + layout.position_map.line_height,
3097// )
3098// - point(scroll_left, scroll_top),
3099// point(
3100// layout.position_map.em_width,
3101// layout.position_map.line_height,
3102// ),
3103// ))
3104// }
3105
3106// fn debug(
3107// &self,
3108// bounds: Bounds<Pixels>,
3109// _: &Self::LayoutState,
3110// _: &Self::PaintState,
3111// _: &Editor,
3112// _: &ViewContext<Editor>,
3113// ) -> json::Value {
3114// json!({
3115// "type": "BufferElement",
3116// "bounds": bounds.to_json()
3117// })
3118// }
3119// }
3120
3121type BufferRow = u32;
3122
3123pub struct LayoutState {
3124 position_map: Arc<PositionMap>,
3125 gutter_size: Size<Pixels>,
3126 gutter_padding: Pixels,
3127 gutter_margin: Pixels,
3128 text_size: gpui::Size<Pixels>,
3129 mode: EditorMode,
3130 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
3131 visible_display_row_range: Range<u32>,
3132 active_rows: BTreeMap<u32, bool>,
3133 highlighted_rows: Option<Range<u32>>,
3134 line_number_layouts: Vec<Option<gpui::Line>>,
3135 display_hunks: Vec<DisplayDiffHunk>,
3136 // blocks: Vec<BlockLayout>,
3137 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
3138 fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Hsla)>,
3139 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
3140 scrollbar_row_range: Range<f32>,
3141 show_scrollbars: bool,
3142 is_singleton: bool,
3143 max_row: u32,
3144 context_menu: Option<(DisplayPoint, AnyElement<Editor>)>,
3145 code_actions_indicator: Option<CodeActionsIndicator>,
3146 // hover_popovers: Option<(DisplayPoint, Vec<AnyElement<Editor>>)>,
3147 // fold_indicators: Vec<Option<AnyElement<Editor>>>,
3148 tab_invisible: Line,
3149 space_invisible: Line,
3150}
3151
3152struct CodeActionsIndicator {
3153 row: u32,
3154 element: AnyElement<Editor>,
3155}
3156
3157struct PositionMap {
3158 size: Size<Pixels>,
3159 line_height: Pixels,
3160 scroll_max: gpui::Point<f32>,
3161 em_width: Pixels,
3162 em_advance: Pixels,
3163 line_layouts: Vec<LineWithInvisibles>,
3164 snapshot: EditorSnapshot,
3165}
3166
3167#[derive(Debug, Copy, Clone)]
3168pub struct PointForPosition {
3169 pub previous_valid: DisplayPoint,
3170 pub next_valid: DisplayPoint,
3171 pub exact_unclipped: DisplayPoint,
3172 pub column_overshoot_after_line_end: u32,
3173}
3174
3175impl PointForPosition {
3176 #[cfg(test)]
3177 pub fn valid(valid: DisplayPoint) -> Self {
3178 Self {
3179 previous_valid: valid,
3180 next_valid: valid,
3181 exact_unclipped: valid,
3182 column_overshoot_after_line_end: 0,
3183 }
3184 }
3185
3186 pub fn as_valid(&self) -> Option<DisplayPoint> {
3187 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
3188 Some(self.previous_valid)
3189 } else {
3190 None
3191 }
3192 }
3193}
3194
3195impl PositionMap {
3196 fn point_for_position(
3197 &self,
3198 text_bounds: Bounds<Pixels>,
3199 position: gpui::Point<Pixels>,
3200 ) -> PointForPosition {
3201 let scroll_position = self.snapshot.scroll_position();
3202 let position = position - text_bounds.origin;
3203 let y = position.y.max(px(0.)).min(self.size.width);
3204 let x = position.x + (scroll_position.x * self.em_width);
3205 let row = (f32::from(y / self.line_height) + scroll_position.y) as u32;
3206
3207 let (column, x_overshoot_after_line_end) = if let Some(line) = self
3208 .line_layouts
3209 .get(row as usize - scroll_position.y as usize)
3210 .map(|&LineWithInvisibles { ref line, .. }| line)
3211 {
3212 if let Some(ix) = line.index_for_x(x) {
3213 (ix as u32, px(0.))
3214 } else {
3215 (line.len as u32, px(0.).max(x - line.width))
3216 }
3217 } else {
3218 (0, x)
3219 };
3220
3221 let mut exact_unclipped = DisplayPoint::new(row, column);
3222 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
3223 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
3224
3225 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
3226 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
3227 PointForPosition {
3228 previous_valid,
3229 next_valid,
3230 exact_unclipped,
3231 column_overshoot_after_line_end,
3232 }
3233 }
3234}
3235
3236struct BlockLayout {
3237 row: u32,
3238 element: AnyElement<Editor>,
3239 style: BlockStyle,
3240}
3241
3242fn layout_line(
3243 row: u32,
3244 snapshot: &EditorSnapshot,
3245 style: &EditorStyle,
3246 cx: &WindowContext,
3247) -> Result<Line> {
3248 let mut line = snapshot.line(row);
3249
3250 if line.len() > MAX_LINE_LEN {
3251 let mut len = MAX_LINE_LEN;
3252 while !line.is_char_boundary(len) {
3253 len -= 1;
3254 }
3255
3256 line.truncate(len);
3257 }
3258
3259 Ok(cx
3260 .text_system()
3261 .layout_text(
3262 &line,
3263 style.text.font_size.to_pixels(cx.rem_size()),
3264 &[TextRun {
3265 len: snapshot.line_len(row) as usize,
3266 font: style.text.font(),
3267 color: Hsla::default(),
3268 underline: None,
3269 }],
3270 None,
3271 )?
3272 .pop()
3273 .unwrap())
3274}
3275
3276#[derive(Debug)]
3277pub struct Cursor {
3278 origin: gpui::Point<Pixels>,
3279 block_width: Pixels,
3280 line_height: Pixels,
3281 color: Hsla,
3282 shape: CursorShape,
3283 block_text: Option<Line>,
3284}
3285
3286impl Cursor {
3287 pub fn new(
3288 origin: gpui::Point<Pixels>,
3289 block_width: Pixels,
3290 line_height: Pixels,
3291 color: Hsla,
3292 shape: CursorShape,
3293 block_text: Option<Line>,
3294 ) -> Cursor {
3295 Cursor {
3296 origin,
3297 block_width,
3298 line_height,
3299 color,
3300 shape,
3301 block_text,
3302 }
3303 }
3304
3305 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
3306 Bounds {
3307 origin: self.origin + origin,
3308 size: size(self.block_width, self.line_height),
3309 }
3310 }
3311
3312 pub fn paint(&self, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
3313 let bounds = match self.shape {
3314 CursorShape::Bar => Bounds {
3315 origin: self.origin + origin,
3316 size: size(px(2.0), self.line_height),
3317 },
3318 CursorShape::Block | CursorShape::Hollow => Bounds {
3319 origin: self.origin + origin,
3320 size: size(self.block_width, self.line_height),
3321 },
3322 CursorShape::Underscore => Bounds {
3323 origin: self.origin
3324 + origin
3325 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
3326 size: size(self.block_width, px(2.0)),
3327 },
3328 };
3329
3330 //Draw background or border quad
3331 if matches!(self.shape, CursorShape::Hollow) {
3332 cx.paint_quad(
3333 bounds,
3334 Corners::default(),
3335 transparent_black(),
3336 Edges::all(px(1.)),
3337 self.color,
3338 );
3339 } else {
3340 cx.paint_quad(
3341 bounds,
3342 Corners::default(),
3343 self.color,
3344 Edges::default(),
3345 transparent_black(),
3346 );
3347 }
3348
3349 if let Some(block_text) = &self.block_text {
3350 block_text.paint(self.origin + origin, self.line_height, cx);
3351 }
3352 }
3353
3354 pub fn shape(&self) -> CursorShape {
3355 self.shape
3356 }
3357}
3358
3359#[derive(Debug)]
3360pub struct HighlightedRange {
3361 pub start_y: Pixels,
3362 pub line_height: Pixels,
3363 pub lines: Vec<HighlightedRangeLine>,
3364 pub color: Hsla,
3365 pub corner_radius: Pixels,
3366}
3367
3368#[derive(Debug)]
3369pub struct HighlightedRangeLine {
3370 pub start_x: Pixels,
3371 pub end_x: Pixels,
3372}
3373
3374impl HighlightedRange {
3375 pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut WindowContext) {
3376 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
3377 self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
3378 self.paint_lines(
3379 self.start_y + self.line_height,
3380 &self.lines[1..],
3381 bounds,
3382 cx,
3383 );
3384 } else {
3385 self.paint_lines(self.start_y, &self.lines, bounds, cx);
3386 }
3387 }
3388
3389 fn paint_lines(
3390 &self,
3391 start_y: Pixels,
3392 lines: &[HighlightedRangeLine],
3393 bounds: Bounds<Pixels>,
3394 cx: &mut WindowContext,
3395 ) {
3396 if lines.is_empty() {
3397 return;
3398 }
3399
3400 let first_line = lines.first().unwrap();
3401 let last_line = lines.last().unwrap();
3402
3403 let first_top_left = point(first_line.start_x, start_y);
3404 let first_top_right = point(first_line.end_x, start_y);
3405
3406 let curve_height = point(Pixels::ZERO, self.corner_radius);
3407 let curve_width = |start_x: Pixels, end_x: Pixels| {
3408 let max = (end_x - start_x) / 2.;
3409 let width = if max < self.corner_radius {
3410 max
3411 } else {
3412 self.corner_radius
3413 };
3414
3415 point(width, Pixels::ZERO)
3416 };
3417
3418 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
3419 let mut path = gpui::Path::new(first_top_right - top_curve_width);
3420 path.curve_to(first_top_right + curve_height, first_top_right);
3421
3422 let mut iter = lines.iter().enumerate().peekable();
3423 while let Some((ix, line)) = iter.next() {
3424 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
3425
3426 if let Some((_, next_line)) = iter.peek() {
3427 let next_top_right = point(next_line.end_x, bottom_right.y);
3428
3429 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
3430 Ordering::Equal => {
3431 path.line_to(bottom_right);
3432 }
3433 Ordering::Less => {
3434 let curve_width = curve_width(next_top_right.x, bottom_right.x);
3435 path.line_to(bottom_right - curve_height);
3436 if self.corner_radius > Pixels::ZERO {
3437 path.curve_to(bottom_right - curve_width, bottom_right);
3438 }
3439 path.line_to(next_top_right + curve_width);
3440 if self.corner_radius > Pixels::ZERO {
3441 path.curve_to(next_top_right + curve_height, next_top_right);
3442 }
3443 }
3444 Ordering::Greater => {
3445 let curve_width = curve_width(bottom_right.x, next_top_right.x);
3446 path.line_to(bottom_right - curve_height);
3447 if self.corner_radius > Pixels::ZERO {
3448 path.curve_to(bottom_right + curve_width, bottom_right);
3449 }
3450 path.line_to(next_top_right - curve_width);
3451 if self.corner_radius > Pixels::ZERO {
3452 path.curve_to(next_top_right + curve_height, next_top_right);
3453 }
3454 }
3455 }
3456 } else {
3457 let curve_width = curve_width(line.start_x, line.end_x);
3458 path.line_to(bottom_right - curve_height);
3459 if self.corner_radius > Pixels::ZERO {
3460 path.curve_to(bottom_right - curve_width, bottom_right);
3461 }
3462
3463 let bottom_left = point(line.start_x, bottom_right.y);
3464 path.line_to(bottom_left + curve_width);
3465 if self.corner_radius > Pixels::ZERO {
3466 path.curve_to(bottom_left - curve_height, bottom_left);
3467 }
3468 }
3469 }
3470
3471 if first_line.start_x > last_line.start_x {
3472 let curve_width = curve_width(last_line.start_x, first_line.start_x);
3473 let second_top_left = point(last_line.start_x, start_y + self.line_height);
3474 path.line_to(second_top_left + curve_height);
3475 if self.corner_radius > Pixels::ZERO {
3476 path.curve_to(second_top_left + curve_width, second_top_left);
3477 }
3478 let first_bottom_left = point(first_line.start_x, second_top_left.y);
3479 path.line_to(first_bottom_left - curve_width);
3480 if self.corner_radius > Pixels::ZERO {
3481 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
3482 }
3483 }
3484
3485 path.line_to(first_top_left + curve_height);
3486 if self.corner_radius > Pixels::ZERO {
3487 path.curve_to(first_top_left + top_curve_width, first_top_left);
3488 }
3489 path.line_to(first_top_right - top_curve_width);
3490
3491 cx.paint_path(path, self.color);
3492 }
3493}
3494
3495// fn range_to_bounds(
3496// range: &Range<DisplayPoint>,
3497// content_origin: gpui::Point<Pixels>,
3498// scroll_left: f32,
3499// scroll_top: f32,
3500// visible_row_range: &Range<u32>,
3501// line_end_overshoot: f32,
3502// position_map: &PositionMap,
3503// ) -> impl Iterator<Item = Bounds<Pixels>> {
3504// let mut bounds: SmallVec<[Bounds<Pixels>; 1]> = SmallVec::new();
3505
3506// if range.start == range.end {
3507// return bounds.into_iter();
3508// }
3509
3510// let start_row = visible_row_range.start;
3511// let end_row = visible_row_range.end;
3512
3513// let row_range = if range.end.column() == 0 {
3514// cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
3515// } else {
3516// cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
3517// };
3518
3519// let first_y =
3520// content_origin.y + row_range.start as f32 * position_map.line_height - scroll_top;
3521
3522// for (idx, row) in row_range.enumerate() {
3523// let line_layout = &position_map.line_layouts[(row - start_row) as usize].line;
3524
3525// let start_x = if row == range.start.row() {
3526// content_origin.x + line_layout.x_for_index(range.start.column() as usize)
3527// - scroll_left
3528// } else {
3529// content_origin.x - scroll_left
3530// };
3531
3532// let end_x = if row == range.end.row() {
3533// content_origin.x + line_layout.x_for_index(range.end.column() as usize) - scroll_left
3534// } else {
3535// content_origin.x + line_layout.width() + line_end_overshoot - scroll_left
3536// };
3537
3538// bounds.push(Bounds::<Pixels>::from_points(
3539// point(start_x, first_y + position_map.line_height * idx as f32),
3540// point(end_x, first_y + position_map.line_height * (idx + 1) as f32),
3541// ))
3542// }
3543
3544// bounds.into_iter()
3545// }
3546
3547pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
3548 (delta.pow(1.5) / 100.0).into()
3549}
3550
3551fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
3552 (delta.pow(1.2) / 300.0).into()
3553}
3554
3555// #[cfg(test)]
3556// mod tests {
3557// use super::*;
3558// use crate::{
3559// display_map::{BlockDisposition, BlockProperties},
3560// editor_tests::{init_test, update_test_language_settings},
3561// Editor, MultiBuffer,
3562// };
3563// use gpui::TestAppContext;
3564// use language::language_settings;
3565// use log::info;
3566// use std::{num::NonZeroU32, sync::Arc};
3567// use util::test::sample_text;
3568
3569// #[gpui::test]
3570// fn test_layout_line_numbers(cx: &mut TestAppContext) {
3571// init_test(cx, |_| {});
3572// let editor = cx
3573// .add_window(|cx| {
3574// let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
3575// Editor::new(EditorMode::Full, buffer, None, None, cx)
3576// })
3577// .root(cx);
3578// let element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3579
3580// let layouts = editor.update(cx, |editor, cx| {
3581// let snapshot = editor.snapshot(cx);
3582// element
3583// .layout_line_numbers(
3584// 0..6,
3585// &Default::default(),
3586// DisplayPoint::new(0, 0),
3587// false,
3588// &snapshot,
3589// cx,
3590// )
3591// .0
3592// });
3593// assert_eq!(layouts.len(), 6);
3594
3595// let relative_rows = editor.update(cx, |editor, cx| {
3596// let snapshot = editor.snapshot(cx);
3597// element.calculate_relative_line_numbers(&snapshot, &(0..6), Some(3))
3598// });
3599// assert_eq!(relative_rows[&0], 3);
3600// assert_eq!(relative_rows[&1], 2);
3601// assert_eq!(relative_rows[&2], 1);
3602// // current line has no relative number
3603// assert_eq!(relative_rows[&4], 1);
3604// assert_eq!(relative_rows[&5], 2);
3605
3606// // works if cursor is before screen
3607// let relative_rows = editor.update(cx, |editor, cx| {
3608// let snapshot = editor.snapshot(cx);
3609
3610// element.calculate_relative_line_numbers(&snapshot, &(3..6), Some(1))
3611// });
3612// assert_eq!(relative_rows.len(), 3);
3613// assert_eq!(relative_rows[&3], 2);
3614// assert_eq!(relative_rows[&4], 3);
3615// assert_eq!(relative_rows[&5], 4);
3616
3617// // works if cursor is after screen
3618// let relative_rows = editor.update(cx, |editor, cx| {
3619// let snapshot = editor.snapshot(cx);
3620
3621// element.calculate_relative_line_numbers(&snapshot, &(0..3), Some(6))
3622// });
3623// assert_eq!(relative_rows.len(), 3);
3624// assert_eq!(relative_rows[&0], 5);
3625// assert_eq!(relative_rows[&1], 4);
3626// assert_eq!(relative_rows[&2], 3);
3627// }
3628
3629// #[gpui::test]
3630// async fn test_vim_visual_selections(cx: &mut TestAppContext) {
3631// init_test(cx, |_| {});
3632
3633// let editor = cx
3634// .add_window(|cx| {
3635// let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
3636// Editor::new(EditorMode::Full, buffer, None, None, cx)
3637// })
3638// .root(cx);
3639// let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3640// let (_, state) = editor.update(cx, |editor, cx| {
3641// editor.cursor_shape = CursorShape::Block;
3642// editor.change_selections(None, cx, |s| {
3643// s.select_ranges([
3644// Point::new(0, 0)..Point::new(1, 0),
3645// Point::new(3, 2)..Point::new(3, 3),
3646// Point::new(5, 6)..Point::new(6, 0),
3647// ]);
3648// });
3649// element.layout(
3650// SizeConstraint::new(point(500., 500.), point(500., 500.)),
3651// editor,
3652// cx,
3653// )
3654// });
3655// assert_eq!(state.selections.len(), 1);
3656// let local_selections = &state.selections[0].1;
3657// assert_eq!(local_selections.len(), 3);
3658// // moves cursor back one line
3659// assert_eq!(local_selections[0].head, DisplayPoint::new(0, 6));
3660// assert_eq!(
3661// local_selections[0].range,
3662// DisplayPoint::new(0, 0)..DisplayPoint::new(1, 0)
3663// );
3664
3665// // moves cursor back one column
3666// assert_eq!(
3667// local_selections[1].range,
3668// DisplayPoint::new(3, 2)..DisplayPoint::new(3, 3)
3669// );
3670// assert_eq!(local_selections[1].head, DisplayPoint::new(3, 2));
3671
3672// // leaves cursor on the max point
3673// assert_eq!(
3674// local_selections[2].range,
3675// DisplayPoint::new(5, 6)..DisplayPoint::new(6, 0)
3676// );
3677// assert_eq!(local_selections[2].head, DisplayPoint::new(6, 0));
3678
3679// // active lines does not include 1 (even though the range of the selection does)
3680// assert_eq!(
3681// state.active_rows.keys().cloned().collect::<Vec<u32>>(),
3682// vec![0, 3, 5, 6]
3683// );
3684
3685// // multi-buffer support
3686// // in DisplayPoint co-ordinates, this is what we're dealing with:
3687// // 0: [[file
3688// // 1: header]]
3689// // 2: aaaaaa
3690// // 3: bbbbbb
3691// // 4: cccccc
3692// // 5:
3693// // 6: ...
3694// // 7: ffffff
3695// // 8: gggggg
3696// // 9: hhhhhh
3697// // 10:
3698// // 11: [[file
3699// // 12: header]]
3700// // 13: bbbbbb
3701// // 14: cccccc
3702// // 15: dddddd
3703// let editor = cx
3704// .add_window(|cx| {
3705// let buffer = MultiBuffer::build_multi(
3706// [
3707// (
3708// &(sample_text(8, 6, 'a') + "\n"),
3709// vec![
3710// Point::new(0, 0)..Point::new(3, 0),
3711// Point::new(4, 0)..Point::new(7, 0),
3712// ],
3713// ),
3714// (
3715// &(sample_text(8, 6, 'a') + "\n"),
3716// vec![Point::new(1, 0)..Point::new(3, 0)],
3717// ),
3718// ],
3719// cx,
3720// );
3721// Editor::new(EditorMode::Full, buffer, None, None, cx)
3722// })
3723// .root(cx);
3724// let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3725// let (_, state) = editor.update(cx, |editor, cx| {
3726// editor.cursor_shape = CursorShape::Block;
3727// editor.change_selections(None, cx, |s| {
3728// s.select_display_ranges([
3729// DisplayPoint::new(4, 0)..DisplayPoint::new(7, 0),
3730// DisplayPoint::new(10, 0)..DisplayPoint::new(13, 0),
3731// ]);
3732// });
3733// element.layout(
3734// SizeConstraint::new(point(500., 500.), point(500., 500.)),
3735// editor,
3736// cx,
3737// )
3738// });
3739
3740// assert_eq!(state.selections.len(), 1);
3741// let local_selections = &state.selections[0].1;
3742// assert_eq!(local_selections.len(), 2);
3743
3744// // moves cursor on excerpt boundary back a line
3745// // and doesn't allow selection to bleed through
3746// assert_eq!(
3747// local_selections[0].range,
3748// DisplayPoint::new(4, 0)..DisplayPoint::new(6, 0)
3749// );
3750// assert_eq!(local_selections[0].head, DisplayPoint::new(5, 0));
3751
3752// // moves cursor on buffer boundary back two lines
3753// // and doesn't allow selection to bleed through
3754// assert_eq!(
3755// local_selections[1].range,
3756// DisplayPoint::new(10, 0)..DisplayPoint::new(11, 0)
3757// );
3758// assert_eq!(local_selections[1].head, DisplayPoint::new(10, 0));
3759// }
3760
3761// #[gpui::test]
3762// fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
3763// init_test(cx, |_| {});
3764
3765// let editor = cx
3766// .add_window(|cx| {
3767// let buffer = MultiBuffer::build_simple("", cx);
3768// Editor::new(EditorMode::Full, buffer, None, None, cx)
3769// })
3770// .root(cx);
3771
3772// editor.update(cx, |editor, cx| {
3773// editor.set_placeholder_text("hello", cx);
3774// editor.insert_blocks(
3775// [BlockProperties {
3776// style: BlockStyle::Fixed,
3777// disposition: BlockDisposition::Above,
3778// height: 3,
3779// position: Anchor::min(),
3780// render: Arc::new(|_| Empty::new().into_any),
3781// }],
3782// None,
3783// cx,
3784// );
3785
3786// // Blur the editor so that it displays placeholder text.
3787// cx.blur();
3788// });
3789
3790// let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3791// let (size, mut state) = editor.update(cx, |editor, cx| {
3792// element.layout(
3793// SizeConstraint::new(point(500., 500.), point(500., 500.)),
3794// editor,
3795// cx,
3796// )
3797// });
3798
3799// assert_eq!(state.position_map.line_layouts.len(), 4);
3800// assert_eq!(
3801// state
3802// .line_number_layouts
3803// .iter()
3804// .map(Option::is_some)
3805// .collect::<Vec<_>>(),
3806// &[false, false, false, true]
3807// );
3808
3809// // Don't panic.
3810// let bounds = Bounds::<Pixels>::new(Default::default(), size);
3811// editor.update(cx, |editor, cx| {
3812// element.paint(bounds, bounds, &mut state, editor, cx);
3813// });
3814// }
3815
3816// #[gpui::test]
3817// fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
3818// const TAB_SIZE: u32 = 4;
3819
3820// let input_text = "\t \t|\t| a b";
3821// let expected_invisibles = vec![
3822// Invisible::Tab {
3823// line_start_offset: 0,
3824// },
3825// Invisible::Whitespace {
3826// line_offset: TAB_SIZE as usize,
3827// },
3828// Invisible::Tab {
3829// line_start_offset: TAB_SIZE as usize + 1,
3830// },
3831// Invisible::Tab {
3832// line_start_offset: TAB_SIZE as usize * 2 + 1,
3833// },
3834// Invisible::Whitespace {
3835// line_offset: TAB_SIZE as usize * 3 + 1,
3836// },
3837// Invisible::Whitespace {
3838// line_offset: TAB_SIZE as usize * 3 + 3,
3839// },
3840// ];
3841// assert_eq!(
3842// expected_invisibles.len(),
3843// input_text
3844// .chars()
3845// .filter(|initial_char| initial_char.is_whitespace())
3846// .count(),
3847// "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
3848// );
3849
3850// init_test(cx, |s| {
3851// s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3852// s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
3853// });
3854
3855// let actual_invisibles =
3856// collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, 500.0);
3857
3858// assert_eq!(expected_invisibles, actual_invisibles);
3859// }
3860
3861// #[gpui::test]
3862// fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
3863// init_test(cx, |s| {
3864// s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3865// s.defaults.tab_size = NonZeroU32::new(4);
3866// });
3867
3868// for editor_mode_without_invisibles in [
3869// EditorMode::SingleLine,
3870// EditorMode::AutoHeight { max_lines: 100 },
3871// ] {
3872// let invisibles = collect_invisibles_from_new_editor(
3873// cx,
3874// editor_mode_without_invisibles,
3875// "\t\t\t| | a b",
3876// 500.0,
3877// );
3878// assert!(invisibles.is_empty,
3879// "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
3880// }
3881// }
3882
3883// #[gpui::test]
3884// fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
3885// let tab_size = 4;
3886// let input_text = "a\tbcd ".repeat(9);
3887// let repeated_invisibles = [
3888// Invisible::Tab {
3889// line_start_offset: 1,
3890// },
3891// Invisible::Whitespace {
3892// line_offset: tab_size as usize + 3,
3893// },
3894// Invisible::Whitespace {
3895// line_offset: tab_size as usize + 4,
3896// },
3897// Invisible::Whitespace {
3898// line_offset: tab_size as usize + 5,
3899// },
3900// ];
3901// let expected_invisibles = std::iter::once(repeated_invisibles)
3902// .cycle()
3903// .take(9)
3904// .flatten()
3905// .collect::<Vec<_>>();
3906// assert_eq!(
3907// expected_invisibles.len(),
3908// input_text
3909// .chars()
3910// .filter(|initial_char| initial_char.is_whitespace())
3911// .count(),
3912// "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
3913// );
3914// info!("Expected invisibles: {expected_invisibles:?}");
3915
3916// init_test(cx, |_| {});
3917
3918// // Put the same string with repeating whitespace pattern into editors of various size,
3919// // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
3920// let resize_step = 10.0;
3921// let mut editor_width = 200.0;
3922// while editor_width <= 1000.0 {
3923// update_test_language_settings(cx, |s| {
3924// s.defaults.tab_size = NonZeroU32::new(tab_size);
3925// s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3926// s.defaults.preferred_line_length = Some(editor_width as u32);
3927// s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
3928// });
3929
3930// let actual_invisibles =
3931// collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, editor_width);
3932
3933// // Whatever the editor size is, ensure it has the same invisible kinds in the same order
3934// // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
3935// let mut i = 0;
3936// for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
3937// i = actual_index;
3938// match expected_invisibles.get(i) {
3939// Some(expected_invisible) => match (expected_invisible, actual_invisible) {
3940// (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
3941// | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
3942// _ => {
3943// panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
3944// }
3945// },
3946// None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
3947// }
3948// }
3949// let missing_expected_invisibles = &expected_invisibles[i + 1..];
3950// assert!(
3951// missing_expected_invisibles.is_empty,
3952// "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
3953// );
3954
3955// editor_width += resize_step;
3956// }
3957// }
3958
3959// fn collect_invisibles_from_new_editor(
3960// cx: &mut TestAppContext,
3961// editor_mode: EditorMode,
3962// input_text: &str,
3963// editor_width: f32,
3964// ) -> Vec<Invisible> {
3965// info!(
3966// "Creating editor with mode {editor_mode:?}, width {editor_width} and text '{input_text}'"
3967// );
3968// let editor = cx
3969// .add_window(|cx| {
3970// let buffer = MultiBuffer::build_simple(&input_text, cx);
3971// Editor::new(editor_mode, buffer, None, None, cx)
3972// })
3973// .root(cx);
3974
3975// let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3976// let (_, layout_state) = editor.update(cx, |editor, cx| {
3977// editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
3978// editor.set_wrap_width(Some(editor_width), cx);
3979
3980// element.layout(
3981// SizeConstraint::new(point(editor_width, 500.), point(editor_width, 500.)),
3982// editor,
3983// cx,
3984// )
3985// });
3986
3987// layout_state
3988// .position_map
3989// .line_layouts
3990// .iter()
3991// .map(|line_with_invisibles| &line_with_invisibles.invisibles)
3992// .flatten()
3993// .cloned()
3994// .collect()
3995// }
3996// }
3997
3998fn build_key_listeners(
3999 global_element_id: GlobalElementId,
4000) -> impl IntoIterator<Item = (TypeId, KeyListener<Editor>)> {
4001 [
4002 build_action_listener(Editor::move_left),
4003 build_action_listener(Editor::move_right),
4004 build_action_listener(Editor::move_down),
4005 build_action_listener(Editor::move_up),
4006 // build_action_listener(Editor::new_file), todo!()
4007 // build_action_listener(Editor::new_file_in_direction), todo!()
4008 build_action_listener(Editor::cancel),
4009 build_action_listener(Editor::newline),
4010 build_action_listener(Editor::newline_above),
4011 build_action_listener(Editor::newline_below),
4012 build_action_listener(Editor::backspace),
4013 build_action_listener(Editor::delete),
4014 build_action_listener(Editor::tab),
4015 build_action_listener(Editor::tab_prev),
4016 build_action_listener(Editor::indent),
4017 build_action_listener(Editor::outdent),
4018 build_action_listener(Editor::delete_line),
4019 build_action_listener(Editor::join_lines),
4020 build_action_listener(Editor::sort_lines_case_sensitive),
4021 build_action_listener(Editor::sort_lines_case_insensitive),
4022 build_action_listener(Editor::reverse_lines),
4023 build_action_listener(Editor::shuffle_lines),
4024 build_action_listener(Editor::convert_to_upper_case),
4025 build_action_listener(Editor::convert_to_lower_case),
4026 build_action_listener(Editor::convert_to_title_case),
4027 build_action_listener(Editor::convert_to_snake_case),
4028 build_action_listener(Editor::convert_to_kebab_case),
4029 build_action_listener(Editor::convert_to_upper_camel_case),
4030 build_action_listener(Editor::convert_to_lower_camel_case),
4031 build_action_listener(Editor::delete_to_previous_word_start),
4032 build_action_listener(Editor::delete_to_previous_subword_start),
4033 build_action_listener(Editor::delete_to_next_word_end),
4034 build_action_listener(Editor::delete_to_next_subword_end),
4035 build_action_listener(Editor::delete_to_beginning_of_line),
4036 build_action_listener(Editor::delete_to_end_of_line),
4037 build_action_listener(Editor::cut_to_end_of_line),
4038 build_action_listener(Editor::duplicate_line),
4039 build_action_listener(Editor::move_line_up),
4040 build_action_listener(Editor::move_line_down),
4041 build_action_listener(Editor::transpose),
4042 build_action_listener(Editor::cut),
4043 build_action_listener(Editor::copy),
4044 build_action_listener(Editor::paste),
4045 build_action_listener(Editor::undo),
4046 build_action_listener(Editor::redo),
4047 build_action_listener(Editor::move_page_up),
4048 build_action_listener(Editor::move_page_down),
4049 build_action_listener(Editor::next_screen),
4050 build_action_listener(Editor::scroll_cursor_top),
4051 build_action_listener(Editor::scroll_cursor_center),
4052 build_action_listener(Editor::scroll_cursor_bottom),
4053 build_action_listener(|editor, _: &LineDown, cx| {
4054 editor.scroll_screen(&ScrollAmount::Line(1.), cx)
4055 }),
4056 build_action_listener(|editor, _: &LineUp, cx| {
4057 editor.scroll_screen(&ScrollAmount::Line(-1.), cx)
4058 }),
4059 build_action_listener(|editor, _: &HalfPageDown, cx| {
4060 editor.scroll_screen(&ScrollAmount::Page(0.5), cx)
4061 }),
4062 build_action_listener(|editor, _: &HalfPageUp, cx| {
4063 editor.scroll_screen(&ScrollAmount::Page(-0.5), cx)
4064 }),
4065 build_action_listener(|editor, _: &PageDown, cx| {
4066 editor.scroll_screen(&ScrollAmount::Page(1.), cx)
4067 }),
4068 build_action_listener(|editor, _: &PageUp, cx| {
4069 editor.scroll_screen(&ScrollAmount::Page(-1.), cx)
4070 }),
4071 build_action_listener(Editor::move_to_previous_word_start),
4072 build_action_listener(Editor::move_to_previous_subword_start),
4073 build_action_listener(Editor::move_to_next_word_end),
4074 build_action_listener(Editor::move_to_next_subword_end),
4075 build_action_listener(Editor::move_to_beginning_of_line),
4076 build_action_listener(Editor::move_to_end_of_line),
4077 build_action_listener(Editor::move_to_start_of_paragraph),
4078 build_action_listener(Editor::move_to_end_of_paragraph),
4079 build_action_listener(Editor::move_to_beginning),
4080 build_action_listener(Editor::move_to_end),
4081 build_action_listener(Editor::select_up),
4082 build_action_listener(Editor::select_down),
4083 build_action_listener(Editor::select_left),
4084 build_action_listener(Editor::select_right),
4085 build_action_listener(Editor::select_to_previous_word_start),
4086 build_action_listener(Editor::select_to_previous_subword_start),
4087 build_action_listener(Editor::select_to_next_word_end),
4088 build_action_listener(Editor::select_to_next_subword_end),
4089 build_action_listener(Editor::select_to_beginning_of_line),
4090 build_action_listener(Editor::select_to_end_of_line),
4091 build_action_listener(Editor::select_to_start_of_paragraph),
4092 build_action_listener(Editor::select_to_end_of_paragraph),
4093 build_action_listener(Editor::select_to_beginning),
4094 build_action_listener(Editor::select_to_end),
4095 build_action_listener(Editor::select_all),
4096 build_action_listener(|editor, action, cx| {
4097 editor.select_all_matches(action, cx).log_err();
4098 }),
4099 build_action_listener(Editor::select_line),
4100 build_action_listener(Editor::split_selection_into_lines),
4101 build_action_listener(Editor::add_selection_above),
4102 build_action_listener(Editor::add_selection_below),
4103 build_action_listener(|editor, action, cx| {
4104 editor.select_next(action, cx).log_err();
4105 }),
4106 build_action_listener(|editor, action, cx| {
4107 editor.select_previous(action, cx).log_err();
4108 }),
4109 build_action_listener(Editor::toggle_comments),
4110 build_action_listener(Editor::select_larger_syntax_node),
4111 build_action_listener(Editor::select_smaller_syntax_node),
4112 build_action_listener(Editor::move_to_enclosing_bracket),
4113 build_action_listener(Editor::undo_selection),
4114 build_action_listener(Editor::redo_selection),
4115 build_action_listener(Editor::go_to_diagnostic),
4116 build_action_listener(Editor::go_to_prev_diagnostic),
4117 build_action_listener(Editor::go_to_hunk),
4118 build_action_listener(Editor::go_to_prev_hunk),
4119 build_action_listener(Editor::go_to_definition),
4120 build_action_listener(Editor::go_to_definition_split),
4121 build_action_listener(Editor::go_to_type_definition),
4122 build_action_listener(Editor::go_to_type_definition_split),
4123 build_action_listener(Editor::fold),
4124 build_action_listener(Editor::fold_at),
4125 build_action_listener(Editor::unfold_lines),
4126 build_action_listener(Editor::unfold_at),
4127 build_action_listener(Editor::fold_selected_ranges),
4128 build_action_listener(Editor::show_completions),
4129 build_action_listener(Editor::toggle_code_actions),
4130 // build_action_listener(Editor::open_excerpts), todo!()
4131 build_action_listener(Editor::toggle_soft_wrap),
4132 build_action_listener(Editor::toggle_inlay_hints),
4133 build_action_listener(Editor::reveal_in_finder),
4134 build_action_listener(Editor::copy_path),
4135 build_action_listener(Editor::copy_relative_path),
4136 build_action_listener(Editor::copy_highlight_json),
4137 build_action_listener(|editor, action, cx| {
4138 editor
4139 .format(action, cx)
4140 .map(|task| task.detach_and_log_err(cx));
4141 }),
4142 build_action_listener(Editor::restart_language_server),
4143 build_action_listener(Editor::show_character_palette),
4144 // build_action_listener(Editor::confirm_completion), todo!()
4145 build_action_listener(|editor, action, cx| {
4146 editor
4147 .confirm_code_action(action, cx)
4148 .map(|task| task.detach_and_log_err(cx));
4149 }),
4150 // build_action_listener(Editor::rename), todo!()
4151 // build_action_listener(Editor::confirm_rename), todo!()
4152 // build_action_listener(Editor::find_all_references), todo!()
4153 build_action_listener(Editor::next_copilot_suggestion),
4154 build_action_listener(Editor::previous_copilot_suggestion),
4155 build_action_listener(Editor::copilot_suggest),
4156 build_action_listener(Editor::context_menu_first),
4157 build_action_listener(Editor::context_menu_prev),
4158 build_action_listener(Editor::context_menu_next),
4159 build_action_listener(Editor::context_menu_last),
4160 build_key_listener(
4161 move |editor, key_down: &KeyDownEvent, dispatch_context, phase, cx| {
4162 if phase == DispatchPhase::Bubble {
4163 if let KeyMatch::Some(action) = cx.match_keystroke(
4164 &global_element_id,
4165 &key_down.keystroke,
4166 dispatch_context,
4167 ) {
4168 return Some(action);
4169 }
4170 }
4171
4172 None
4173 },
4174 ),
4175 ]
4176}
4177
4178fn build_key_listener<T: 'static>(
4179 listener: impl Fn(
4180 &mut Editor,
4181 &T,
4182 &[&DispatchContext],
4183 DispatchPhase,
4184 &mut ViewContext<Editor>,
4185 ) -> Option<Box<dyn Action>>
4186 + 'static,
4187) -> (TypeId, KeyListener<Editor>) {
4188 (
4189 TypeId::of::<T>(),
4190 Box::new(move |editor, event, dispatch_context, phase, cx| {
4191 let key_event = event.downcast_ref::<T>()?;
4192 listener(editor, key_event, dispatch_context, phase, cx)
4193 }),
4194 )
4195}
4196
4197fn build_action_listener<T: Action>(
4198 listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
4199) -> (TypeId, KeyListener<Editor>) {
4200 build_key_listener(move |editor, action: &T, dispatch_context, phase, cx| {
4201 if phase == DispatchPhase::Bubble {
4202 listener(editor, action, cx);
4203 }
4204 None
4205 })
4206}