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