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