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