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