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