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