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