1use crate::{
2 display_map::{
3 BlockContext, BlockStyle, DisplaySnapshot, FoldStatus, HighlightedChunk, ToDisplayPoint,
4 TransformBlock,
5 },
6 editor_settings::{DoubleClickInMultibuffer, MultiCursorModifier, ShowScrollbar},
7 git::{
8 blame::{CommitDetails, GitBlame},
9 diff_hunk_to_display, DisplayDiffHunk,
10 },
11 hover_popover::{
12 self, hover_at, HOVER_POPOVER_GAP, MIN_POPOVER_CHARACTER_WIDTH, MIN_POPOVER_LINE_HEIGHT,
13 },
14 items::BufferSearchHighlights,
15 mouse_context_menu::{self, MouseContextMenu},
16 scroll::scroll_amount::ScrollAmount,
17 CursorShape, DisplayPoint, DocumentHighlightRead, DocumentHighlightWrite, Editor, EditorMode,
18 EditorSettings, EditorSnapshot, EditorStyle, GutterDimensions, HalfPageDown, HalfPageUp,
19 HoveredCursor, LineDown, LineUp, OpenExcerpts, PageDown, PageUp, Point, SelectPhase, Selection,
20 SoftWrap, ToPoint, CURSORS_VISIBLE_FOR, MAX_LINE_LEN,
21};
22use anyhow::Result;
23use collections::{BTreeMap, HashMap};
24use git::{blame::BlameEntry, diff::DiffHunkStatus, Oid};
25use gpui::{
26 anchored, deferred, div, fill, outline, point, px, quad, relative, size, svg,
27 transparent_black, Action, AnchorCorner, AnyElement, AvailableSpace, Bounds, ClipboardItem,
28 ContentMask, Corners, CursorStyle, DispatchPhase, Edges, Element, ElementContext,
29 ElementInputHandler, Entity, Hitbox, Hsla, InteractiveElement, IntoElement,
30 ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PaintQuad,
31 ParentElement, Pixels, ScrollDelta, ScrollHandle, ScrollWheelEvent, ShapedLine, SharedString,
32 Size, Stateful, StatefulInteractiveElement, Style, Styled, TextRun, TextStyle,
33 TextStyleRefinement, View, ViewContext, WeakView, WindowContext,
34};
35use itertools::Itertools;
36use language::language_settings::ShowWhitespaceSetting;
37use lsp::DiagnosticSeverity;
38use multi_buffer::Anchor;
39use project::{
40 project_settings::{GitGutterSetting, ProjectSettings},
41 ProjectPath,
42};
43use settings::Settings;
44use smallvec::SmallVec;
45use std::{
46 any::TypeId,
47 borrow::Cow,
48 cmp::{self, Ordering},
49 fmt::Write,
50 iter, mem,
51 ops::Range,
52 sync::Arc,
53};
54use sum_tree::Bias;
55use theme::{ActiveTheme, PlayerColor, ThemeSettings};
56use ui::{h_flex, ButtonLike, ButtonStyle, ContextMenu, Tooltip};
57use ui::{prelude::*, tooltip_container};
58use util::ResultExt;
59use workspace::{item::Item, Workspace};
60
61struct SelectionLayout {
62 head: DisplayPoint,
63 cursor_shape: CursorShape,
64 is_newest: bool,
65 is_local: bool,
66 range: Range<DisplayPoint>,
67 active_rows: Range<u32>,
68 user_name: Option<SharedString>,
69}
70
71impl SelectionLayout {
72 fn new<T: ToPoint + ToDisplayPoint + Clone>(
73 selection: Selection<T>,
74 line_mode: bool,
75 cursor_shape: CursorShape,
76 map: &DisplaySnapshot,
77 is_newest: bool,
78 is_local: bool,
79 user_name: Option<SharedString>,
80 ) -> Self {
81 let point_selection = selection.map(|p| p.to_point(&map.buffer_snapshot));
82 let display_selection = point_selection.map(|p| p.to_display_point(map));
83 let mut range = display_selection.range();
84 let mut head = display_selection.head();
85 let mut active_rows = map.prev_line_boundary(point_selection.start).1.row()
86 ..map.next_line_boundary(point_selection.end).1.row();
87
88 // vim visual line mode
89 if line_mode {
90 let point_range = map.expand_to_line(point_selection.range());
91 range = point_range.start.to_display_point(map)..point_range.end.to_display_point(map);
92 }
93
94 // any vim visual mode (including line mode)
95 if cursor_shape == CursorShape::Block && !range.is_empty() && !selection.reversed {
96 if head.column() > 0 {
97 head = map.clip_point(DisplayPoint::new(head.row(), head.column() - 1), Bias::Left)
98 } else if head.row() > 0 && head != map.max_point() {
99 head = map.clip_point(
100 DisplayPoint::new(head.row() - 1, map.line_len(head.row() - 1)),
101 Bias::Left,
102 );
103 // updating range.end is a no-op unless you're cursor is
104 // on the newline containing a multi-buffer divider
105 // in which case the clip_point may have moved the head up
106 // an additional row.
107 range.end = DisplayPoint::new(head.row() + 1, 0);
108 active_rows.end = head.row();
109 }
110 }
111
112 Self {
113 head,
114 cursor_shape,
115 is_newest,
116 is_local,
117 range,
118 active_rows,
119 user_name,
120 }
121 }
122}
123
124pub struct EditorElement {
125 editor: View<Editor>,
126 style: EditorStyle,
127}
128
129impl EditorElement {
130 pub fn new(editor: &View<Editor>, style: EditorStyle) -> Self {
131 Self {
132 editor: editor.clone(),
133 style,
134 }
135 }
136
137 fn register_actions(&self, cx: &mut WindowContext) {
138 let view = &self.editor;
139 view.update(cx, |editor, cx| {
140 for action in editor.editor_actions.iter() {
141 (action)(cx)
142 }
143 });
144
145 crate::rust_analyzer_ext::apply_related_actions(view, cx);
146 register_action(view, cx, Editor::move_left);
147 register_action(view, cx, Editor::move_right);
148 register_action(view, cx, Editor::move_down);
149 register_action(view, cx, Editor::move_down_by_lines);
150 register_action(view, cx, Editor::select_down_by_lines);
151 register_action(view, cx, Editor::move_up);
152 register_action(view, cx, Editor::move_up_by_lines);
153 register_action(view, cx, Editor::select_up_by_lines);
154 register_action(view, cx, Editor::cancel);
155 register_action(view, cx, Editor::newline);
156 register_action(view, cx, Editor::newline_above);
157 register_action(view, cx, Editor::newline_below);
158 register_action(view, cx, Editor::backspace);
159 register_action(view, cx, Editor::delete);
160 register_action(view, cx, Editor::tab);
161 register_action(view, cx, Editor::tab_prev);
162 register_action(view, cx, Editor::indent);
163 register_action(view, cx, Editor::outdent);
164 register_action(view, cx, Editor::delete_line);
165 register_action(view, cx, Editor::join_lines);
166 register_action(view, cx, Editor::sort_lines_case_sensitive);
167 register_action(view, cx, Editor::sort_lines_case_insensitive);
168 register_action(view, cx, Editor::reverse_lines);
169 register_action(view, cx, Editor::shuffle_lines);
170 register_action(view, cx, Editor::convert_to_upper_case);
171 register_action(view, cx, Editor::convert_to_lower_case);
172 register_action(view, cx, Editor::convert_to_title_case);
173 register_action(view, cx, Editor::convert_to_snake_case);
174 register_action(view, cx, Editor::convert_to_kebab_case);
175 register_action(view, cx, Editor::convert_to_upper_camel_case);
176 register_action(view, cx, Editor::convert_to_lower_camel_case);
177 register_action(view, cx, Editor::delete_to_previous_word_start);
178 register_action(view, cx, Editor::delete_to_previous_subword_start);
179 register_action(view, cx, Editor::delete_to_next_word_end);
180 register_action(view, cx, Editor::delete_to_next_subword_end);
181 register_action(view, cx, Editor::delete_to_beginning_of_line);
182 register_action(view, cx, Editor::delete_to_end_of_line);
183 register_action(view, cx, Editor::cut_to_end_of_line);
184 register_action(view, cx, Editor::duplicate_line_up);
185 register_action(view, cx, Editor::duplicate_line_down);
186 register_action(view, cx, Editor::move_line_up);
187 register_action(view, cx, Editor::move_line_down);
188 register_action(view, cx, Editor::transpose);
189 register_action(view, cx, Editor::cut);
190 register_action(view, cx, Editor::copy);
191 register_action(view, cx, Editor::paste);
192 register_action(view, cx, Editor::undo);
193 register_action(view, cx, Editor::redo);
194 register_action(view, cx, Editor::move_page_up);
195 register_action(view, cx, Editor::move_page_down);
196 register_action(view, cx, Editor::next_screen);
197 register_action(view, cx, Editor::scroll_cursor_top);
198 register_action(view, cx, Editor::scroll_cursor_center);
199 register_action(view, cx, Editor::scroll_cursor_bottom);
200 register_action(view, cx, |editor, _: &LineDown, cx| {
201 editor.scroll_screen(&ScrollAmount::Line(1.), cx)
202 });
203 register_action(view, cx, |editor, _: &LineUp, cx| {
204 editor.scroll_screen(&ScrollAmount::Line(-1.), cx)
205 });
206 register_action(view, cx, |editor, _: &HalfPageDown, cx| {
207 editor.scroll_screen(&ScrollAmount::Page(0.5), cx)
208 });
209 register_action(view, cx, |editor, _: &HalfPageUp, cx| {
210 editor.scroll_screen(&ScrollAmount::Page(-0.5), cx)
211 });
212 register_action(view, cx, |editor, _: &PageDown, cx| {
213 editor.scroll_screen(&ScrollAmount::Page(1.), cx)
214 });
215 register_action(view, cx, |editor, _: &PageUp, cx| {
216 editor.scroll_screen(&ScrollAmount::Page(-1.), cx)
217 });
218 register_action(view, cx, Editor::move_to_previous_word_start);
219 register_action(view, cx, Editor::move_to_previous_subword_start);
220 register_action(view, cx, Editor::move_to_next_word_end);
221 register_action(view, cx, Editor::move_to_next_subword_end);
222 register_action(view, cx, Editor::move_to_beginning_of_line);
223 register_action(view, cx, Editor::move_to_end_of_line);
224 register_action(view, cx, Editor::move_to_start_of_paragraph);
225 register_action(view, cx, Editor::move_to_end_of_paragraph);
226 register_action(view, cx, Editor::move_to_beginning);
227 register_action(view, cx, Editor::move_to_end);
228 register_action(view, cx, Editor::select_up);
229 register_action(view, cx, Editor::select_down);
230 register_action(view, cx, Editor::select_left);
231 register_action(view, cx, Editor::select_right);
232 register_action(view, cx, Editor::select_to_previous_word_start);
233 register_action(view, cx, Editor::select_to_previous_subword_start);
234 register_action(view, cx, Editor::select_to_next_word_end);
235 register_action(view, cx, Editor::select_to_next_subword_end);
236 register_action(view, cx, Editor::select_to_beginning_of_line);
237 register_action(view, cx, Editor::select_to_end_of_line);
238 register_action(view, cx, Editor::select_to_start_of_paragraph);
239 register_action(view, cx, Editor::select_to_end_of_paragraph);
240 register_action(view, cx, Editor::select_to_beginning);
241 register_action(view, cx, Editor::select_to_end);
242 register_action(view, cx, Editor::select_all);
243 register_action(view, cx, |editor, action, cx| {
244 editor.select_all_matches(action, cx).log_err();
245 });
246 register_action(view, cx, Editor::select_line);
247 register_action(view, cx, Editor::split_selection_into_lines);
248 register_action(view, cx, Editor::add_selection_above);
249 register_action(view, cx, Editor::add_selection_below);
250 register_action(view, cx, |editor, action, cx| {
251 editor.select_next(action, cx).log_err();
252 });
253 register_action(view, cx, |editor, action, cx| {
254 editor.select_previous(action, cx).log_err();
255 });
256 register_action(view, cx, Editor::toggle_comments);
257 register_action(view, cx, Editor::select_larger_syntax_node);
258 register_action(view, cx, Editor::select_smaller_syntax_node);
259 register_action(view, cx, Editor::move_to_enclosing_bracket);
260 register_action(view, cx, Editor::undo_selection);
261 register_action(view, cx, Editor::redo_selection);
262 register_action(view, cx, Editor::go_to_diagnostic);
263 register_action(view, cx, Editor::go_to_prev_diagnostic);
264 register_action(view, cx, Editor::go_to_hunk);
265 register_action(view, cx, Editor::go_to_prev_hunk);
266 register_action(view, cx, |editor, a, cx| {
267 editor.go_to_definition(a, cx).detach_and_log_err(cx);
268 });
269 register_action(view, cx, |editor, a, cx| {
270 editor.go_to_definition_split(a, cx).detach_and_log_err(cx);
271 });
272 register_action(view, cx, |editor, a, cx| {
273 editor.go_to_implementation(a, cx).detach_and_log_err(cx);
274 });
275 register_action(view, cx, |editor, a, cx| {
276 editor
277 .go_to_implementation_split(a, cx)
278 .detach_and_log_err(cx);
279 });
280 register_action(view, cx, |editor, a, cx| {
281 editor.go_to_type_definition(a, cx).detach_and_log_err(cx);
282 });
283 register_action(view, cx, |editor, a, cx| {
284 editor
285 .go_to_type_definition_split(a, cx)
286 .detach_and_log_err(cx);
287 });
288 register_action(view, cx, Editor::open_url);
289 register_action(view, cx, Editor::fold);
290 register_action(view, cx, Editor::fold_at);
291 register_action(view, cx, Editor::unfold_lines);
292 register_action(view, cx, Editor::unfold_at);
293 register_action(view, cx, Editor::fold_selected_ranges);
294 register_action(view, cx, Editor::show_completions);
295 register_action(view, cx, Editor::toggle_code_actions);
296 register_action(view, cx, Editor::open_excerpts);
297 register_action(view, cx, Editor::open_excerpts_in_split);
298 register_action(view, cx, Editor::toggle_soft_wrap);
299 register_action(view, cx, Editor::toggle_line_numbers);
300 register_action(view, cx, Editor::toggle_inlay_hints);
301 register_action(view, cx, hover_popover::hover);
302 register_action(view, cx, Editor::reveal_in_finder);
303 register_action(view, cx, Editor::copy_path);
304 register_action(view, cx, Editor::copy_relative_path);
305 register_action(view, cx, Editor::copy_highlight_json);
306 register_action(view, cx, Editor::copy_permalink_to_line);
307 register_action(view, cx, Editor::open_permalink_to_line);
308 register_action(view, cx, Editor::toggle_git_blame);
309 register_action(view, cx, Editor::toggle_git_blame_inline);
310 register_action(view, cx, |editor, action, cx| {
311 if let Some(task) = editor.format(action, cx) {
312 task.detach_and_log_err(cx);
313 } else {
314 cx.propagate();
315 }
316 });
317 register_action(view, cx, Editor::restart_language_server);
318 register_action(view, cx, Editor::show_character_palette);
319 register_action(view, cx, |editor, action, cx| {
320 if let Some(task) = editor.confirm_completion(action, cx) {
321 task.detach_and_log_err(cx);
322 } else {
323 cx.propagate();
324 }
325 });
326 register_action(view, cx, |editor, action, cx| {
327 if let Some(task) = editor.confirm_code_action(action, cx) {
328 task.detach_and_log_err(cx);
329 } else {
330 cx.propagate();
331 }
332 });
333 register_action(view, cx, |editor, action, cx| {
334 if let Some(task) = editor.rename(action, cx) {
335 task.detach_and_log_err(cx);
336 } else {
337 cx.propagate();
338 }
339 });
340 register_action(view, cx, |editor, action, cx| {
341 if let Some(task) = editor.confirm_rename(action, cx) {
342 task.detach_and_log_err(cx);
343 } else {
344 cx.propagate();
345 }
346 });
347 register_action(view, cx, |editor, action, cx| {
348 if let Some(task) = editor.find_all_references(action, cx) {
349 task.detach_and_log_err(cx);
350 } else {
351 cx.propagate();
352 }
353 });
354 register_action(view, cx, Editor::next_inline_completion);
355 register_action(view, cx, Editor::previous_inline_completion);
356 register_action(view, cx, Editor::show_inline_completion);
357 register_action(view, cx, Editor::context_menu_first);
358 register_action(view, cx, Editor::context_menu_prev);
359 register_action(view, cx, Editor::context_menu_next);
360 register_action(view, cx, Editor::context_menu_last);
361 register_action(view, cx, Editor::display_cursor_names);
362 register_action(view, cx, Editor::unique_lines_case_insensitive);
363 register_action(view, cx, Editor::unique_lines_case_sensitive);
364 register_action(view, cx, Editor::accept_partial_inline_completion);
365 register_action(view, cx, Editor::revert_selected_hunks);
366 }
367
368 fn register_key_listeners(&self, cx: &mut ElementContext, layout: &EditorLayout) {
369 let position_map = layout.position_map.clone();
370 cx.on_key_event({
371 let editor = self.editor.clone();
372 let text_hitbox = layout.text_hitbox.clone();
373 move |event: &ModifiersChangedEvent, phase, cx| {
374 if phase != DispatchPhase::Bubble {
375 return;
376 }
377
378 editor.update(cx, |editor, cx| {
379 Self::modifiers_changed(editor, event, &position_map, &text_hitbox, cx)
380 })
381 }
382 });
383 }
384
385 fn modifiers_changed(
386 editor: &mut Editor,
387 event: &ModifiersChangedEvent,
388 position_map: &PositionMap,
389 text_hitbox: &Hitbox,
390 cx: &mut ViewContext<Editor>,
391 ) {
392 let mouse_position = cx.mouse_position();
393 if !text_hitbox.is_hovered(cx) {
394 return;
395 }
396
397 editor.update_hovered_link(
398 position_map.point_for_position(text_hitbox.bounds, mouse_position),
399 &position_map.snapshot,
400 event.modifiers,
401 cx,
402 )
403 }
404
405 fn mouse_left_down(
406 editor: &mut Editor,
407 event: &MouseDownEvent,
408 position_map: &PositionMap,
409 text_hitbox: &Hitbox,
410 gutter_hitbox: &Hitbox,
411 cx: &mut ViewContext<Editor>,
412 ) {
413 if cx.default_prevented() {
414 return;
415 }
416
417 let mut click_count = event.click_count;
418 let mut modifiers = event.modifiers;
419
420 if gutter_hitbox.is_hovered(cx) {
421 click_count = 3; // Simulate triple-click when clicking the gutter to select lines
422 } else if !text_hitbox.is_hovered(cx) {
423 return;
424 }
425
426 if click_count == 2 && !editor.buffer().read(cx).is_singleton() {
427 match EditorSettings::get_global(cx).double_click_in_multibuffer {
428 DoubleClickInMultibuffer::Select => {
429 // do nothing special on double click, all selection logic is below
430 }
431 DoubleClickInMultibuffer::Open => {
432 if modifiers.alt {
433 // if double click is made with alt, pretend it's a regular double click without opening and alt,
434 // and run the selection logic.
435 modifiers.alt = false;
436 } else {
437 // if double click is made without alt, open the corresponding excerp
438 editor.open_excerpts(&OpenExcerpts, cx);
439 return;
440 }
441 }
442 }
443 }
444
445 let point_for_position =
446 position_map.point_for_position(text_hitbox.bounds, event.position);
447 let position = point_for_position.previous_valid;
448 if modifiers.shift && modifiers.alt {
449 editor.select(
450 SelectPhase::BeginColumnar {
451 position,
452 goal_column: point_for_position.exact_unclipped.column(),
453 },
454 cx,
455 );
456 } else if modifiers.shift && !modifiers.control && !modifiers.alt && !modifiers.secondary()
457 {
458 editor.select(
459 SelectPhase::Extend {
460 position,
461 click_count,
462 },
463 cx,
464 );
465 } else {
466 let multi_cursor_setting = EditorSettings::get_global(cx).multi_cursor_modifier;
467 let multi_cursor_modifier = match multi_cursor_setting {
468 MultiCursorModifier::Alt => modifiers.alt,
469 MultiCursorModifier::CmdOrCtrl => modifiers.secondary(),
470 };
471 editor.select(
472 SelectPhase::Begin {
473 position,
474 add: multi_cursor_modifier,
475 click_count,
476 },
477 cx,
478 );
479 }
480
481 cx.stop_propagation();
482 }
483
484 fn mouse_right_down(
485 editor: &mut Editor,
486 event: &MouseDownEvent,
487 position_map: &PositionMap,
488 text_hitbox: &Hitbox,
489 cx: &mut ViewContext<Editor>,
490 ) {
491 if !text_hitbox.is_hovered(cx) {
492 return;
493 }
494 let point_for_position =
495 position_map.point_for_position(text_hitbox.bounds, event.position);
496 mouse_context_menu::deploy_context_menu(
497 editor,
498 event.position,
499 point_for_position.previous_valid,
500 cx,
501 );
502 cx.stop_propagation();
503 }
504
505 fn mouse_up(
506 editor: &mut Editor,
507 event: &MouseUpEvent,
508 position_map: &PositionMap,
509 text_hitbox: &Hitbox,
510 cx: &mut ViewContext<Editor>,
511 ) {
512 let end_selection = editor.has_pending_selection();
513 let pending_nonempty_selections = editor.has_pending_nonempty_selection();
514
515 if end_selection {
516 editor.select(SelectPhase::End, cx);
517 }
518
519 let multi_cursor_setting = EditorSettings::get_global(cx).multi_cursor_modifier;
520 let multi_cursor_modifier = match multi_cursor_setting {
521 MultiCursorModifier::Alt => event.modifiers.secondary(),
522 MultiCursorModifier::CmdOrCtrl => event.modifiers.alt,
523 };
524
525 if !pending_nonempty_selections && multi_cursor_modifier && text_hitbox.is_hovered(cx) {
526 let point = position_map.point_for_position(text_hitbox.bounds, event.position);
527 editor.handle_click_hovered_link(point, event.modifiers, cx);
528
529 cx.stop_propagation();
530 } else if end_selection {
531 cx.stop_propagation();
532 }
533 }
534
535 fn mouse_dragged(
536 editor: &mut Editor,
537 event: &MouseMoveEvent,
538 position_map: &PositionMap,
539 text_bounds: Bounds<Pixels>,
540 cx: &mut ViewContext<Editor>,
541 ) {
542 if !editor.has_pending_selection() {
543 return;
544 }
545
546 let point_for_position = position_map.point_for_position(text_bounds, event.position);
547 let mut scroll_delta = gpui::Point::<f32>::default();
548 let vertical_margin = position_map.line_height.min(text_bounds.size.height / 3.0);
549 let top = text_bounds.origin.y + vertical_margin;
550 let bottom = text_bounds.lower_left().y - vertical_margin;
551 if event.position.y < top {
552 scroll_delta.y = -scale_vertical_mouse_autoscroll_delta(top - event.position.y);
553 }
554 if event.position.y > bottom {
555 scroll_delta.y = scale_vertical_mouse_autoscroll_delta(event.position.y - bottom);
556 }
557
558 let horizontal_margin = position_map.line_height.min(text_bounds.size.width / 3.0);
559 let left = text_bounds.origin.x + horizontal_margin;
560 let right = text_bounds.upper_right().x - horizontal_margin;
561 if event.position.x < left {
562 scroll_delta.x = -scale_horizontal_mouse_autoscroll_delta(left - event.position.x);
563 }
564 if event.position.x > right {
565 scroll_delta.x = scale_horizontal_mouse_autoscroll_delta(event.position.x - right);
566 }
567
568 editor.select(
569 SelectPhase::Update {
570 position: point_for_position.previous_valid,
571 goal_column: point_for_position.exact_unclipped.column(),
572 scroll_delta,
573 },
574 cx,
575 );
576 }
577
578 fn mouse_moved(
579 editor: &mut Editor,
580 event: &MouseMoveEvent,
581 position_map: &PositionMap,
582 text_hitbox: &Hitbox,
583 gutter_hitbox: &Hitbox,
584 cx: &mut ViewContext<Editor>,
585 ) {
586 let modifiers = event.modifiers;
587 let gutter_hovered = gutter_hitbox.is_hovered(cx);
588 editor.set_gutter_hovered(gutter_hovered, cx);
589
590 // Don't trigger hover popover if mouse is hovering over context menu
591 if text_hitbox.is_hovered(cx) {
592 let point_for_position =
593 position_map.point_for_position(text_hitbox.bounds, event.position);
594
595 editor.update_hovered_link(point_for_position, &position_map.snapshot, modifiers, cx);
596
597 if let Some(point) = point_for_position.as_valid() {
598 hover_at(editor, Some(point), cx);
599 Self::update_visible_cursor(editor, point, position_map, cx);
600 } else {
601 hover_at(editor, None, cx);
602 }
603 } else {
604 editor.hide_hovered_link(cx);
605 hover_at(editor, None, cx);
606 if gutter_hovered {
607 cx.stop_propagation();
608 }
609 }
610 }
611
612 fn update_visible_cursor(
613 editor: &mut Editor,
614 point: DisplayPoint,
615 position_map: &PositionMap,
616 cx: &mut ViewContext<Editor>,
617 ) {
618 let snapshot = &position_map.snapshot;
619 let Some(hub) = editor.collaboration_hub() else {
620 return;
621 };
622 let range = DisplayPoint::new(point.row(), point.column().saturating_sub(1))
623 ..DisplayPoint::new(
624 point.row(),
625 (point.column() + 1).min(snapshot.line_len(point.row())),
626 );
627
628 let range = snapshot
629 .buffer_snapshot
630 .anchor_at(range.start.to_point(&snapshot.display_snapshot), Bias::Left)
631 ..snapshot
632 .buffer_snapshot
633 .anchor_at(range.end.to_point(&snapshot.display_snapshot), Bias::Right);
634
635 let Some(selection) = snapshot.remote_selections_in_range(&range, hub, cx).next() else {
636 return;
637 };
638 let key = crate::HoveredCursor {
639 replica_id: selection.replica_id,
640 selection_id: selection.selection.id,
641 };
642 editor.hovered_cursors.insert(
643 key.clone(),
644 cx.spawn(|editor, mut cx| async move {
645 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
646 editor
647 .update(&mut cx, |editor, cx| {
648 editor.hovered_cursors.remove(&key);
649 cx.notify();
650 })
651 .ok();
652 }),
653 );
654 cx.notify()
655 }
656
657 fn layout_selections(
658 &self,
659 start_anchor: Anchor,
660 end_anchor: Anchor,
661 snapshot: &EditorSnapshot,
662 start_row: u32,
663 end_row: u32,
664 cx: &mut ElementContext,
665 ) -> (
666 Vec<(PlayerColor, Vec<SelectionLayout>)>,
667 BTreeMap<u32, bool>,
668 Option<DisplayPoint>,
669 ) {
670 let mut selections: Vec<(PlayerColor, Vec<SelectionLayout>)> = Vec::new();
671 let mut active_rows = BTreeMap::new();
672 let mut newest_selection_head = None;
673 let editor = self.editor.read(cx);
674
675 if editor.show_local_selections {
676 let mut local_selections: Vec<Selection<Point>> = editor
677 .selections
678 .disjoint_in_range(start_anchor..end_anchor, cx);
679 local_selections.extend(editor.selections.pending(cx));
680 let mut layouts = Vec::new();
681 let newest = editor.selections.newest(cx);
682 for selection in local_selections.drain(..) {
683 let is_empty = selection.start == selection.end;
684 let is_newest = selection == newest;
685
686 let layout = SelectionLayout::new(
687 selection,
688 editor.selections.line_mode,
689 editor.cursor_shape,
690 &snapshot.display_snapshot,
691 is_newest,
692 editor.leader_peer_id.is_none(),
693 None,
694 );
695 if is_newest {
696 newest_selection_head = Some(layout.head);
697 }
698
699 for row in cmp::max(layout.active_rows.start, start_row)
700 ..=cmp::min(layout.active_rows.end, end_row)
701 {
702 let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
703 *contains_non_empty_selection |= !is_empty;
704 }
705 layouts.push(layout);
706 }
707
708 let player = if editor.read_only(cx) {
709 cx.theme().players().read_only()
710 } else {
711 self.style.local_player
712 };
713
714 selections.push((player, layouts));
715 }
716
717 if let Some(collaboration_hub) = &editor.collaboration_hub {
718 // When following someone, render the local selections in their color.
719 if let Some(leader_id) = editor.leader_peer_id {
720 if let Some(collaborator) = collaboration_hub.collaborators(cx).get(&leader_id) {
721 if let Some(participant_index) = collaboration_hub
722 .user_participant_indices(cx)
723 .get(&collaborator.user_id)
724 {
725 if let Some((local_selection_style, _)) = selections.first_mut() {
726 *local_selection_style = cx
727 .theme()
728 .players()
729 .color_for_participant(participant_index.0);
730 }
731 }
732 }
733 }
734
735 let mut remote_selections = HashMap::default();
736 for selection in snapshot.remote_selections_in_range(
737 &(start_anchor..end_anchor),
738 collaboration_hub.as_ref(),
739 cx,
740 ) {
741 let selection_style = if let Some(participant_index) = selection.participant_index {
742 cx.theme()
743 .players()
744 .color_for_participant(participant_index.0)
745 } else {
746 cx.theme().players().absent()
747 };
748
749 // Don't re-render the leader's selections, since the local selections
750 // match theirs.
751 if Some(selection.peer_id) == editor.leader_peer_id {
752 continue;
753 }
754 let key = HoveredCursor {
755 replica_id: selection.replica_id,
756 selection_id: selection.selection.id,
757 };
758
759 let is_shown =
760 editor.show_cursor_names || editor.hovered_cursors.contains_key(&key);
761
762 remote_selections
763 .entry(selection.replica_id)
764 .or_insert((selection_style, Vec::new()))
765 .1
766 .push(SelectionLayout::new(
767 selection.selection,
768 selection.line_mode,
769 selection.cursor_shape,
770 &snapshot.display_snapshot,
771 false,
772 false,
773 if is_shown { selection.user_name } else { None },
774 ));
775 }
776
777 selections.extend(remote_selections.into_values());
778 }
779 (selections, active_rows, newest_selection_head)
780 }
781
782 #[allow(clippy::too_many_arguments)]
783 fn layout_folds(
784 &self,
785 snapshot: &EditorSnapshot,
786 content_origin: gpui::Point<Pixels>,
787 visible_anchor_range: Range<Anchor>,
788 visible_display_row_range: Range<u32>,
789 scroll_pixel_position: gpui::Point<Pixels>,
790 line_height: Pixels,
791 line_layouts: &[LineWithInvisibles],
792 cx: &mut ElementContext,
793 ) -> Vec<FoldLayout> {
794 snapshot
795 .folds_in_range(visible_anchor_range.clone())
796 .filter_map(|fold| {
797 let fold_range = fold.range.clone();
798 let display_range = fold.range.start.to_display_point(&snapshot)
799 ..fold.range.end.to_display_point(&snapshot);
800 debug_assert_eq!(display_range.start.row(), display_range.end.row());
801 let row = display_range.start.row();
802 debug_assert!(row < visible_display_row_range.end);
803 let line_layout = line_layouts
804 .get((row - visible_display_row_range.start) as usize)
805 .map(|l| &l.line)?;
806
807 let start_x = content_origin.x
808 + line_layout.x_for_index(display_range.start.column() as usize)
809 - scroll_pixel_position.x;
810 let start_y = content_origin.y + row as f32 * line_height - scroll_pixel_position.y;
811 let end_x = content_origin.x
812 + line_layout.x_for_index(display_range.end.column() as usize)
813 - scroll_pixel_position.x;
814
815 let fold_bounds = Bounds {
816 origin: point(start_x, start_y),
817 size: size(end_x - start_x, line_height),
818 };
819
820 let mut hover_element = div()
821 .id(fold.id)
822 .size_full()
823 .cursor_pointer()
824 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
825 .on_click(
826 cx.listener_for(&self.editor, move |editor: &mut Editor, _, cx| {
827 editor.unfold_ranges(
828 [fold_range.start..fold_range.end],
829 true,
830 false,
831 cx,
832 );
833 cx.stop_propagation();
834 }),
835 )
836 .into_any();
837 hover_element.layout(fold_bounds.origin, fold_bounds.size.into(), cx);
838 Some(FoldLayout {
839 display_range,
840 hover_element,
841 })
842 })
843 .collect()
844 }
845
846 #[allow(clippy::too_many_arguments)]
847 fn layout_cursors(
848 &self,
849 snapshot: &EditorSnapshot,
850 selections: &[(PlayerColor, Vec<SelectionLayout>)],
851 visible_display_row_range: Range<u32>,
852 line_layouts: &[LineWithInvisibles],
853 text_hitbox: &Hitbox,
854 content_origin: gpui::Point<Pixels>,
855 scroll_pixel_position: gpui::Point<Pixels>,
856 line_height: Pixels,
857 em_width: Pixels,
858 cx: &mut ElementContext,
859 ) -> Vec<CursorLayout> {
860 self.editor.update(cx, |editor, cx| {
861 let mut cursors = Vec::new();
862 for (player_color, selections) in selections {
863 for selection in selections {
864 let cursor_position = selection.head;
865 if (selection.is_local && !editor.show_local_cursors(cx))
866 || !visible_display_row_range.contains(&cursor_position.row())
867 {
868 continue;
869 }
870
871 let cursor_row_layout = &line_layouts
872 [(cursor_position.row() - visible_display_row_range.start) as usize]
873 .line;
874 let cursor_column = cursor_position.column() as usize;
875
876 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
877 let mut block_width =
878 cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
879 if block_width == Pixels::ZERO {
880 block_width = em_width;
881 }
882 let block_text = if let CursorShape::Block = selection.cursor_shape {
883 snapshot.display_chars_at(cursor_position).next().and_then(
884 |(character, _)| {
885 let text = if character == '\n' {
886 SharedString::from(" ")
887 } else {
888 SharedString::from(character.to_string())
889 };
890 let len = text.len();
891
892 let font = cursor_row_layout
893 .font_id_for_index(cursor_column)
894 .and_then(|cursor_font_id| {
895 cx.text_system().get_font_for_id(cursor_font_id)
896 })
897 .unwrap_or(self.style.text.font());
898
899 cx.text_system()
900 .shape_line(
901 text,
902 cursor_row_layout.font_size,
903 &[TextRun {
904 len,
905 font: font,
906 color: self.style.background,
907 background_color: None,
908 strikethrough: None,
909 underline: None,
910 }],
911 )
912 .log_err()
913 },
914 )
915 } else {
916 None
917 };
918
919 let x = cursor_character_x - scroll_pixel_position.x;
920 let y = (cursor_position.row() as f32 - scroll_pixel_position.y / line_height)
921 * line_height;
922 if selection.is_newest {
923 editor.pixel_position_of_newest_cursor = Some(point(
924 text_hitbox.origin.x + x + block_width / 2.,
925 text_hitbox.origin.y + y + line_height / 2.,
926 ))
927 }
928
929 let mut cursor = CursorLayout {
930 color: player_color.cursor,
931 block_width,
932 origin: point(x, y),
933 line_height,
934 shape: selection.cursor_shape,
935 block_text,
936 cursor_name: None,
937 };
938 let cursor_name = selection.user_name.clone().map(|name| CursorName {
939 string: name,
940 color: self.style.background,
941 is_top_row: cursor_position.row() == 0,
942 });
943 cx.with_element_context(|cx| cursor.layout(content_origin, cursor_name, cx));
944 cursors.push(cursor);
945 }
946 }
947 cursors
948 })
949 }
950
951 fn layout_scrollbar(
952 &self,
953 snapshot: &EditorSnapshot,
954 bounds: Bounds<Pixels>,
955 scroll_position: gpui::Point<f32>,
956 line_height: Pixels,
957 height_in_lines: f32,
958 cx: &mut ElementContext,
959 ) -> Option<ScrollbarLayout> {
960 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
961 let show_scrollbars = match scrollbar_settings.show {
962 ShowScrollbar::Auto => {
963 let editor = self.editor.read(cx);
964 let is_singleton = editor.is_singleton(cx);
965 // Git
966 (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_git_diffs())
967 ||
968 // Buffer Search Results
969 (is_singleton && scrollbar_settings.search_results && editor.has_background_highlights::<BufferSearchHighlights>())
970 ||
971 // Selected Symbol Occurrences
972 (is_singleton && scrollbar_settings.selected_symbol && (editor.has_background_highlights::<DocumentHighlightRead>() || editor.has_background_highlights::<DocumentHighlightWrite>()))
973 ||
974 // Diagnostics
975 (is_singleton && scrollbar_settings.diagnostics && snapshot.buffer_snapshot.has_diagnostics())
976 ||
977 // Scrollmanager
978 editor.scroll_manager.scrollbars_visible()
979 }
980 ShowScrollbar::System => self.editor.read(cx).scroll_manager.scrollbars_visible(),
981 ShowScrollbar::Always => true,
982 ShowScrollbar::Never => false,
983 };
984 if snapshot.mode != EditorMode::Full {
985 return None;
986 }
987
988 let visible_row_range = scroll_position.y..scroll_position.y + height_in_lines;
989
990 // If a drag took place after we started dragging the scrollbar,
991 // cancel the scrollbar drag.
992 if cx.has_active_drag() {
993 self.editor.update(cx, |editor, cx| {
994 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
995 });
996 }
997
998 let track_bounds = Bounds::from_corners(
999 point(self.scrollbar_left(&bounds), bounds.origin.y),
1000 point(bounds.lower_right().x, bounds.lower_left().y),
1001 );
1002
1003 let scroll_height = snapshot.max_point().row() as f32 + height_in_lines;
1004 let mut height = bounds.size.height;
1005 let mut first_row_y_offset = px(0.0);
1006
1007 // Impose a minimum height on the scrollbar thumb
1008 let row_height = height / scroll_height;
1009 let min_thumb_height = line_height;
1010 let thumb_height = height_in_lines * row_height;
1011 if thumb_height < min_thumb_height {
1012 first_row_y_offset = (min_thumb_height - thumb_height) / 2.0;
1013 height -= min_thumb_height - thumb_height;
1014 }
1015
1016 Some(ScrollbarLayout {
1017 hitbox: cx.insert_hitbox(track_bounds, false),
1018 visible_row_range,
1019 height,
1020 scroll_height,
1021 first_row_y_offset,
1022 row_height,
1023 visible: show_scrollbars,
1024 })
1025 }
1026
1027 #[allow(clippy::too_many_arguments)]
1028 fn layout_gutter_fold_indicators(
1029 &self,
1030 fold_statuses: Vec<Option<(FoldStatus, u32, bool)>>,
1031 line_height: Pixels,
1032 gutter_dimensions: &GutterDimensions,
1033 gutter_settings: crate::editor_settings::Gutter,
1034 scroll_pixel_position: gpui::Point<Pixels>,
1035 gutter_hitbox: &Hitbox,
1036 cx: &mut ElementContext,
1037 ) -> Vec<Option<AnyElement>> {
1038 let mut indicators = self.editor.update(cx, |editor, cx| {
1039 editor.render_fold_indicators(
1040 fold_statuses,
1041 &self.style,
1042 editor.gutter_hovered,
1043 line_height,
1044 gutter_dimensions.margin,
1045 cx,
1046 )
1047 });
1048
1049 for (ix, fold_indicator) in indicators.iter_mut().enumerate() {
1050 if let Some(fold_indicator) = fold_indicator {
1051 debug_assert!(gutter_settings.folds);
1052 let available_space = size(
1053 AvailableSpace::MinContent,
1054 AvailableSpace::Definite(line_height * 0.55),
1055 );
1056 let fold_indicator_size = fold_indicator.measure(available_space, cx);
1057
1058 let position = point(
1059 gutter_dimensions.width - gutter_dimensions.right_padding,
1060 ix as f32 * line_height - (scroll_pixel_position.y % line_height),
1061 );
1062 let centering_offset = point(
1063 (gutter_dimensions.right_padding + gutter_dimensions.margin
1064 - fold_indicator_size.width)
1065 / 2.,
1066 (line_height - fold_indicator_size.height) / 2.,
1067 );
1068 let origin = gutter_hitbox.origin + position + centering_offset;
1069 fold_indicator.layout(origin, available_space, cx);
1070 }
1071 }
1072
1073 indicators
1074 }
1075
1076 //Folds contained in a hunk are ignored apart from shrinking visual size
1077 //If a fold contains any hunks then that fold line is marked as modified
1078 fn layout_git_gutters(
1079 &self,
1080 display_rows: Range<u32>,
1081 snapshot: &EditorSnapshot,
1082 ) -> Vec<DisplayDiffHunk> {
1083 let buffer_snapshot = &snapshot.buffer_snapshot;
1084
1085 let buffer_start_row = DisplayPoint::new(display_rows.start, 0)
1086 .to_point(snapshot)
1087 .row;
1088 let buffer_end_row = DisplayPoint::new(display_rows.end, 0)
1089 .to_point(snapshot)
1090 .row;
1091
1092 buffer_snapshot
1093 .git_diff_hunks_in_range(buffer_start_row..buffer_end_row)
1094 .map(|hunk| diff_hunk_to_display(hunk, snapshot))
1095 .dedup()
1096 .collect()
1097 }
1098
1099 #[allow(clippy::too_many_arguments)]
1100 fn layout_inline_blame(
1101 &self,
1102 display_row: u32,
1103 display_snapshot: &DisplaySnapshot,
1104 line_layout: &LineWithInvisibles,
1105 em_width: Pixels,
1106 content_origin: gpui::Point<Pixels>,
1107 scroll_pixel_position: gpui::Point<Pixels>,
1108 line_height: Pixels,
1109 cx: &mut ElementContext,
1110 ) -> Option<AnyElement> {
1111 if !self
1112 .editor
1113 .update(cx, |editor, cx| editor.render_git_blame_inline(cx))
1114 {
1115 return None;
1116 }
1117
1118 let workspace = self
1119 .editor
1120 .read(cx)
1121 .workspace
1122 .as_ref()
1123 .map(|(w, _)| w.clone());
1124
1125 let display_point = DisplayPoint::new(display_row, 0);
1126 let buffer_row = display_point.to_point(display_snapshot).row;
1127
1128 let blame = self.editor.read(cx).blame.clone()?;
1129 let blame_entry = blame
1130 .update(cx, |blame, cx| {
1131 blame.blame_for_rows([Some(buffer_row)], cx).next()
1132 })
1133 .flatten()?;
1134
1135 let mut element =
1136 render_inline_blame_entry(&blame, blame_entry, &self.style, workspace, cx);
1137
1138 let start_y = content_origin.y
1139 + line_height * (display_row as f32 - scroll_pixel_position.y / line_height);
1140
1141 let start_x = {
1142 const INLINE_BLAME_PADDING_EM_WIDTHS: f32 = 6.;
1143
1144 let line_width = line_layout.line.width;
1145 content_origin.x + line_width + (em_width * INLINE_BLAME_PADDING_EM_WIDTHS)
1146 };
1147
1148 let absolute_offset = point(start_x, start_y);
1149 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1150
1151 element.layout(absolute_offset, available_space, cx);
1152
1153 Some(element)
1154 }
1155
1156 #[allow(clippy::too_many_arguments)]
1157 fn layout_blame_entries(
1158 &self,
1159 buffer_rows: impl Iterator<Item = Option<u32>>,
1160 em_width: Pixels,
1161 scroll_position: gpui::Point<f32>,
1162 line_height: Pixels,
1163 gutter_hitbox: &Hitbox,
1164 max_width: Option<Pixels>,
1165 cx: &mut ElementContext,
1166 ) -> Option<Vec<AnyElement>> {
1167 if !self
1168 .editor
1169 .update(cx, |editor, cx| editor.render_git_blame_gutter(cx))
1170 {
1171 return None;
1172 }
1173
1174 let blame = self.editor.read(cx).blame.clone()?;
1175 let blamed_rows: Vec<_> = blame.update(cx, |blame, cx| {
1176 blame.blame_for_rows(buffer_rows, cx).collect()
1177 });
1178
1179 let width = if let Some(max_width) = max_width {
1180 AvailableSpace::Definite(max_width)
1181 } else {
1182 AvailableSpace::MaxContent
1183 };
1184 let scroll_top = scroll_position.y * line_height;
1185 let start_x = em_width * 1;
1186
1187 let mut last_used_color: Option<(PlayerColor, Oid)> = None;
1188
1189 let shaped_lines = blamed_rows
1190 .into_iter()
1191 .enumerate()
1192 .flat_map(|(ix, blame_entry)| {
1193 if let Some(blame_entry) = blame_entry {
1194 let mut element = render_blame_entry(
1195 ix,
1196 &blame,
1197 blame_entry,
1198 &self.style,
1199 &mut last_used_color,
1200 self.editor.clone(),
1201 cx,
1202 );
1203
1204 let start_y = ix as f32 * line_height - (scroll_top % line_height);
1205 let absolute_offset = gutter_hitbox.origin + point(start_x, start_y);
1206
1207 element.layout(absolute_offset, size(width, AvailableSpace::MinContent), cx);
1208
1209 Some(element)
1210 } else {
1211 None
1212 }
1213 })
1214 .collect();
1215
1216 Some(shaped_lines)
1217 }
1218
1219 fn layout_code_actions_indicator(
1220 &self,
1221 line_height: Pixels,
1222 newest_selection_head: DisplayPoint,
1223 scroll_pixel_position: gpui::Point<Pixels>,
1224 gutter_dimensions: &GutterDimensions,
1225 gutter_hitbox: &Hitbox,
1226 cx: &mut ElementContext,
1227 ) -> Option<AnyElement> {
1228 let mut active = false;
1229 let mut button = None;
1230 self.editor.update(cx, |editor, cx| {
1231 active = matches!(
1232 editor.context_menu.read().as_ref(),
1233 Some(crate::ContextMenu::CodeActions(_))
1234 );
1235 button = editor.render_code_actions_indicator(&self.style, active, cx);
1236 });
1237
1238 let mut button = button?.into_any_element();
1239 let available_space = size(
1240 AvailableSpace::MinContent,
1241 AvailableSpace::Definite(line_height),
1242 );
1243 let indicator_size = button.measure(available_space, cx);
1244
1245 let blame_width = gutter_dimensions
1246 .git_blame_entries_width
1247 .unwrap_or(Pixels::ZERO);
1248
1249 let mut x = blame_width;
1250 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
1251 - indicator_size.width
1252 - blame_width;
1253 x += available_width / 2.;
1254
1255 let mut y = newest_selection_head.row() as f32 * line_height - scroll_pixel_position.y;
1256 y += (line_height - indicator_size.height) / 2.;
1257
1258 button.layout(gutter_hitbox.origin + point(x, y), available_space, cx);
1259 Some(button)
1260 }
1261
1262 fn calculate_relative_line_numbers(
1263 &self,
1264 snapshot: &EditorSnapshot,
1265 rows: &Range<u32>,
1266 relative_to: Option<u32>,
1267 ) -> HashMap<u32, u32> {
1268 let mut relative_rows: HashMap<u32, u32> = Default::default();
1269 let Some(relative_to) = relative_to else {
1270 return relative_rows;
1271 };
1272
1273 let start = rows.start.min(relative_to);
1274 let end = rows.end.max(relative_to);
1275
1276 let buffer_rows = snapshot
1277 .buffer_rows(start)
1278 .take(1 + (end - start) as usize)
1279 .collect::<Vec<_>>();
1280
1281 let head_idx = relative_to - start;
1282 let mut delta = 1;
1283 let mut i = head_idx + 1;
1284 while i < buffer_rows.len() as u32 {
1285 if buffer_rows[i as usize].is_some() {
1286 if rows.contains(&(i + start)) {
1287 relative_rows.insert(i + start, delta);
1288 }
1289 delta += 1;
1290 }
1291 i += 1;
1292 }
1293 delta = 1;
1294 i = head_idx.min(buffer_rows.len() as u32 - 1);
1295 while i > 0 && buffer_rows[i as usize].is_none() {
1296 i -= 1;
1297 }
1298
1299 while i > 0 {
1300 i -= 1;
1301 if buffer_rows[i as usize].is_some() {
1302 if rows.contains(&(i + start)) {
1303 relative_rows.insert(i + start, delta);
1304 }
1305 delta += 1;
1306 }
1307 }
1308
1309 relative_rows
1310 }
1311
1312 fn layout_line_numbers(
1313 &self,
1314 rows: Range<u32>,
1315 buffer_rows: impl Iterator<Item = Option<u32>>,
1316 active_rows: &BTreeMap<u32, bool>,
1317 newest_selection_head: Option<DisplayPoint>,
1318 snapshot: &EditorSnapshot,
1319 cx: &ElementContext,
1320 ) -> (
1321 Vec<Option<ShapedLine>>,
1322 Vec<Option<(FoldStatus, BufferRow, bool)>>,
1323 ) {
1324 let editor = self.editor.read(cx);
1325 let is_singleton = editor.is_singleton(cx);
1326 let newest_selection_head = newest_selection_head.unwrap_or_else(|| {
1327 let newest = editor.selections.newest::<Point>(cx);
1328 SelectionLayout::new(
1329 newest,
1330 editor.selections.line_mode,
1331 editor.cursor_shape,
1332 &snapshot.display_snapshot,
1333 true,
1334 true,
1335 None,
1336 )
1337 .head
1338 });
1339 let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1340 let include_line_numbers =
1341 EditorSettings::get_global(cx).gutter.line_numbers && snapshot.mode == EditorMode::Full;
1342 let include_fold_statuses =
1343 EditorSettings::get_global(cx).gutter.folds && snapshot.mode == EditorMode::Full;
1344 let mut shaped_line_numbers = Vec::with_capacity(rows.len());
1345 let mut fold_statuses = Vec::with_capacity(rows.len());
1346 let mut line_number = String::new();
1347 let is_relative = EditorSettings::get_global(cx).relative_line_numbers;
1348 let relative_to = if is_relative {
1349 Some(newest_selection_head.row())
1350 } else {
1351 None
1352 };
1353
1354 let relative_rows = self.calculate_relative_line_numbers(snapshot, &rows, relative_to);
1355
1356 for (ix, row) in buffer_rows.into_iter().enumerate() {
1357 let display_row = rows.start + ix as u32;
1358 let (active, color) = if active_rows.contains_key(&display_row) {
1359 (true, cx.theme().colors().editor_active_line_number)
1360 } else {
1361 (false, cx.theme().colors().editor_line_number)
1362 };
1363 if let Some(buffer_row) = row {
1364 if include_line_numbers {
1365 line_number.clear();
1366 let default_number = buffer_row + 1;
1367 let number = relative_rows
1368 .get(&(ix as u32 + rows.start))
1369 .unwrap_or(&default_number);
1370 write!(&mut line_number, "{}", number).unwrap();
1371 let run = TextRun {
1372 len: line_number.len(),
1373 font: self.style.text.font(),
1374 color,
1375 background_color: None,
1376 underline: None,
1377 strikethrough: None,
1378 };
1379 let shaped_line = cx
1380 .text_system()
1381 .shape_line(line_number.clone().into(), font_size, &[run])
1382 .unwrap();
1383 shaped_line_numbers.push(Some(shaped_line));
1384 }
1385 if include_fold_statuses {
1386 fold_statuses.push(
1387 is_singleton
1388 .then(|| {
1389 snapshot
1390 .fold_for_line(buffer_row)
1391 .map(|fold_status| (fold_status, buffer_row, active))
1392 })
1393 .flatten(),
1394 )
1395 }
1396 } else {
1397 fold_statuses.push(None);
1398 shaped_line_numbers.push(None);
1399 }
1400 }
1401
1402 (shaped_line_numbers, fold_statuses)
1403 }
1404
1405 fn layout_lines(
1406 &self,
1407 rows: Range<u32>,
1408 line_number_layouts: &[Option<ShapedLine>],
1409 snapshot: &EditorSnapshot,
1410 cx: &ElementContext,
1411 ) -> Vec<LineWithInvisibles> {
1412 if rows.start >= rows.end {
1413 return Vec::new();
1414 }
1415
1416 // Show the placeholder when the editor is empty
1417 if snapshot.is_empty() {
1418 let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1419 let placeholder_color = cx.theme().colors().text_placeholder;
1420 let placeholder_text = snapshot.placeholder_text();
1421
1422 let placeholder_lines = placeholder_text
1423 .as_ref()
1424 .map_or("", AsRef::as_ref)
1425 .split('\n')
1426 .skip(rows.start as usize)
1427 .chain(iter::repeat(""))
1428 .take(rows.len());
1429 placeholder_lines
1430 .filter_map(move |line| {
1431 let run = TextRun {
1432 len: line.len(),
1433 font: self.style.text.font(),
1434 color: placeholder_color,
1435 background_color: None,
1436 underline: Default::default(),
1437 strikethrough: None,
1438 };
1439 cx.text_system()
1440 .shape_line(line.to_string().into(), font_size, &[run])
1441 .log_err()
1442 })
1443 .map(|line| LineWithInvisibles {
1444 line,
1445 invisibles: Vec::new(),
1446 })
1447 .collect()
1448 } else {
1449 let chunks = snapshot.highlighted_chunks(rows.clone(), true, &self.style);
1450 LineWithInvisibles::from_chunks(
1451 chunks,
1452 &self.style.text,
1453 MAX_LINE_LEN,
1454 rows.len(),
1455 line_number_layouts,
1456 snapshot.mode,
1457 cx,
1458 )
1459 }
1460 }
1461
1462 #[allow(clippy::too_many_arguments)]
1463 fn build_blocks(
1464 &self,
1465 rows: Range<u32>,
1466 snapshot: &EditorSnapshot,
1467 hitbox: &Hitbox,
1468 text_hitbox: &Hitbox,
1469 scroll_width: &mut Pixels,
1470 gutter_dimensions: &GutterDimensions,
1471 em_width: Pixels,
1472 text_x: Pixels,
1473 line_height: Pixels,
1474 line_layouts: &[LineWithInvisibles],
1475 cx: &mut ElementContext,
1476 ) -> Vec<BlockLayout> {
1477 let mut block_id = 0;
1478 let (fixed_blocks, non_fixed_blocks) = snapshot
1479 .blocks_in_range(rows.clone())
1480 .partition::<Vec<_>, _>(|(_, block)| match block {
1481 TransformBlock::ExcerptHeader { .. } => false,
1482 TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
1483 });
1484
1485 let render_block = |block: &TransformBlock,
1486 available_space: Size<AvailableSpace>,
1487 block_id: usize,
1488 block_row_start: u32,
1489 cx: &mut ElementContext| {
1490 let mut element = match block {
1491 TransformBlock::Custom(block) => {
1492 let align_to = block
1493 .position()
1494 .to_point(&snapshot.buffer_snapshot)
1495 .to_display_point(snapshot);
1496 let anchor_x = text_x
1497 + if rows.contains(&align_to.row()) {
1498 line_layouts[(align_to.row() - rows.start) as usize]
1499 .line
1500 .x_for_index(align_to.column() as usize)
1501 } else {
1502 layout_line(align_to.row(), snapshot, &self.style, cx)
1503 .unwrap()
1504 .x_for_index(align_to.column() as usize)
1505 };
1506
1507 block.render(&mut BlockContext {
1508 context: cx,
1509 anchor_x,
1510 gutter_dimensions,
1511 line_height,
1512 em_width,
1513 block_id,
1514 max_width: text_hitbox.size.width.max(*scroll_width),
1515 editor_style: &self.style,
1516 })
1517 }
1518
1519 TransformBlock::ExcerptHeader {
1520 buffer,
1521 range,
1522 starts_new_buffer,
1523 height,
1524 ..
1525 } => {
1526 let include_root = self
1527 .editor
1528 .read(cx)
1529 .project
1530 .as_ref()
1531 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
1532 .unwrap_or_default();
1533
1534 #[derive(Clone)]
1535 struct JumpData {
1536 position: Point,
1537 anchor: text::Anchor,
1538 path: ProjectPath,
1539 line_offset_from_top: u32,
1540 }
1541
1542 let jump_data = project::File::from_dyn(buffer.file()).map(|file| {
1543 let jump_path = ProjectPath {
1544 worktree_id: file.worktree_id(cx),
1545 path: file.path.clone(),
1546 };
1547 let jump_anchor = range
1548 .primary
1549 .as_ref()
1550 .map_or(range.context.start, |primary| primary.start);
1551
1552 let excerpt_start = range.context.start;
1553 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
1554 let offset_from_excerpt_start = if jump_anchor == excerpt_start {
1555 0
1556 } else {
1557 let excerpt_start_row =
1558 language::ToPoint::to_point(&jump_anchor, buffer).row;
1559 jump_position.row - excerpt_start_row
1560 };
1561
1562 let line_offset_from_top =
1563 block_row_start + *height as u32 + offset_from_excerpt_start
1564 - snapshot
1565 .scroll_anchor
1566 .scroll_position(&snapshot.display_snapshot)
1567 .y as u32;
1568
1569 JumpData {
1570 position: jump_position,
1571 anchor: jump_anchor,
1572 path: jump_path,
1573 line_offset_from_top,
1574 }
1575 });
1576
1577 let element = if *starts_new_buffer {
1578 let path = buffer.resolve_file_path(cx, include_root);
1579 let mut filename = None;
1580 let mut parent_path = None;
1581 // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
1582 if let Some(path) = path {
1583 filename = path.file_name().map(|f| f.to_string_lossy().to_string());
1584 parent_path = path
1585 .parent()
1586 .map(|p| SharedString::from(p.to_string_lossy().to_string() + "/"));
1587 }
1588
1589 v_flex()
1590 .id(("path header container", block_id))
1591 .size_full()
1592 .justify_center()
1593 .p(gpui::px(6.))
1594 .child(
1595 h_flex()
1596 .id("path header block")
1597 .size_full()
1598 .pl(gpui::px(12.))
1599 .pr(gpui::px(8.))
1600 .rounded_md()
1601 .shadow_md()
1602 .border()
1603 .border_color(cx.theme().colors().border)
1604 .bg(cx.theme().colors().editor_subheader_background)
1605 .justify_between()
1606 .hover(|style| style.bg(cx.theme().colors().element_hover))
1607 .child(
1608 h_flex().gap_3().child(
1609 h_flex()
1610 .gap_2()
1611 .child(
1612 filename
1613 .map(SharedString::from)
1614 .unwrap_or_else(|| "untitled".into()),
1615 )
1616 .when_some(parent_path, |then, path| {
1617 then.child(
1618 div().child(path).text_color(
1619 cx.theme().colors().text_muted,
1620 ),
1621 )
1622 }),
1623 ),
1624 )
1625 .when_some(jump_data.clone(), |this, jump_data| {
1626 this.cursor_pointer()
1627 .tooltip(|cx| {
1628 Tooltip::for_action(
1629 "Jump to File",
1630 &OpenExcerpts,
1631 cx,
1632 )
1633 })
1634 .on_mouse_down(MouseButton::Left, |_, cx| {
1635 cx.stop_propagation()
1636 })
1637 .on_click(cx.listener_for(&self.editor, {
1638 move |editor, _, cx| {
1639 editor.jump(
1640 jump_data.path.clone(),
1641 jump_data.position,
1642 jump_data.anchor,
1643 jump_data.line_offset_from_top,
1644 cx,
1645 );
1646 }
1647 }))
1648 }),
1649 )
1650 } else {
1651 v_flex()
1652 .id(("collapsed context", block_id))
1653 .size_full()
1654 .child(
1655 div()
1656 .flex()
1657 .v_flex()
1658 .justify_start()
1659 .id("jump to collapsed context")
1660 .w(relative(1.0))
1661 .h_full()
1662 .child(
1663 div()
1664 .h_px()
1665 .w_full()
1666 .bg(cx.theme().colors().border_variant)
1667 .group_hover("excerpt-jump-action", |style| {
1668 style.bg(cx.theme().colors().border)
1669 }),
1670 ),
1671 )
1672 .child(
1673 h_flex()
1674 .justify_end()
1675 .flex_none()
1676 .w(
1677 gutter_dimensions.width - (gutter_dimensions.left_padding), // + gutter_dimensions.right_padding)
1678 )
1679 .h_full()
1680 .child(
1681 ButtonLike::new("jump-icon")
1682 .style(ButtonStyle::Transparent)
1683 .child(
1684 svg()
1685 .path(IconName::ArrowUpRight.path())
1686 .size(IconSize::XSmall.rems())
1687 .text_color(cx.theme().colors().border)
1688 .group_hover("excerpt-jump-action", |style| {
1689 style.text_color(
1690 cx.theme().colors().editor_line_number,
1691 )
1692 }),
1693 )
1694 .when_some(jump_data.clone(), |this, jump_data| {
1695 this.on_click(cx.listener_for(&self.editor, {
1696 let path = jump_data.path.clone();
1697 move |editor, _, cx| {
1698 editor.jump(
1699 path.clone(),
1700 jump_data.position,
1701 jump_data.anchor,
1702 jump_data.line_offset_from_top,
1703 cx,
1704 );
1705 }
1706 }))
1707 .tooltip({
1708 move |cx| {
1709 Tooltip::for_action(
1710 format!(
1711 "Jump to {}:L{}",
1712 jump_data.path.path.display(),
1713 jump_data.position.row + 1
1714 ),
1715 &OpenExcerpts,
1716 cx,
1717 )
1718 }
1719 })
1720 }),
1721 ),
1722 )
1723 .group("excerpt-jump-action")
1724 .cursor_pointer()
1725 .when_some(jump_data.clone(), |this, jump_data| {
1726 this.on_click(cx.listener_for(&self.editor, {
1727 let path = jump_data.path.clone();
1728 move |editor, _, cx| {
1729 cx.stop_propagation();
1730
1731 editor.jump(
1732 path.clone(),
1733 jump_data.position,
1734 jump_data.anchor,
1735 jump_data.line_offset_from_top,
1736 cx,
1737 );
1738 }
1739 }))
1740 .tooltip(move |cx| {
1741 Tooltip::for_action(
1742 format!(
1743 "Jump to {}:L{}",
1744 jump_data.path.path.display(),
1745 jump_data.position.row + 1
1746 ),
1747 &OpenExcerpts,
1748 cx,
1749 )
1750 })
1751 })
1752 };
1753 element.into_any()
1754 }
1755 };
1756
1757 let size = element.measure(available_space, cx);
1758 (element, size)
1759 };
1760
1761 let mut fixed_block_max_width = Pixels::ZERO;
1762 let mut blocks = Vec::new();
1763 for (row, block) in fixed_blocks {
1764 let available_space = size(
1765 AvailableSpace::MinContent,
1766 AvailableSpace::Definite(block.height() as f32 * line_height),
1767 );
1768 let (element, element_size) = render_block(block, available_space, block_id, row, cx);
1769 block_id += 1;
1770 fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
1771 blocks.push(BlockLayout {
1772 row,
1773 element,
1774 available_space,
1775 style: BlockStyle::Fixed,
1776 });
1777 }
1778 for (row, block) in non_fixed_blocks {
1779 let style = match block {
1780 TransformBlock::Custom(block) => block.style(),
1781 TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
1782 };
1783 let width = match style {
1784 BlockStyle::Sticky => hitbox.size.width,
1785 BlockStyle::Flex => hitbox
1786 .size
1787 .width
1788 .max(fixed_block_max_width)
1789 .max(gutter_dimensions.width + *scroll_width),
1790 BlockStyle::Fixed => unreachable!(),
1791 };
1792 let available_space = size(
1793 AvailableSpace::Definite(width),
1794 AvailableSpace::Definite(block.height() as f32 * line_height),
1795 );
1796 let (element, _) = render_block(block, available_space, block_id, row, cx);
1797 block_id += 1;
1798 blocks.push(BlockLayout {
1799 row,
1800 element,
1801 available_space,
1802 style,
1803 });
1804 }
1805
1806 *scroll_width = (*scroll_width).max(fixed_block_max_width - gutter_dimensions.width);
1807 blocks
1808 }
1809
1810 fn layout_blocks(
1811 &self,
1812 blocks: &mut Vec<BlockLayout>,
1813 hitbox: &Hitbox,
1814 line_height: Pixels,
1815 scroll_pixel_position: gpui::Point<Pixels>,
1816 cx: &mut ElementContext,
1817 ) {
1818 for block in blocks {
1819 let mut origin = hitbox.origin
1820 + point(
1821 Pixels::ZERO,
1822 block.row as f32 * line_height - scroll_pixel_position.y,
1823 );
1824 if !matches!(block.style, BlockStyle::Sticky) {
1825 origin += point(-scroll_pixel_position.x, Pixels::ZERO);
1826 }
1827 block.element.layout(origin, block.available_space, cx);
1828 }
1829 }
1830
1831 #[allow(clippy::too_many_arguments)]
1832 fn layout_context_menu(
1833 &self,
1834 line_height: Pixels,
1835 hitbox: &Hitbox,
1836 text_hitbox: &Hitbox,
1837 content_origin: gpui::Point<Pixels>,
1838 start_row: u32,
1839 scroll_pixel_position: gpui::Point<Pixels>,
1840 line_layouts: &[LineWithInvisibles],
1841 newest_selection_head: DisplayPoint,
1842 cx: &mut ElementContext,
1843 ) -> bool {
1844 let max_height = cmp::min(
1845 12. * line_height,
1846 cmp::max(3. * line_height, (hitbox.size.height - line_height) / 2.),
1847 );
1848 let Some((position, mut context_menu)) = self.editor.update(cx, |editor, cx| {
1849 if editor.context_menu_visible() {
1850 editor.render_context_menu(newest_selection_head, &self.style, max_height, cx)
1851 } else {
1852 None
1853 }
1854 }) else {
1855 return false;
1856 };
1857
1858 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1859 let context_menu_size = context_menu.measure(available_space, cx);
1860
1861 let cursor_row_layout = &line_layouts[(position.row() - start_row) as usize].line;
1862 let x = cursor_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
1863 let y = (position.row() + 1) as f32 * line_height - scroll_pixel_position.y;
1864 let mut list_origin = content_origin + point(x, y);
1865 let list_width = context_menu_size.width;
1866 let list_height = context_menu_size.height;
1867
1868 // Snap the right edge of the list to the right edge of the window if
1869 // its horizontal bounds overflow.
1870 if list_origin.x + list_width > cx.viewport_size().width {
1871 list_origin.x = (cx.viewport_size().width - list_width).max(Pixels::ZERO);
1872 }
1873
1874 if list_origin.y + list_height > text_hitbox.lower_right().y {
1875 list_origin.y -= line_height + list_height;
1876 }
1877
1878 cx.defer_draw(context_menu, list_origin, 1);
1879 true
1880 }
1881
1882 fn layout_mouse_context_menu(&self, cx: &mut ElementContext) -> Option<AnyElement> {
1883 let mouse_context_menu = self.editor.read(cx).mouse_context_menu.as_ref()?;
1884 let mut element = deferred(
1885 anchored()
1886 .position(mouse_context_menu.position)
1887 .child(mouse_context_menu.context_menu.clone())
1888 .anchor(AnchorCorner::TopLeft)
1889 .snap_to_window(),
1890 )
1891 .with_priority(1)
1892 .into_any();
1893
1894 element.layout(gpui::Point::default(), AvailableSpace::min_size(), cx);
1895 Some(element)
1896 }
1897
1898 #[allow(clippy::too_many_arguments)]
1899 fn layout_hover_popovers(
1900 &self,
1901 snapshot: &EditorSnapshot,
1902 hitbox: &Hitbox,
1903 text_hitbox: &Hitbox,
1904 visible_display_row_range: Range<u32>,
1905 content_origin: gpui::Point<Pixels>,
1906 scroll_pixel_position: gpui::Point<Pixels>,
1907 line_layouts: &[LineWithInvisibles],
1908 line_height: Pixels,
1909 em_width: Pixels,
1910 cx: &mut ElementContext,
1911 ) {
1912 struct MeasuredHoverPopover {
1913 element: AnyElement,
1914 size: Size<Pixels>,
1915 horizontal_offset: Pixels,
1916 }
1917
1918 let max_size = size(
1919 (120. * em_width) // Default size
1920 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
1921 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
1922 (16. * line_height) // Default size
1923 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
1924 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
1925 );
1926
1927 let hover_popovers = self.editor.update(cx, |editor, cx| {
1928 editor.hover_state.render(
1929 &snapshot,
1930 &self.style,
1931 visible_display_row_range.clone(),
1932 max_size,
1933 editor.workspace.as_ref().map(|(w, _)| w.clone()),
1934 cx,
1935 )
1936 });
1937 let Some((position, hover_popovers)) = hover_popovers else {
1938 return;
1939 };
1940
1941 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1942
1943 // This is safe because we check on layout whether the required row is available
1944 let hovered_row_layout =
1945 &line_layouts[(position.row() - visible_display_row_range.start) as usize].line;
1946
1947 // Compute Hovered Point
1948 let x =
1949 hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
1950 let y = position.row() as f32 * line_height - scroll_pixel_position.y;
1951 let hovered_point = content_origin + point(x, y);
1952
1953 let mut overall_height = Pixels::ZERO;
1954 let mut measured_hover_popovers = Vec::new();
1955 for mut hover_popover in hover_popovers {
1956 let size = hover_popover.measure(available_space, cx);
1957 let horizontal_offset =
1958 (text_hitbox.upper_right().x - (hovered_point.x + size.width)).min(Pixels::ZERO);
1959
1960 overall_height += HOVER_POPOVER_GAP + size.height;
1961
1962 measured_hover_popovers.push(MeasuredHoverPopover {
1963 element: hover_popover,
1964 size,
1965 horizontal_offset,
1966 });
1967 }
1968 overall_height += HOVER_POPOVER_GAP;
1969
1970 fn draw_occluder(width: Pixels, origin: gpui::Point<Pixels>, cx: &mut ElementContext) {
1971 let mut occlusion = div()
1972 .size_full()
1973 .occlude()
1974 .on_mouse_move(|_, cx| cx.stop_propagation())
1975 .into_any_element();
1976 occlusion.measure(size(width, HOVER_POPOVER_GAP).into(), cx);
1977 cx.defer_draw(occlusion, origin, 2);
1978 }
1979
1980 if hovered_point.y > overall_height {
1981 // There is enough space above. Render popovers above the hovered point
1982 let mut current_y = hovered_point.y;
1983 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
1984 let size = popover.size;
1985 let popover_origin = point(
1986 hovered_point.x + popover.horizontal_offset,
1987 current_y - size.height,
1988 );
1989
1990 cx.defer_draw(popover.element, popover_origin, 2);
1991 if position != itertools::Position::Last {
1992 let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
1993 draw_occluder(size.width, origin, cx);
1994 }
1995
1996 current_y = popover_origin.y - HOVER_POPOVER_GAP;
1997 }
1998 } else {
1999 // There is not enough space above. Render popovers below the hovered point
2000 let mut current_y = hovered_point.y + line_height;
2001 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
2002 let size = popover.size;
2003 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
2004
2005 cx.defer_draw(popover.element, popover_origin, 2);
2006 if position != itertools::Position::Last {
2007 let origin = point(popover_origin.x, popover_origin.y + size.height);
2008 draw_occluder(size.width, origin, cx);
2009 }
2010
2011 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
2012 }
2013 }
2014 }
2015
2016 fn paint_background(&self, layout: &EditorLayout, cx: &mut ElementContext) {
2017 cx.paint_layer(layout.hitbox.bounds, |cx| {
2018 let scroll_top = layout.position_map.snapshot.scroll_position().y;
2019 let gutter_bg = cx.theme().colors().editor_gutter_background;
2020 cx.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
2021 cx.paint_quad(fill(layout.text_hitbox.bounds, self.style.background));
2022
2023 if let EditorMode::Full = layout.mode {
2024 let mut active_rows = layout.active_rows.iter().peekable();
2025 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
2026 let mut end_row = *start_row;
2027 while active_rows.peek().map_or(false, |r| {
2028 *r.0 == end_row + 1 && r.1 == contains_non_empty_selection
2029 }) {
2030 active_rows.next().unwrap();
2031 end_row += 1;
2032 }
2033
2034 if !contains_non_empty_selection {
2035 let origin = point(
2036 layout.hitbox.origin.x,
2037 layout.hitbox.origin.y
2038 + (*start_row as f32 - scroll_top)
2039 * layout.position_map.line_height,
2040 );
2041 let size = size(
2042 layout.hitbox.size.width,
2043 layout.position_map.line_height * (end_row - start_row + 1) as f32,
2044 );
2045 let active_line_bg = cx.theme().colors().editor_active_line_background;
2046 cx.paint_quad(fill(Bounds { origin, size }, active_line_bg));
2047 }
2048 }
2049
2050 let mut paint_highlight =
2051 |highlight_row_start: u32, highlight_row_end: u32, color| {
2052 let origin = point(
2053 layout.hitbox.origin.x,
2054 layout.hitbox.origin.y
2055 + (highlight_row_start as f32 - scroll_top)
2056 * layout.position_map.line_height,
2057 );
2058 let size = size(
2059 layout.hitbox.size.width,
2060 layout.position_map.line_height
2061 * (highlight_row_end + 1 - highlight_row_start) as f32,
2062 );
2063 cx.paint_quad(fill(Bounds { origin, size }, color));
2064 };
2065
2066 let mut last_row = None;
2067 let mut highlight_row_start = 0u32;
2068 let mut highlight_row_end = 0u32;
2069 for (&row, &color) in &layout.highlighted_rows {
2070 let paint = last_row.map_or(false, |(last_row, last_color)| {
2071 last_color != color || last_row + 1 < row
2072 });
2073
2074 if paint {
2075 let paint_range_is_unfinished = highlight_row_end == 0;
2076 if paint_range_is_unfinished {
2077 highlight_row_end = row;
2078 last_row = None;
2079 }
2080 paint_highlight(highlight_row_start, highlight_row_end, color);
2081 highlight_row_start = 0;
2082 highlight_row_end = 0;
2083 if !paint_range_is_unfinished {
2084 highlight_row_start = row;
2085 last_row = Some((row, color));
2086 }
2087 } else {
2088 if last_row.is_none() {
2089 highlight_row_start = row;
2090 } else {
2091 highlight_row_end = row;
2092 }
2093 last_row = Some((row, color));
2094 }
2095 }
2096 if let Some((row, hsla)) = last_row {
2097 highlight_row_end = row;
2098 paint_highlight(highlight_row_start, highlight_row_end, hsla);
2099 }
2100
2101 let scroll_left =
2102 layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
2103
2104 for (wrap_position, active) in layout.wrap_guides.iter() {
2105 let x = (layout.text_hitbox.origin.x
2106 + *wrap_position
2107 + layout.position_map.em_width / 2.)
2108 - scroll_left;
2109
2110 let show_scrollbars = layout
2111 .scrollbar_layout
2112 .as_ref()
2113 .map_or(false, |scrollbar| scrollbar.visible);
2114 if x < layout.text_hitbox.origin.x
2115 || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
2116 {
2117 continue;
2118 }
2119
2120 let color = if *active {
2121 cx.theme().colors().editor_active_wrap_guide
2122 } else {
2123 cx.theme().colors().editor_wrap_guide
2124 };
2125 cx.paint_quad(fill(
2126 Bounds {
2127 origin: point(x, layout.text_hitbox.origin.y),
2128 size: size(px(1.), layout.text_hitbox.size.height),
2129 },
2130 color,
2131 ));
2132 }
2133 }
2134 })
2135 }
2136
2137 fn paint_gutter(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2138 let line_height = layout.position_map.line_height;
2139
2140 let scroll_position = layout.position_map.snapshot.scroll_position();
2141 let scroll_top = scroll_position.y * line_height;
2142
2143 cx.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
2144
2145 let show_git_gutter = matches!(
2146 ProjectSettings::get_global(cx).git.git_gutter,
2147 Some(GitGutterSetting::TrackedFiles)
2148 );
2149
2150 if show_git_gutter {
2151 Self::paint_diff_hunks(layout, cx);
2152 }
2153
2154 if layout.blamed_display_rows.is_some() {
2155 self.paint_blamed_display_rows(layout, cx);
2156 }
2157
2158 for (ix, line) in layout.line_numbers.iter().enumerate() {
2159 if let Some(line) = line {
2160 let line_origin = layout.gutter_hitbox.origin
2161 + point(
2162 layout.gutter_hitbox.size.width
2163 - line.width
2164 - layout.gutter_dimensions.right_padding,
2165 ix as f32 * line_height - (scroll_top % line_height),
2166 );
2167
2168 line.paint(line_origin, line_height, cx).log_err();
2169 }
2170 }
2171
2172 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2173 cx.with_element_id(Some("gutter_fold_indicators"), |cx| {
2174 for fold_indicator in layout.fold_indicators.iter_mut().flatten() {
2175 fold_indicator.paint(cx);
2176 }
2177 });
2178
2179 if let Some(indicator) = layout.code_actions_indicator.as_mut() {
2180 indicator.paint(cx);
2181 }
2182 })
2183 }
2184
2185 fn paint_diff_hunks(layout: &EditorLayout, cx: &mut ElementContext) {
2186 if layout.display_hunks.is_empty() {
2187 return;
2188 }
2189
2190 let line_height = layout.position_map.line_height;
2191
2192 let scroll_position = layout.position_map.snapshot.scroll_position();
2193 let scroll_top = scroll_position.y * line_height;
2194
2195 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2196 for hunk in &layout.display_hunks {
2197 let (display_row_range, status) = match hunk {
2198 //TODO: This rendering is entirely a horrible hack
2199 &DisplayDiffHunk::Folded { display_row: row } => {
2200 let start_y = row as f32 * line_height - scroll_top;
2201 let end_y = start_y + line_height;
2202
2203 let width = 0.275 * line_height;
2204 let highlight_origin = layout.gutter_hitbox.origin + point(-width, start_y);
2205 let highlight_size = size(width * 2., end_y - start_y);
2206 let highlight_bounds = Bounds::new(highlight_origin, highlight_size);
2207 cx.paint_quad(quad(
2208 highlight_bounds,
2209 Corners::all(1. * line_height),
2210 cx.theme().status().modified,
2211 Edges::default(),
2212 transparent_black(),
2213 ));
2214
2215 continue;
2216 }
2217
2218 DisplayDiffHunk::Unfolded {
2219 display_row_range,
2220 status,
2221 } => (display_row_range, status),
2222 };
2223
2224 let color = match status {
2225 DiffHunkStatus::Added => cx.theme().status().created,
2226 DiffHunkStatus::Modified => cx.theme().status().modified,
2227
2228 //TODO: This rendering is entirely a horrible hack
2229 DiffHunkStatus::Removed => {
2230 let row = display_row_range.start;
2231
2232 let offset = line_height / 2.;
2233 let start_y = row as f32 * line_height - offset - scroll_top;
2234 let end_y = start_y + line_height;
2235
2236 let width = 0.275 * line_height;
2237 let highlight_origin = layout.gutter_hitbox.origin + point(-width, start_y);
2238 let highlight_size = size(width * 2., end_y - start_y);
2239 let highlight_bounds = Bounds::new(highlight_origin, highlight_size);
2240 cx.paint_quad(quad(
2241 highlight_bounds,
2242 Corners::all(1. * line_height),
2243 cx.theme().status().deleted,
2244 Edges::default(),
2245 transparent_black(),
2246 ));
2247
2248 continue;
2249 }
2250 };
2251
2252 let start_row = display_row_range.start;
2253 let end_row = display_row_range.end;
2254 // If we're in a multibuffer, row range span might include an
2255 // excerpt header, so if we were to draw the marker straight away,
2256 // the hunk might include the rows of that header.
2257 // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
2258 // Instead, we simply check whether the range we're dealing with includes
2259 // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
2260 let end_row_in_current_excerpt = layout
2261 .position_map
2262 .snapshot
2263 .blocks_in_range(start_row..end_row)
2264 .find_map(|(start_row, block)| {
2265 if matches!(block, TransformBlock::ExcerptHeader { .. }) {
2266 Some(start_row)
2267 } else {
2268 None
2269 }
2270 })
2271 .unwrap_or(end_row);
2272
2273 let start_y = start_row as f32 * line_height - scroll_top;
2274 let end_y = end_row_in_current_excerpt as f32 * line_height - scroll_top;
2275
2276 let width = 0.275 * line_height;
2277 let highlight_origin = layout.gutter_hitbox.origin + point(-width, start_y);
2278 let highlight_size = size(width * 2., end_y - start_y);
2279 let highlight_bounds = Bounds::new(highlight_origin, highlight_size);
2280 cx.paint_quad(quad(
2281 highlight_bounds,
2282 Corners::all(0.05 * line_height),
2283 color,
2284 Edges::default(),
2285 transparent_black(),
2286 ));
2287 }
2288 })
2289 }
2290
2291 fn paint_blamed_display_rows(&self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2292 let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
2293 return;
2294 };
2295
2296 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2297 for mut blame_element in blamed_display_rows.into_iter() {
2298 blame_element.paint(cx);
2299 }
2300 })
2301 }
2302
2303 fn paint_text(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2304 cx.with_content_mask(
2305 Some(ContentMask {
2306 bounds: layout.text_hitbox.bounds,
2307 }),
2308 |cx| {
2309 let cursor_style = if self
2310 .editor
2311 .read(cx)
2312 .hovered_link_state
2313 .as_ref()
2314 .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
2315 {
2316 CursorStyle::PointingHand
2317 } else {
2318 CursorStyle::IBeam
2319 };
2320 cx.set_cursor_style(cursor_style, &layout.text_hitbox);
2321
2322 cx.with_element_id(Some("folds"), |cx| self.paint_folds(layout, cx));
2323 let invisible_display_ranges = self.paint_highlights(layout, cx);
2324 self.paint_lines(&invisible_display_ranges, layout, cx);
2325 self.paint_redactions(layout, cx);
2326 self.paint_cursors(layout, cx);
2327 self.paint_inline_blame(layout, cx);
2328 },
2329 )
2330 }
2331
2332 fn paint_highlights(
2333 &mut self,
2334 layout: &mut EditorLayout,
2335 cx: &mut ElementContext,
2336 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
2337 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2338 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
2339 let line_end_overshoot = 0.15 * layout.position_map.line_height;
2340 for (range, color) in &layout.highlighted_ranges {
2341 self.paint_highlighted_range(
2342 range.clone(),
2343 *color,
2344 Pixels::ZERO,
2345 line_end_overshoot,
2346 layout,
2347 cx,
2348 );
2349 }
2350
2351 let corner_radius = 0.15 * layout.position_map.line_height;
2352
2353 for (player_color, selections) in &layout.selections {
2354 for selection in selections.into_iter() {
2355 self.paint_highlighted_range(
2356 selection.range.clone(),
2357 player_color.selection,
2358 corner_radius,
2359 corner_radius * 2.,
2360 layout,
2361 cx,
2362 );
2363
2364 if selection.is_local && !selection.range.is_empty() {
2365 invisible_display_ranges.push(selection.range.clone());
2366 }
2367 }
2368 }
2369 invisible_display_ranges
2370 })
2371 }
2372
2373 fn paint_lines(
2374 &mut self,
2375 invisible_display_ranges: &[Range<DisplayPoint>],
2376 layout: &EditorLayout,
2377 cx: &mut ElementContext,
2378 ) {
2379 let whitespace_setting = self
2380 .editor
2381 .read(cx)
2382 .buffer
2383 .read(cx)
2384 .settings_at(0, cx)
2385 .show_whitespaces;
2386
2387 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
2388 let row = layout.visible_display_row_range.start + ix as u32;
2389 line_with_invisibles.draw(
2390 layout,
2391 row,
2392 layout.content_origin,
2393 whitespace_setting,
2394 invisible_display_ranges,
2395 cx,
2396 )
2397 }
2398 }
2399
2400 fn paint_redactions(&mut self, layout: &EditorLayout, cx: &mut ElementContext) {
2401 if layout.redacted_ranges.is_empty() {
2402 return;
2403 }
2404
2405 let line_end_overshoot = layout.line_end_overshoot();
2406
2407 // A softer than perfect black
2408 let redaction_color = gpui::rgb(0x0e1111);
2409
2410 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2411 for range in layout.redacted_ranges.iter() {
2412 self.paint_highlighted_range(
2413 range.clone(),
2414 redaction_color.into(),
2415 Pixels::ZERO,
2416 line_end_overshoot,
2417 layout,
2418 cx,
2419 );
2420 }
2421 });
2422 }
2423
2424 fn paint_cursors(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2425 for cursor in &mut layout.cursors {
2426 cursor.paint(layout.content_origin, cx);
2427 }
2428 }
2429
2430 fn paint_scrollbar(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2431 let Some(scrollbar_layout) = layout.scrollbar_layout.as_ref() else {
2432 return;
2433 };
2434
2435 let thumb_bounds = scrollbar_layout.thumb_bounds();
2436 if scrollbar_layout.visible {
2437 cx.paint_layer(scrollbar_layout.hitbox.bounds, |cx| {
2438 cx.paint_quad(quad(
2439 scrollbar_layout.hitbox.bounds,
2440 Corners::default(),
2441 cx.theme().colors().scrollbar_track_background,
2442 Edges {
2443 top: Pixels::ZERO,
2444 right: Pixels::ZERO,
2445 bottom: Pixels::ZERO,
2446 left: ScrollbarLayout::BORDER_WIDTH,
2447 },
2448 cx.theme().colors().scrollbar_track_border,
2449 ));
2450
2451 // Refresh scrollbar markers in the background. Below, we paint whatever markers have already been computed.
2452 self.refresh_scrollbar_markers(layout, scrollbar_layout, cx);
2453
2454 let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
2455 for marker in markers.iter() {
2456 let mut marker = marker.clone();
2457 marker.bounds.origin += scrollbar_layout.hitbox.origin;
2458 cx.paint_quad(marker);
2459 }
2460
2461 cx.paint_quad(quad(
2462 thumb_bounds,
2463 Corners::default(),
2464 cx.theme().colors().scrollbar_thumb_background,
2465 Edges {
2466 top: Pixels::ZERO,
2467 right: Pixels::ZERO,
2468 bottom: Pixels::ZERO,
2469 left: ScrollbarLayout::BORDER_WIDTH,
2470 },
2471 cx.theme().colors().scrollbar_thumb_border,
2472 ));
2473 });
2474 }
2475
2476 cx.set_cursor_style(CursorStyle::Arrow, &scrollbar_layout.hitbox);
2477
2478 let scroll_height = scrollbar_layout.scroll_height;
2479 let height = scrollbar_layout.height;
2480 let row_range = scrollbar_layout.visible_row_range.clone();
2481
2482 cx.on_mouse_event({
2483 let editor = self.editor.clone();
2484 let hitbox = scrollbar_layout.hitbox.clone();
2485 let mut mouse_position = cx.mouse_position();
2486 move |event: &MouseMoveEvent, phase, cx| {
2487 if phase == DispatchPhase::Capture {
2488 return;
2489 }
2490
2491 editor.update(cx, |editor, cx| {
2492 if event.pressed_button == Some(MouseButton::Left)
2493 && editor.scroll_manager.is_dragging_scrollbar()
2494 {
2495 let y = mouse_position.y;
2496 let new_y = event.position.y;
2497 if (hitbox.top()..hitbox.bottom()).contains(&y) {
2498 let mut position = editor.scroll_position(cx);
2499 position.y += (new_y - y) * scroll_height / height;
2500 if position.y < 0.0 {
2501 position.y = 0.0;
2502 }
2503 editor.set_scroll_position(position, cx);
2504 }
2505
2506 mouse_position = event.position;
2507 cx.stop_propagation();
2508 } else {
2509 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
2510 if hitbox.is_hovered(cx) {
2511 editor.scroll_manager.show_scrollbar(cx);
2512 }
2513 }
2514 })
2515 }
2516 });
2517
2518 if self.editor.read(cx).scroll_manager.is_dragging_scrollbar() {
2519 cx.on_mouse_event({
2520 let editor = self.editor.clone();
2521 move |_: &MouseUpEvent, phase, cx| {
2522 if phase == DispatchPhase::Capture {
2523 return;
2524 }
2525
2526 editor.update(cx, |editor, cx| {
2527 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
2528 cx.stop_propagation();
2529 });
2530 }
2531 });
2532 } else {
2533 cx.on_mouse_event({
2534 let editor = self.editor.clone();
2535 let hitbox = scrollbar_layout.hitbox.clone();
2536 move |event: &MouseDownEvent, phase, cx| {
2537 if phase == DispatchPhase::Capture || !hitbox.is_hovered(cx) {
2538 return;
2539 }
2540
2541 editor.update(cx, |editor, cx| {
2542 editor.scroll_manager.set_is_dragging_scrollbar(true, cx);
2543
2544 let y = event.position.y;
2545 if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
2546 let center_row =
2547 ((y - hitbox.top()) * scroll_height / height).round() as u32;
2548 let top_row = center_row
2549 .saturating_sub((row_range.end - row_range.start) as u32 / 2);
2550 let mut position = editor.scroll_position(cx);
2551 position.y = top_row as f32;
2552 editor.set_scroll_position(position, cx);
2553 } else {
2554 editor.scroll_manager.show_scrollbar(cx);
2555 }
2556
2557 cx.stop_propagation();
2558 });
2559 }
2560 });
2561 }
2562 }
2563
2564 fn refresh_scrollbar_markers(
2565 &self,
2566 layout: &EditorLayout,
2567 scrollbar_layout: &ScrollbarLayout,
2568 cx: &mut ElementContext,
2569 ) {
2570 self.editor.update(cx, |editor, cx| {
2571 if !editor.is_singleton(cx)
2572 || !editor
2573 .scrollbar_marker_state
2574 .should_refresh(scrollbar_layout.hitbox.size)
2575 {
2576 return;
2577 }
2578
2579 let scrollbar_layout = scrollbar_layout.clone();
2580 let background_highlights = editor.background_highlights.clone();
2581 let snapshot = layout.position_map.snapshot.clone();
2582 let theme = cx.theme().clone();
2583 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
2584 let max_row = layout.max_row;
2585
2586 editor.scrollbar_marker_state.dirty = false;
2587 editor.scrollbar_marker_state.pending_refresh =
2588 Some(cx.spawn(|editor, mut cx| async move {
2589 let scrollbar_size = scrollbar_layout.hitbox.size;
2590 let scrollbar_markers = cx
2591 .background_executor()
2592 .spawn(async move {
2593 let mut marker_quads = Vec::new();
2594
2595 if scrollbar_settings.git_diff {
2596 let marker_row_ranges = snapshot
2597 .buffer_snapshot
2598 .git_diff_hunks_in_range(0..max_row)
2599 .map(|hunk| {
2600 let start_display_row =
2601 Point::new(hunk.associated_range.start, 0)
2602 .to_display_point(&snapshot.display_snapshot)
2603 .row();
2604 let mut end_display_row =
2605 Point::new(hunk.associated_range.end, 0)
2606 .to_display_point(&snapshot.display_snapshot)
2607 .row();
2608 if end_display_row != start_display_row {
2609 end_display_row -= 1;
2610 }
2611 let color = match hunk.status() {
2612 DiffHunkStatus::Added => theme.status().created,
2613 DiffHunkStatus::Modified => theme.status().modified,
2614 DiffHunkStatus::Removed => theme.status().deleted,
2615 };
2616 ColoredRange {
2617 start: start_display_row,
2618 end: end_display_row,
2619 color,
2620 }
2621 });
2622
2623 marker_quads.extend(
2624 scrollbar_layout.marker_quads_for_ranges(marker_row_ranges, 0),
2625 );
2626 }
2627
2628 for (background_highlight_id, (_, background_ranges)) in
2629 background_highlights.iter()
2630 {
2631 let is_search_highlights = *background_highlight_id
2632 == TypeId::of::<BufferSearchHighlights>();
2633 let is_symbol_occurrences = *background_highlight_id
2634 == TypeId::of::<DocumentHighlightRead>()
2635 || *background_highlight_id
2636 == TypeId::of::<DocumentHighlightWrite>();
2637 if (is_search_highlights && scrollbar_settings.search_results)
2638 || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
2639 {
2640 let marker_row_ranges =
2641 background_ranges.into_iter().map(|range| {
2642 let display_start = range
2643 .start
2644 .to_display_point(&snapshot.display_snapshot);
2645 let display_end = range
2646 .end
2647 .to_display_point(&snapshot.display_snapshot);
2648 ColoredRange {
2649 start: display_start.row(),
2650 end: display_end.row(),
2651 color: theme.status().info,
2652 }
2653 });
2654 marker_quads.extend(
2655 scrollbar_layout
2656 .marker_quads_for_ranges(marker_row_ranges, 1),
2657 );
2658 }
2659 }
2660
2661 if scrollbar_settings.diagnostics {
2662 let max_point =
2663 snapshot.display_snapshot.buffer_snapshot.max_point();
2664
2665 let diagnostics = snapshot
2666 .buffer_snapshot
2667 .diagnostics_in_range::<_, Point>(
2668 Point::zero()..max_point,
2669 false,
2670 )
2671 // We want to sort by severity, in order to paint the most severe diagnostics last.
2672 .sorted_by_key(|diagnostic| {
2673 std::cmp::Reverse(diagnostic.diagnostic.severity)
2674 });
2675
2676 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
2677 let start_display = diagnostic
2678 .range
2679 .start
2680 .to_display_point(&snapshot.display_snapshot);
2681 let end_display = diagnostic
2682 .range
2683 .end
2684 .to_display_point(&snapshot.display_snapshot);
2685 let color = match diagnostic.diagnostic.severity {
2686 DiagnosticSeverity::ERROR => theme.status().error,
2687 DiagnosticSeverity::WARNING => theme.status().warning,
2688 DiagnosticSeverity::INFORMATION => theme.status().info,
2689 _ => theme.status().hint,
2690 };
2691 ColoredRange {
2692 start: start_display.row(),
2693 end: end_display.row(),
2694 color,
2695 }
2696 });
2697 marker_quads.extend(
2698 scrollbar_layout.marker_quads_for_ranges(marker_row_ranges, 2),
2699 );
2700 }
2701
2702 Arc::from(marker_quads)
2703 })
2704 .await;
2705
2706 editor.update(&mut cx, |editor, cx| {
2707 editor.scrollbar_marker_state.markers = scrollbar_markers;
2708 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
2709 editor.scrollbar_marker_state.pending_refresh = None;
2710 cx.notify();
2711 })?;
2712
2713 Ok(())
2714 }));
2715 });
2716 }
2717
2718 #[allow(clippy::too_many_arguments)]
2719 fn paint_highlighted_range(
2720 &self,
2721 range: Range<DisplayPoint>,
2722 color: Hsla,
2723 corner_radius: Pixels,
2724 line_end_overshoot: Pixels,
2725 layout: &EditorLayout,
2726 cx: &mut ElementContext,
2727 ) {
2728 let start_row = layout.visible_display_row_range.start;
2729 let end_row = layout.visible_display_row_range.end;
2730 if range.start != range.end {
2731 let row_range = if range.end.column() == 0 {
2732 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
2733 } else {
2734 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
2735 };
2736
2737 let highlighted_range = HighlightedRange {
2738 color,
2739 line_height: layout.position_map.line_height,
2740 corner_radius,
2741 start_y: layout.content_origin.y
2742 + row_range.start as f32 * layout.position_map.line_height
2743 - layout.position_map.scroll_pixel_position.y,
2744 lines: row_range
2745 .into_iter()
2746 .map(|row| {
2747 let line_layout =
2748 &layout.position_map.line_layouts[(row - start_row) as usize].line;
2749 HighlightedRangeLine {
2750 start_x: if row == range.start.row() {
2751 layout.content_origin.x
2752 + line_layout.x_for_index(range.start.column() as usize)
2753 - layout.position_map.scroll_pixel_position.x
2754 } else {
2755 layout.content_origin.x
2756 - layout.position_map.scroll_pixel_position.x
2757 },
2758 end_x: if row == range.end.row() {
2759 layout.content_origin.x
2760 + line_layout.x_for_index(range.end.column() as usize)
2761 - layout.position_map.scroll_pixel_position.x
2762 } else {
2763 layout.content_origin.x + line_layout.width + line_end_overshoot
2764 - layout.position_map.scroll_pixel_position.x
2765 },
2766 }
2767 })
2768 .collect(),
2769 };
2770
2771 highlighted_range.paint(layout.text_hitbox.bounds, cx);
2772 }
2773 }
2774
2775 fn paint_folds(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2776 if layout.folds.is_empty() {
2777 return;
2778 }
2779
2780 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2781 let fold_corner_radius = 0.15 * layout.position_map.line_height;
2782 for mut fold in mem::take(&mut layout.folds) {
2783 fold.hover_element.paint(cx);
2784
2785 let hover_element = fold.hover_element.downcast_mut::<Stateful<Div>>().unwrap();
2786 let fold_background = if hover_element.interactivity().active.unwrap() {
2787 cx.theme().colors().ghost_element_active
2788 } else if hover_element.interactivity().hovered.unwrap() {
2789 cx.theme().colors().ghost_element_hover
2790 } else {
2791 cx.theme().colors().ghost_element_background
2792 };
2793
2794 self.paint_highlighted_range(
2795 fold.display_range.clone(),
2796 fold_background,
2797 fold_corner_radius,
2798 fold_corner_radius * 2.,
2799 layout,
2800 cx,
2801 );
2802 }
2803 })
2804 }
2805
2806 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2807 if let Some(mut inline_blame) = layout.inline_blame.take() {
2808 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2809 inline_blame.paint(cx);
2810 })
2811 }
2812 }
2813
2814 fn paint_blocks(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2815 for mut block in layout.blocks.drain(..) {
2816 block.element.paint(cx);
2817 }
2818 }
2819
2820 fn paint_mouse_context_menu(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2821 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
2822 mouse_context_menu.paint(cx);
2823 }
2824 }
2825
2826 fn paint_scroll_wheel_listener(&mut self, layout: &EditorLayout, cx: &mut ElementContext) {
2827 cx.on_mouse_event({
2828 let position_map = layout.position_map.clone();
2829 let editor = self.editor.clone();
2830 let hitbox = layout.hitbox.clone();
2831 let mut delta = ScrollDelta::default();
2832
2833 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
2834 // accidentally turn off their scrolling.
2835 let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
2836
2837 move |event: &ScrollWheelEvent, phase, cx| {
2838 if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
2839 delta = delta.coalesce(event.delta);
2840 editor.update(cx, |editor, cx| {
2841 let position_map: &PositionMap = &position_map;
2842
2843 let line_height = position_map.line_height;
2844 let max_glyph_width = position_map.em_width;
2845 let (delta, axis) = match delta {
2846 gpui::ScrollDelta::Pixels(mut pixels) => {
2847 //Trackpad
2848 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
2849 (pixels, axis)
2850 }
2851
2852 gpui::ScrollDelta::Lines(lines) => {
2853 //Not trackpad
2854 let pixels =
2855 point(lines.x * max_glyph_width, lines.y * line_height);
2856 (pixels, None)
2857 }
2858 };
2859
2860 let scroll_position = position_map.snapshot.scroll_position();
2861 let x = (scroll_position.x * max_glyph_width
2862 - (delta.x * scroll_sensitivity))
2863 / max_glyph_width;
2864 let y = (scroll_position.y * line_height - (delta.y * scroll_sensitivity))
2865 / line_height;
2866 let scroll_position =
2867 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
2868 editor.scroll(scroll_position, axis, cx);
2869 cx.stop_propagation();
2870 });
2871 }
2872 }
2873 });
2874 }
2875
2876 fn paint_mouse_listeners(&mut self, layout: &EditorLayout, cx: &mut ElementContext) {
2877 self.paint_scroll_wheel_listener(layout, cx);
2878
2879 cx.on_mouse_event({
2880 let position_map = layout.position_map.clone();
2881 let editor = self.editor.clone();
2882 let text_hitbox = layout.text_hitbox.clone();
2883 let gutter_hitbox = layout.gutter_hitbox.clone();
2884
2885 move |event: &MouseDownEvent, phase, cx| {
2886 if phase == DispatchPhase::Bubble {
2887 match event.button {
2888 MouseButton::Left => editor.update(cx, |editor, cx| {
2889 Self::mouse_left_down(
2890 editor,
2891 event,
2892 &position_map,
2893 &text_hitbox,
2894 &gutter_hitbox,
2895 cx,
2896 );
2897 }),
2898 MouseButton::Right => editor.update(cx, |editor, cx| {
2899 Self::mouse_right_down(editor, event, &position_map, &text_hitbox, cx);
2900 }),
2901 _ => {}
2902 };
2903 }
2904 }
2905 });
2906
2907 cx.on_mouse_event({
2908 let editor = self.editor.clone();
2909 let position_map = layout.position_map.clone();
2910 let text_hitbox = layout.text_hitbox.clone();
2911
2912 move |event: &MouseUpEvent, phase, cx| {
2913 if phase == DispatchPhase::Bubble {
2914 editor.update(cx, |editor, cx| {
2915 Self::mouse_up(editor, event, &position_map, &text_hitbox, cx)
2916 });
2917 }
2918 }
2919 });
2920 cx.on_mouse_event({
2921 let position_map = layout.position_map.clone();
2922 let editor = self.editor.clone();
2923 let text_hitbox = layout.text_hitbox.clone();
2924 let gutter_hitbox = layout.gutter_hitbox.clone();
2925
2926 move |event: &MouseMoveEvent, phase, cx| {
2927 if phase == DispatchPhase::Bubble {
2928 editor.update(cx, |editor, cx| {
2929 if event.pressed_button == Some(MouseButton::Left) {
2930 Self::mouse_dragged(
2931 editor,
2932 event,
2933 &position_map,
2934 text_hitbox.bounds,
2935 cx,
2936 )
2937 }
2938
2939 Self::mouse_moved(
2940 editor,
2941 event,
2942 &position_map,
2943 &text_hitbox,
2944 &gutter_hitbox,
2945 cx,
2946 )
2947 });
2948 }
2949 }
2950 });
2951 }
2952
2953 fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
2954 bounds.upper_right().x - self.style.scrollbar_width
2955 }
2956
2957 fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
2958 let style = &self.style;
2959 let font_size = style.text.font_size.to_pixels(cx.rem_size());
2960 let layout = cx
2961 .text_system()
2962 .shape_line(
2963 SharedString::from(" ".repeat(column)),
2964 font_size,
2965 &[TextRun {
2966 len: column,
2967 font: style.text.font(),
2968 color: Hsla::default(),
2969 background_color: None,
2970 underline: None,
2971 strikethrough: None,
2972 }],
2973 )
2974 .unwrap();
2975
2976 layout.width
2977 }
2978
2979 fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
2980 let digit_count = (snapshot.max_buffer_row() as f32 + 1.).log10().floor() as usize + 1;
2981 self.column_pixels(digit_count, cx)
2982 }
2983}
2984
2985fn render_inline_blame_entry(
2986 blame: &gpui::Model<GitBlame>,
2987 blame_entry: BlameEntry,
2988 style: &EditorStyle,
2989 workspace: Option<WeakView<Workspace>>,
2990 cx: &mut ElementContext<'_>,
2991) -> AnyElement {
2992 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
2993
2994 let author = blame_entry.author.as_deref().unwrap_or_default();
2995 let text = format!("{}, {}", author, relative_timestamp);
2996
2997 let details = blame.read(cx).details_for_entry(&blame_entry);
2998
2999 let tooltip = cx.new_view(|_| BlameEntryTooltip::new(blame_entry, details, style, workspace));
3000
3001 h_flex()
3002 .id("inline-blame")
3003 .w_full()
3004 .font(style.text.font().family)
3005 .text_color(cx.theme().status().hint)
3006 .line_height(style.text.line_height)
3007 .child(Icon::new(IconName::FileGit).color(Color::Hint))
3008 .child(text)
3009 .gap_2()
3010 .hoverable_tooltip(move |_| tooltip.clone().into())
3011 .into_any()
3012}
3013
3014fn blame_entry_timestamp(
3015 blame_entry: &BlameEntry,
3016 format: time_format::TimestampFormat,
3017 cx: &WindowContext,
3018) -> String {
3019 match blame_entry.author_offset_date_time() {
3020 Ok(timestamp) => time_format::format_localized_timestamp(
3021 timestamp,
3022 time::OffsetDateTime::now_utc(),
3023 cx.local_timezone(),
3024 format,
3025 ),
3026 Err(_) => "Error parsing date".to_string(),
3027 }
3028}
3029
3030fn blame_entry_relative_timestamp(blame_entry: &BlameEntry, cx: &WindowContext) -> String {
3031 blame_entry_timestamp(blame_entry, time_format::TimestampFormat::Relative, cx)
3032}
3033
3034fn blame_entry_absolute_timestamp(blame_entry: &BlameEntry, cx: &WindowContext) -> String {
3035 blame_entry_timestamp(
3036 blame_entry,
3037 time_format::TimestampFormat::MediumAbsolute,
3038 cx,
3039 )
3040}
3041
3042struct BlameEntryTooltip {
3043 blame_entry: BlameEntry,
3044 details: Option<CommitDetails>,
3045 style: EditorStyle,
3046 workspace: Option<WeakView<Workspace>>,
3047 scroll_handle: ScrollHandle,
3048}
3049
3050impl BlameEntryTooltip {
3051 fn new(
3052 blame_entry: BlameEntry,
3053 details: Option<CommitDetails>,
3054 style: &EditorStyle,
3055 workspace: Option<WeakView<Workspace>>,
3056 ) -> Self {
3057 Self {
3058 style: style.clone(),
3059 blame_entry,
3060 details,
3061 workspace,
3062 scroll_handle: ScrollHandle::new(),
3063 }
3064 }
3065}
3066
3067impl Render for BlameEntryTooltip {
3068 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
3069 let author = self
3070 .blame_entry
3071 .author
3072 .clone()
3073 .unwrap_or("<no name>".to_string());
3074
3075 let author_email = self.blame_entry.author_mail.clone();
3076
3077 let pretty_commit_id = format!("{}", self.blame_entry.sha);
3078 let short_commit_id = pretty_commit_id.chars().take(6).collect::<String>();
3079 let absolute_timestamp = blame_entry_absolute_timestamp(&self.blame_entry, cx);
3080
3081 let message = self
3082 .details
3083 .as_ref()
3084 .map(|details| {
3085 crate::render_parsed_markdown(
3086 "blame-message",
3087 &details.parsed_message,
3088 &self.style,
3089 self.workspace.clone(),
3090 cx,
3091 )
3092 .into_any()
3093 })
3094 .unwrap_or("<no commit message>".into_any());
3095
3096 let ui_font_size = ThemeSettings::get_global(cx).ui_font_size;
3097 let message_max_height = cx.line_height() * 12 + (ui_font_size / 0.4);
3098
3099 tooltip_container(cx, move |this, cx| {
3100 this.occlude()
3101 .on_mouse_move(|_, cx| cx.stop_propagation())
3102 .child(
3103 v_flex()
3104 .w(gpui::rems(30.))
3105 .gap_4()
3106 .child(
3107 h_flex()
3108 .gap_x_2()
3109 .overflow_x_hidden()
3110 .flex_wrap()
3111 .child(author)
3112 .when_some(author_email, |this, author_email| {
3113 this.child(
3114 div()
3115 .text_color(cx.theme().colors().text_muted)
3116 .child(author_email),
3117 )
3118 })
3119 .pb_1()
3120 .border_b_1()
3121 .border_color(cx.theme().colors().border),
3122 )
3123 .child(
3124 div()
3125 .id("inline-blame-commit-message")
3126 .occlude()
3127 .child(message)
3128 .max_h(message_max_height)
3129 .overflow_y_scroll()
3130 .track_scroll(&self.scroll_handle),
3131 )
3132 .child(
3133 h_flex()
3134 .text_color(cx.theme().colors().text_muted)
3135 .w_full()
3136 .justify_between()
3137 .child(absolute_timestamp)
3138 .child(
3139 Button::new("commit-sha-button", short_commit_id.clone())
3140 .style(ButtonStyle::Transparent)
3141 .color(Color::Muted)
3142 .icon(IconName::FileGit)
3143 .icon_color(Color::Muted)
3144 .icon_position(IconPosition::Start)
3145 .disabled(
3146 self.details.as_ref().map_or(true, |details| {
3147 details.permalink.is_none()
3148 }),
3149 )
3150 .when_some(
3151 self.details
3152 .as_ref()
3153 .and_then(|details| details.permalink.clone()),
3154 |this, url| {
3155 this.on_click(move |_, cx| {
3156 cx.stop_propagation();
3157 cx.open_url(url.as_str())
3158 })
3159 },
3160 ),
3161 ),
3162 ),
3163 )
3164 })
3165 }
3166}
3167
3168fn render_blame_entry(
3169 ix: usize,
3170 blame: &gpui::Model<GitBlame>,
3171 blame_entry: BlameEntry,
3172 style: &EditorStyle,
3173 last_used_color: &mut Option<(PlayerColor, Oid)>,
3174 editor: View<Editor>,
3175 cx: &mut ElementContext<'_>,
3176) -> AnyElement {
3177 let mut sha_color = cx
3178 .theme()
3179 .players()
3180 .color_for_participant(blame_entry.sha.into());
3181 // If the last color we used is the same as the one we get for this line, but
3182 // the commit SHAs are different, then we try again to get a different color.
3183 match *last_used_color {
3184 Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
3185 let index: u32 = blame_entry.sha.into();
3186 sha_color = cx.theme().players().color_for_participant(index + 1);
3187 }
3188 _ => {}
3189 };
3190 last_used_color.replace((sha_color, blame_entry.sha));
3191
3192 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
3193
3194 let pretty_commit_id = format!("{}", blame_entry.sha);
3195 let short_commit_id = pretty_commit_id.chars().take(6).collect::<String>();
3196
3197 let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
3198 let name = util::truncate_and_trailoff(author_name, 20);
3199
3200 let details = blame.read(cx).details_for_entry(&blame_entry);
3201
3202 let workspace = editor.read(cx).workspace.as_ref().map(|(w, _)| w.clone());
3203
3204 let tooltip = cx.new_view(|_| {
3205 BlameEntryTooltip::new(blame_entry.clone(), details.clone(), style, workspace)
3206 });
3207
3208 h_flex()
3209 .w_full()
3210 .font(style.text.font().family)
3211 .line_height(style.text.line_height)
3212 .id(("blame", ix))
3213 .children([
3214 div()
3215 .text_color(sha_color.cursor)
3216 .child(short_commit_id)
3217 .mr_2(),
3218 div()
3219 .w_full()
3220 .h_flex()
3221 .justify_between()
3222 .text_color(cx.theme().status().hint)
3223 .child(name)
3224 .child(relative_timestamp),
3225 ])
3226 .on_mouse_down(MouseButton::Right, {
3227 let blame_entry = blame_entry.clone();
3228 move |event, cx| {
3229 deploy_blame_entry_context_menu(&blame_entry, editor.clone(), event.position, cx);
3230 }
3231 })
3232 .hover(|style| style.bg(cx.theme().colors().element_hover))
3233 .when_some(
3234 details.and_then(|details| details.permalink),
3235 |this, url| {
3236 let url = url.clone();
3237 this.cursor_pointer().on_click(move |_, cx| {
3238 cx.stop_propagation();
3239 cx.open_url(url.as_str())
3240 })
3241 },
3242 )
3243 .hoverable_tooltip(move |_| tooltip.clone().into())
3244 .into_any()
3245}
3246
3247fn deploy_blame_entry_context_menu(
3248 blame_entry: &BlameEntry,
3249 editor: View<Editor>,
3250 position: gpui::Point<Pixels>,
3251 cx: &mut WindowContext<'_>,
3252) {
3253 let context_menu = ContextMenu::build(cx, move |this, _| {
3254 let sha = format!("{}", blame_entry.sha);
3255 this.entry("Copy commit SHA", None, move |cx| {
3256 cx.write_to_clipboard(ClipboardItem::new(sha.clone()));
3257 })
3258 });
3259
3260 editor.update(cx, move |editor, cx| {
3261 editor.mouse_context_menu = Some(MouseContextMenu::new(position, context_menu, cx));
3262 cx.notify();
3263 });
3264}
3265
3266#[derive(Debug)]
3267pub(crate) struct LineWithInvisibles {
3268 pub line: ShapedLine,
3269 invisibles: Vec<Invisible>,
3270}
3271
3272impl LineWithInvisibles {
3273 fn from_chunks<'a>(
3274 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
3275 text_style: &TextStyle,
3276 max_line_len: usize,
3277 max_line_count: usize,
3278 line_number_layouts: &[Option<ShapedLine>],
3279 editor_mode: EditorMode,
3280 cx: &WindowContext,
3281 ) -> Vec<Self> {
3282 let mut layouts = Vec::with_capacity(max_line_count);
3283 let mut line = String::new();
3284 let mut invisibles = Vec::new();
3285 let mut styles = Vec::new();
3286 let mut non_whitespace_added = false;
3287 let mut row = 0;
3288 let mut line_exceeded_max_len = false;
3289 let font_size = text_style.font_size.to_pixels(cx.rem_size());
3290
3291 for highlighted_chunk in chunks.chain([HighlightedChunk {
3292 chunk: "\n",
3293 style: None,
3294 is_tab: false,
3295 }]) {
3296 for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
3297 if ix > 0 {
3298 let shaped_line = cx
3299 .text_system()
3300 .shape_line(line.clone().into(), font_size, &styles)
3301 .unwrap();
3302 layouts.push(Self {
3303 line: shaped_line,
3304 invisibles: std::mem::take(&mut invisibles),
3305 });
3306
3307 line.clear();
3308 styles.clear();
3309 row += 1;
3310 line_exceeded_max_len = false;
3311 non_whitespace_added = false;
3312 if row == max_line_count {
3313 return layouts;
3314 }
3315 }
3316
3317 if !line_chunk.is_empty() && !line_exceeded_max_len {
3318 let text_style = if let Some(style) = highlighted_chunk.style {
3319 Cow::Owned(text_style.clone().highlight(style))
3320 } else {
3321 Cow::Borrowed(text_style)
3322 };
3323
3324 if line.len() + line_chunk.len() > max_line_len {
3325 let mut chunk_len = max_line_len - line.len();
3326 while !line_chunk.is_char_boundary(chunk_len) {
3327 chunk_len -= 1;
3328 }
3329 line_chunk = &line_chunk[..chunk_len];
3330 line_exceeded_max_len = true;
3331 }
3332
3333 styles.push(TextRun {
3334 len: line_chunk.len(),
3335 font: text_style.font(),
3336 color: text_style.color,
3337 background_color: text_style.background_color,
3338 underline: text_style.underline,
3339 strikethrough: text_style.strikethrough,
3340 });
3341
3342 if editor_mode == EditorMode::Full {
3343 // Line wrap pads its contents with fake whitespaces,
3344 // avoid printing them
3345 let inside_wrapped_string = line_number_layouts
3346 .get(row)
3347 .and_then(|layout| layout.as_ref())
3348 .is_none();
3349 if highlighted_chunk.is_tab {
3350 if non_whitespace_added || !inside_wrapped_string {
3351 invisibles.push(Invisible::Tab {
3352 line_start_offset: line.len(),
3353 });
3354 }
3355 } else {
3356 invisibles.extend(
3357 line_chunk
3358 .chars()
3359 .enumerate()
3360 .filter(|(_, line_char)| {
3361 let is_whitespace = line_char.is_whitespace();
3362 non_whitespace_added |= !is_whitespace;
3363 is_whitespace
3364 && (non_whitespace_added || !inside_wrapped_string)
3365 })
3366 .map(|(whitespace_index, _)| Invisible::Whitespace {
3367 line_offset: line.len() + whitespace_index,
3368 }),
3369 )
3370 }
3371 }
3372
3373 line.push_str(line_chunk);
3374 }
3375 }
3376 }
3377
3378 layouts
3379 }
3380
3381 fn draw(
3382 &self,
3383 layout: &EditorLayout,
3384 row: u32,
3385 content_origin: gpui::Point<Pixels>,
3386 whitespace_setting: ShowWhitespaceSetting,
3387 selection_ranges: &[Range<DisplayPoint>],
3388 cx: &mut ElementContext,
3389 ) {
3390 let line_height = layout.position_map.line_height;
3391 let line_y =
3392 line_height * (row as f32 - layout.position_map.scroll_pixel_position.y / line_height);
3393
3394 let line_origin =
3395 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
3396 self.line.paint(line_origin, line_height, cx).log_err();
3397
3398 self.draw_invisibles(
3399 &selection_ranges,
3400 layout,
3401 content_origin,
3402 line_y,
3403 row,
3404 line_height,
3405 whitespace_setting,
3406 cx,
3407 );
3408 }
3409
3410 #[allow(clippy::too_many_arguments)]
3411 fn draw_invisibles(
3412 &self,
3413 selection_ranges: &[Range<DisplayPoint>],
3414 layout: &EditorLayout,
3415 content_origin: gpui::Point<Pixels>,
3416 line_y: Pixels,
3417 row: u32,
3418 line_height: Pixels,
3419 whitespace_setting: ShowWhitespaceSetting,
3420 cx: &mut ElementContext,
3421 ) {
3422 let allowed_invisibles_regions = match whitespace_setting {
3423 ShowWhitespaceSetting::None => return,
3424 ShowWhitespaceSetting::Selection => Some(selection_ranges),
3425 ShowWhitespaceSetting::All => None,
3426 };
3427
3428 for invisible in &self.invisibles {
3429 let (&token_offset, invisible_symbol) = match invisible {
3430 Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
3431 Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
3432 };
3433
3434 let x_offset = self.line.x_for_index(token_offset);
3435 let invisible_offset =
3436 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
3437 let origin = content_origin
3438 + gpui::point(
3439 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
3440 line_y,
3441 );
3442
3443 if let Some(allowed_regions) = allowed_invisibles_regions {
3444 let invisible_point = DisplayPoint::new(row, token_offset as u32);
3445 if !allowed_regions
3446 .iter()
3447 .any(|region| region.start <= invisible_point && invisible_point < region.end)
3448 {
3449 continue;
3450 }
3451 }
3452 invisible_symbol.paint(origin, line_height, cx).log_err();
3453 }
3454 }
3455}
3456
3457#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3458enum Invisible {
3459 Tab { line_start_offset: usize },
3460 Whitespace { line_offset: usize },
3461}
3462
3463impl Element for EditorElement {
3464 type BeforeLayout = ();
3465 type AfterLayout = EditorLayout;
3466
3467 fn before_layout(&mut self, cx: &mut ElementContext) -> (gpui::LayoutId, ()) {
3468 self.editor.update(cx, |editor, cx| {
3469 editor.set_style(self.style.clone(), cx);
3470
3471 let layout_id = match editor.mode {
3472 EditorMode::SingleLine => {
3473 let rem_size = cx.rem_size();
3474 let mut style = Style::default();
3475 style.size.width = relative(1.).into();
3476 style.size.height = self.style.text.line_height_in_pixels(rem_size).into();
3477 cx.with_element_context(|cx| cx.request_layout(&style, None))
3478 }
3479 EditorMode::AutoHeight { max_lines } => {
3480 let editor_handle = cx.view().clone();
3481 let max_line_number_width =
3482 self.max_line_number_width(&editor.snapshot(cx), cx);
3483 cx.with_element_context(|cx| {
3484 cx.request_measured_layout(
3485 Style::default(),
3486 move |known_dimensions, _, cx| {
3487 editor_handle
3488 .update(cx, |editor, cx| {
3489 compute_auto_height_layout(
3490 editor,
3491 max_lines,
3492 max_line_number_width,
3493 known_dimensions,
3494 cx,
3495 )
3496 })
3497 .unwrap_or_default()
3498 },
3499 )
3500 })
3501 }
3502 EditorMode::Full => {
3503 let mut style = Style::default();
3504 style.size.width = relative(1.).into();
3505 style.size.height = relative(1.).into();
3506 cx.with_element_context(|cx| cx.request_layout(&style, None))
3507 }
3508 };
3509
3510 (layout_id, ())
3511 })
3512 }
3513
3514 fn after_layout(
3515 &mut self,
3516 bounds: Bounds<Pixels>,
3517 _: &mut Self::BeforeLayout,
3518 cx: &mut ElementContext,
3519 ) -> Self::AfterLayout {
3520 let text_style = TextStyleRefinement {
3521 font_size: Some(self.style.text.font_size),
3522 line_height: Some(self.style.text.line_height),
3523 ..Default::default()
3524 };
3525 cx.with_text_style(Some(text_style), |cx| {
3526 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
3527 let mut snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
3528 let style = self.style.clone();
3529
3530 let font_id = cx.text_system().resolve_font(&style.text.font());
3531 let font_size = style.text.font_size.to_pixels(cx.rem_size());
3532 let line_height = style.text.line_height_in_pixels(cx.rem_size());
3533 let em_width = cx
3534 .text_system()
3535 .typographic_bounds(font_id, font_size, 'm')
3536 .unwrap()
3537 .size
3538 .width;
3539 let em_advance = cx
3540 .text_system()
3541 .advance(font_id, font_size, 'm')
3542 .unwrap()
3543 .width;
3544
3545 let gutter_dimensions = snapshot.gutter_dimensions(
3546 font_id,
3547 font_size,
3548 em_width,
3549 self.max_line_number_width(&snapshot, cx),
3550 cx,
3551 );
3552 let text_width = bounds.size.width - gutter_dimensions.width;
3553 let overscroll = size(em_width, px(0.));
3554
3555 snapshot = self.editor.update(cx, |editor, cx| {
3556 editor.last_bounds = Some(bounds);
3557 editor.gutter_width = gutter_dimensions.width;
3558 editor.set_visible_line_count(bounds.size.height / line_height, cx);
3559
3560 let editor_width =
3561 text_width - gutter_dimensions.margin - overscroll.width - em_width;
3562 let wrap_width = match editor.soft_wrap_mode(cx) {
3563 SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
3564 SoftWrap::EditorWidth => editor_width,
3565 SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
3566 };
3567
3568 if editor.set_wrap_width(Some(wrap_width), cx) {
3569 editor.snapshot(cx)
3570 } else {
3571 snapshot
3572 }
3573 });
3574
3575 let wrap_guides = self
3576 .editor
3577 .read(cx)
3578 .wrap_guides(cx)
3579 .iter()
3580 .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
3581 .collect::<SmallVec<[_; 2]>>();
3582
3583 let hitbox = cx.insert_hitbox(bounds, false);
3584 let gutter_hitbox = cx.insert_hitbox(
3585 Bounds {
3586 origin: bounds.origin,
3587 size: size(gutter_dimensions.width, bounds.size.height),
3588 },
3589 false,
3590 );
3591 let text_hitbox = cx.insert_hitbox(
3592 Bounds {
3593 origin: gutter_hitbox.upper_right(),
3594 size: size(text_width, bounds.size.height),
3595 },
3596 false,
3597 );
3598 // Offset the content_bounds from the text_bounds by the gutter margin (which
3599 // is roughly half a character wide) to make hit testing work more like how we want.
3600 let content_origin =
3601 text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
3602
3603 let autoscroll_horizontally = self.editor.update(cx, |editor, cx| {
3604 let autoscroll_horizontally =
3605 editor.autoscroll_vertically(bounds, line_height, cx);
3606 snapshot = editor.snapshot(cx);
3607 autoscroll_horizontally
3608 });
3609
3610 let mut scroll_position = snapshot.scroll_position();
3611 // The scroll position is a fractional point, the whole number of which represents
3612 // the top of the window in terms of display rows.
3613 let start_row = scroll_position.y as u32;
3614 let height_in_lines = bounds.size.height / line_height;
3615 let max_row = snapshot.max_point().row();
3616
3617 // Add 1 to ensure selections bleed off screen
3618 let end_row =
3619 1 + cmp::min((scroll_position.y + height_in_lines).ceil() as u32, max_row);
3620
3621 let buffer_rows = snapshot
3622 .buffer_rows(start_row)
3623 .take((start_row..end_row).len());
3624
3625 let start_anchor = if start_row == 0 {
3626 Anchor::min()
3627 } else {
3628 snapshot.buffer_snapshot.anchor_before(
3629 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
3630 )
3631 };
3632 let end_anchor = if end_row > max_row {
3633 Anchor::max()
3634 } else {
3635 snapshot.buffer_snapshot.anchor_before(
3636 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
3637 )
3638 };
3639
3640 let highlighted_rows = self
3641 .editor
3642 .update(cx, |editor, cx| editor.highlighted_display_rows(cx));
3643 let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
3644 start_anchor..end_anchor,
3645 &snapshot.display_snapshot,
3646 cx.theme().colors(),
3647 );
3648
3649 let redacted_ranges = self.editor.read(cx).redacted_ranges(
3650 start_anchor..end_anchor,
3651 &snapshot.display_snapshot,
3652 cx,
3653 );
3654
3655 let (selections, active_rows, newest_selection_head) = self.layout_selections(
3656 start_anchor,
3657 end_anchor,
3658 &snapshot,
3659 start_row,
3660 end_row,
3661 cx,
3662 );
3663
3664 let (line_numbers, fold_statuses) = self.layout_line_numbers(
3665 start_row..end_row,
3666 buffer_rows.clone(),
3667 &active_rows,
3668 newest_selection_head,
3669 &snapshot,
3670 cx,
3671 );
3672
3673 let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
3674
3675 let mut max_visible_line_width = Pixels::ZERO;
3676 let line_layouts =
3677 self.layout_lines(start_row..end_row, &line_numbers, &snapshot, cx);
3678 for line_with_invisibles in &line_layouts {
3679 if line_with_invisibles.line.width > max_visible_line_width {
3680 max_visible_line_width = line_with_invisibles.line.width;
3681 }
3682 }
3683
3684 let longest_line_width = layout_line(snapshot.longest_row(), &snapshot, &style, cx)
3685 .unwrap()
3686 .width;
3687 let mut scroll_width =
3688 longest_line_width.max(max_visible_line_width) + overscroll.width;
3689 let mut blocks = self.build_blocks(
3690 start_row..end_row,
3691 &snapshot,
3692 &hitbox,
3693 &text_hitbox,
3694 &mut scroll_width,
3695 &gutter_dimensions,
3696 em_width,
3697 gutter_dimensions.width + gutter_dimensions.margin,
3698 line_height,
3699 &line_layouts,
3700 cx,
3701 );
3702
3703 let scroll_pixel_position = point(
3704 scroll_position.x * em_width,
3705 scroll_position.y * line_height,
3706 );
3707
3708 let mut inline_blame = None;
3709 if let Some(newest_selection_head) = newest_selection_head {
3710 let display_row = newest_selection_head.row();
3711 if (start_row..end_row).contains(&display_row) {
3712 let line_layout = &line_layouts[(display_row - start_row) as usize];
3713 inline_blame = self.layout_inline_blame(
3714 display_row,
3715 &snapshot.display_snapshot,
3716 line_layout,
3717 em_width,
3718 content_origin,
3719 scroll_pixel_position,
3720 line_height,
3721 cx,
3722 );
3723 }
3724 }
3725
3726 let blamed_display_rows = self.layout_blame_entries(
3727 buffer_rows,
3728 em_width,
3729 scroll_position,
3730 line_height,
3731 &gutter_hitbox,
3732 gutter_dimensions.git_blame_entries_width,
3733 cx,
3734 );
3735
3736 let scroll_max = point(
3737 ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
3738 max_row as f32,
3739 );
3740
3741 self.editor.update(cx, |editor, cx| {
3742 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
3743
3744 let autoscrolled = if autoscroll_horizontally {
3745 editor.autoscroll_horizontally(
3746 start_row,
3747 text_hitbox.size.width,
3748 scroll_width,
3749 em_width,
3750 &line_layouts,
3751 cx,
3752 )
3753 } else {
3754 false
3755 };
3756
3757 if clamped || autoscrolled {
3758 snapshot = editor.snapshot(cx);
3759 scroll_position = snapshot.scroll_position();
3760 }
3761 });
3762
3763 cx.with_element_id(Some("blocks"), |cx| {
3764 self.layout_blocks(
3765 &mut blocks,
3766 &hitbox,
3767 line_height,
3768 scroll_pixel_position,
3769 cx,
3770 );
3771 });
3772
3773 let cursors = self.layout_cursors(
3774 &snapshot,
3775 &selections,
3776 start_row..end_row,
3777 &line_layouts,
3778 &text_hitbox,
3779 content_origin,
3780 scroll_pixel_position,
3781 line_height,
3782 em_width,
3783 cx,
3784 );
3785
3786 let scrollbar_layout = self.layout_scrollbar(
3787 &snapshot,
3788 bounds,
3789 scroll_position,
3790 line_height,
3791 height_in_lines,
3792 cx,
3793 );
3794
3795 let folds = cx.with_element_id(Some("folds"), |cx| {
3796 self.layout_folds(
3797 &snapshot,
3798 content_origin,
3799 start_anchor..end_anchor,
3800 start_row..end_row,
3801 scroll_pixel_position,
3802 line_height,
3803 &line_layouts,
3804 cx,
3805 )
3806 });
3807
3808 let gutter_settings = EditorSettings::get_global(cx).gutter;
3809
3810 let mut context_menu_visible = false;
3811 let mut code_actions_indicator = None;
3812 if let Some(newest_selection_head) = newest_selection_head {
3813 if (start_row..end_row).contains(&newest_selection_head.row()) {
3814 context_menu_visible = self.layout_context_menu(
3815 line_height,
3816 &hitbox,
3817 &text_hitbox,
3818 content_origin,
3819 start_row,
3820 scroll_pixel_position,
3821 &line_layouts,
3822 newest_selection_head,
3823 cx,
3824 );
3825 if gutter_settings.code_actions {
3826 code_actions_indicator = self.layout_code_actions_indicator(
3827 line_height,
3828 newest_selection_head,
3829 scroll_pixel_position,
3830 &gutter_dimensions,
3831 &gutter_hitbox,
3832 cx,
3833 );
3834 }
3835 }
3836 }
3837
3838 if !context_menu_visible && !cx.has_active_drag() {
3839 self.layout_hover_popovers(
3840 &snapshot,
3841 &hitbox,
3842 &text_hitbox,
3843 start_row..end_row,
3844 content_origin,
3845 scroll_pixel_position,
3846 &line_layouts,
3847 line_height,
3848 em_width,
3849 cx,
3850 );
3851 }
3852
3853 let mouse_context_menu = self.layout_mouse_context_menu(cx);
3854
3855 let fold_indicators = if gutter_settings.folds {
3856 cx.with_element_id(Some("gutter_fold_indicators"), |cx| {
3857 self.layout_gutter_fold_indicators(
3858 fold_statuses,
3859 line_height,
3860 &gutter_dimensions,
3861 gutter_settings,
3862 scroll_pixel_position,
3863 &gutter_hitbox,
3864 cx,
3865 )
3866 })
3867 } else {
3868 Vec::new()
3869 };
3870
3871 let invisible_symbol_font_size = font_size / 2.;
3872 let tab_invisible = cx
3873 .text_system()
3874 .shape_line(
3875 "→".into(),
3876 invisible_symbol_font_size,
3877 &[TextRun {
3878 len: "→".len(),
3879 font: self.style.text.font(),
3880 color: cx.theme().colors().editor_invisible,
3881 background_color: None,
3882 underline: None,
3883 strikethrough: None,
3884 }],
3885 )
3886 .unwrap();
3887 let space_invisible = cx
3888 .text_system()
3889 .shape_line(
3890 "•".into(),
3891 invisible_symbol_font_size,
3892 &[TextRun {
3893 len: "•".len(),
3894 font: self.style.text.font(),
3895 color: cx.theme().colors().editor_invisible,
3896 background_color: None,
3897 underline: None,
3898 strikethrough: None,
3899 }],
3900 )
3901 .unwrap();
3902
3903 EditorLayout {
3904 mode: snapshot.mode,
3905 position_map: Arc::new(PositionMap {
3906 size: bounds.size,
3907 scroll_pixel_position,
3908 scroll_max,
3909 line_layouts,
3910 line_height,
3911 em_width,
3912 em_advance,
3913 snapshot,
3914 }),
3915 visible_display_row_range: start_row..end_row,
3916 wrap_guides,
3917 hitbox,
3918 text_hitbox,
3919 gutter_hitbox,
3920 gutter_dimensions,
3921 content_origin,
3922 scrollbar_layout,
3923 max_row,
3924 active_rows,
3925 highlighted_rows,
3926 highlighted_ranges,
3927 redacted_ranges,
3928 line_numbers,
3929 display_hunks,
3930 blamed_display_rows,
3931 inline_blame,
3932 folds,
3933 blocks,
3934 cursors,
3935 selections,
3936 mouse_context_menu,
3937 code_actions_indicator,
3938 fold_indicators,
3939 tab_invisible,
3940 space_invisible,
3941 }
3942 })
3943 })
3944 }
3945
3946 fn paint(
3947 &mut self,
3948 bounds: Bounds<gpui::Pixels>,
3949 _: &mut Self::BeforeLayout,
3950 layout: &mut Self::AfterLayout,
3951 cx: &mut ElementContext,
3952 ) {
3953 let focus_handle = self.editor.focus_handle(cx);
3954 let key_context = self.editor.read(cx).key_context(cx);
3955 cx.set_focus_handle(&focus_handle);
3956 cx.set_key_context(key_context);
3957 cx.set_view_id(self.editor.entity_id());
3958 cx.handle_input(
3959 &focus_handle,
3960 ElementInputHandler::new(bounds, self.editor.clone()),
3961 );
3962 self.register_actions(cx);
3963 self.register_key_listeners(cx, layout);
3964
3965 let text_style = TextStyleRefinement {
3966 font_size: Some(self.style.text.font_size),
3967 line_height: Some(self.style.text.line_height),
3968 ..Default::default()
3969 };
3970 cx.with_text_style(Some(text_style), |cx| {
3971 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
3972 self.paint_mouse_listeners(layout, cx);
3973
3974 self.paint_background(layout, cx);
3975 if layout.gutter_hitbox.size.width > Pixels::ZERO {
3976 self.paint_gutter(layout, cx);
3977 }
3978 self.paint_text(layout, cx);
3979
3980 if !layout.blocks.is_empty() {
3981 cx.with_element_id(Some("blocks"), |cx| {
3982 self.paint_blocks(layout, cx);
3983 });
3984 }
3985
3986 self.paint_scrollbar(layout, cx);
3987 self.paint_mouse_context_menu(layout, cx);
3988 });
3989 })
3990 }
3991}
3992
3993impl IntoElement for EditorElement {
3994 type Element = Self;
3995
3996 fn into_element(self) -> Self::Element {
3997 self
3998 }
3999}
4000
4001type BufferRow = u32;
4002
4003pub struct EditorLayout {
4004 position_map: Arc<PositionMap>,
4005 hitbox: Hitbox,
4006 text_hitbox: Hitbox,
4007 gutter_hitbox: Hitbox,
4008 gutter_dimensions: GutterDimensions,
4009 content_origin: gpui::Point<Pixels>,
4010 scrollbar_layout: Option<ScrollbarLayout>,
4011 mode: EditorMode,
4012 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
4013 visible_display_row_range: Range<u32>,
4014 active_rows: BTreeMap<u32, bool>,
4015 highlighted_rows: BTreeMap<u32, Hsla>,
4016 line_numbers: Vec<Option<ShapedLine>>,
4017 display_hunks: Vec<DisplayDiffHunk>,
4018 blamed_display_rows: Option<Vec<AnyElement>>,
4019 inline_blame: Option<AnyElement>,
4020 folds: Vec<FoldLayout>,
4021 blocks: Vec<BlockLayout>,
4022 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
4023 redacted_ranges: Vec<Range<DisplayPoint>>,
4024 cursors: Vec<CursorLayout>,
4025 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
4026 max_row: u32,
4027 code_actions_indicator: Option<AnyElement>,
4028 fold_indicators: Vec<Option<AnyElement>>,
4029 mouse_context_menu: Option<AnyElement>,
4030 tab_invisible: ShapedLine,
4031 space_invisible: ShapedLine,
4032}
4033
4034impl EditorLayout {
4035 fn line_end_overshoot(&self) -> Pixels {
4036 0.15 * self.position_map.line_height
4037 }
4038}
4039
4040struct ColoredRange<T> {
4041 start: T,
4042 end: T,
4043 color: Hsla,
4044}
4045
4046#[derive(Clone)]
4047struct ScrollbarLayout {
4048 hitbox: Hitbox,
4049 visible_row_range: Range<f32>,
4050 visible: bool,
4051 height: Pixels,
4052 scroll_height: f32,
4053 first_row_y_offset: Pixels,
4054 row_height: Pixels,
4055}
4056
4057impl ScrollbarLayout {
4058 const BORDER_WIDTH: Pixels = px(1.0);
4059 const MIN_MARKER_HEIGHT: Pixels = px(2.0);
4060
4061 fn thumb_bounds(&self) -> Bounds<Pixels> {
4062 let thumb_top = self.y_for_row(self.visible_row_range.start) - self.first_row_y_offset;
4063 let thumb_bottom = self.y_for_row(self.visible_row_range.end) + self.first_row_y_offset;
4064 Bounds::from_corners(
4065 point(self.hitbox.left(), thumb_top),
4066 point(self.hitbox.right(), thumb_bottom),
4067 )
4068 }
4069
4070 fn y_for_row(&self, row: f32) -> Pixels {
4071 self.hitbox.top() + self.first_row_y_offset + row * self.row_height
4072 }
4073
4074 fn marker_quads_for_ranges(
4075 &self,
4076 row_ranges: impl IntoIterator<Item = ColoredRange<u32>>,
4077 column: usize,
4078 ) -> Vec<PaintQuad> {
4079 let column_width =
4080 px(((self.hitbox.size.width - ScrollbarLayout::BORDER_WIDTH).0 / 3.0).floor());
4081
4082 let left_x = ScrollbarLayout::BORDER_WIDTH + (column as f32 * column_width);
4083 let right_x = left_x + column_width;
4084
4085 let mut background_pixel_ranges = row_ranges
4086 .into_iter()
4087 .map(|range| {
4088 let start_y = self.first_row_y_offset + range.start as f32 * self.row_height;
4089 let end_y = self.first_row_y_offset + (range.end + 1) as f32 * self.row_height;
4090 ColoredRange {
4091 start: start_y,
4092 end: end_y,
4093 color: range.color,
4094 }
4095 })
4096 .peekable();
4097
4098 let mut quads = Vec::new();
4099 while let Some(mut pixel_range) = background_pixel_ranges.next() {
4100 pixel_range.end = pixel_range
4101 .end
4102 .max(pixel_range.start + Self::MIN_MARKER_HEIGHT);
4103 while let Some(next_pixel_range) = background_pixel_ranges.peek() {
4104 if pixel_range.end >= next_pixel_range.start
4105 && pixel_range.color == next_pixel_range.color
4106 {
4107 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
4108 background_pixel_ranges.next();
4109 } else {
4110 break;
4111 }
4112 }
4113
4114 let bounds = Bounds::from_corners(
4115 point(left_x, pixel_range.start),
4116 point(right_x, pixel_range.end),
4117 );
4118 quads.push(quad(
4119 bounds,
4120 Corners::default(),
4121 pixel_range.color,
4122 Edges::default(),
4123 Hsla::transparent_black(),
4124 ));
4125 }
4126
4127 quads
4128 }
4129}
4130
4131struct FoldLayout {
4132 display_range: Range<DisplayPoint>,
4133 hover_element: AnyElement,
4134}
4135
4136struct PositionMap {
4137 size: Size<Pixels>,
4138 line_height: Pixels,
4139 scroll_pixel_position: gpui::Point<Pixels>,
4140 scroll_max: gpui::Point<f32>,
4141 em_width: Pixels,
4142 em_advance: Pixels,
4143 line_layouts: Vec<LineWithInvisibles>,
4144 snapshot: EditorSnapshot,
4145}
4146
4147#[derive(Debug, Copy, Clone)]
4148pub struct PointForPosition {
4149 pub previous_valid: DisplayPoint,
4150 pub next_valid: DisplayPoint,
4151 pub exact_unclipped: DisplayPoint,
4152 pub column_overshoot_after_line_end: u32,
4153}
4154
4155impl PointForPosition {
4156 pub fn as_valid(&self) -> Option<DisplayPoint> {
4157 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
4158 Some(self.previous_valid)
4159 } else {
4160 None
4161 }
4162 }
4163}
4164
4165impl PositionMap {
4166 fn point_for_position(
4167 &self,
4168 text_bounds: Bounds<Pixels>,
4169 position: gpui::Point<Pixels>,
4170 ) -> PointForPosition {
4171 let scroll_position = self.snapshot.scroll_position();
4172 let position = position - text_bounds.origin;
4173 let y = position.y.max(px(0.)).min(self.size.height);
4174 let x = position.x + (scroll_position.x * self.em_width);
4175 let row = ((y / self.line_height) + scroll_position.y) as u32;
4176
4177 let (column, x_overshoot_after_line_end) = if let Some(line) = self
4178 .line_layouts
4179 .get(row as usize - scroll_position.y as usize)
4180 .map(|LineWithInvisibles { line, .. }| line)
4181 {
4182 if let Some(ix) = line.index_for_x(x) {
4183 (ix as u32, px(0.))
4184 } else {
4185 (line.len as u32, px(0.).max(x - line.width))
4186 }
4187 } else {
4188 (0, x)
4189 };
4190
4191 let mut exact_unclipped = DisplayPoint::new(row, column);
4192 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
4193 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
4194
4195 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
4196 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
4197 PointForPosition {
4198 previous_valid,
4199 next_valid,
4200 exact_unclipped,
4201 column_overshoot_after_line_end,
4202 }
4203 }
4204}
4205
4206struct BlockLayout {
4207 row: u32,
4208 element: AnyElement,
4209 available_space: Size<AvailableSpace>,
4210 style: BlockStyle,
4211}
4212
4213fn layout_line(
4214 row: u32,
4215 snapshot: &EditorSnapshot,
4216 style: &EditorStyle,
4217 cx: &WindowContext,
4218) -> Result<ShapedLine> {
4219 let mut line = snapshot.line(row);
4220
4221 if line.len() > MAX_LINE_LEN {
4222 let mut len = MAX_LINE_LEN;
4223 while !line.is_char_boundary(len) {
4224 len -= 1;
4225 }
4226
4227 line.truncate(len);
4228 }
4229
4230 cx.text_system().shape_line(
4231 line.into(),
4232 style.text.font_size.to_pixels(cx.rem_size()),
4233 &[TextRun {
4234 len: snapshot.line_len(row) as usize,
4235 font: style.text.font(),
4236 color: Hsla::default(),
4237 background_color: None,
4238 underline: None,
4239 strikethrough: None,
4240 }],
4241 )
4242}
4243
4244pub struct CursorLayout {
4245 origin: gpui::Point<Pixels>,
4246 block_width: Pixels,
4247 line_height: Pixels,
4248 color: Hsla,
4249 shape: CursorShape,
4250 block_text: Option<ShapedLine>,
4251 cursor_name: Option<AnyElement>,
4252}
4253
4254#[derive(Debug)]
4255pub struct CursorName {
4256 string: SharedString,
4257 color: Hsla,
4258 is_top_row: bool,
4259}
4260
4261impl CursorLayout {
4262 pub fn new(
4263 origin: gpui::Point<Pixels>,
4264 block_width: Pixels,
4265 line_height: Pixels,
4266 color: Hsla,
4267 shape: CursorShape,
4268 block_text: Option<ShapedLine>,
4269 ) -> CursorLayout {
4270 CursorLayout {
4271 origin,
4272 block_width,
4273 line_height,
4274 color,
4275 shape,
4276 block_text,
4277 cursor_name: None,
4278 }
4279 }
4280
4281 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
4282 Bounds {
4283 origin: self.origin + origin,
4284 size: size(self.block_width, self.line_height),
4285 }
4286 }
4287
4288 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
4289 match self.shape {
4290 CursorShape::Bar => Bounds {
4291 origin: self.origin + origin,
4292 size: size(px(2.0), self.line_height),
4293 },
4294 CursorShape::Block | CursorShape::Hollow => Bounds {
4295 origin: self.origin + origin,
4296 size: size(self.block_width, self.line_height),
4297 },
4298 CursorShape::Underscore => Bounds {
4299 origin: self.origin
4300 + origin
4301 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
4302 size: size(self.block_width, px(2.0)),
4303 },
4304 }
4305 }
4306
4307 pub fn layout(
4308 &mut self,
4309 origin: gpui::Point<Pixels>,
4310 cursor_name: Option<CursorName>,
4311 cx: &mut ElementContext,
4312 ) {
4313 if let Some(cursor_name) = cursor_name {
4314 let bounds = self.bounds(origin);
4315 let text_size = self.line_height / 1.5;
4316
4317 let name_origin = if cursor_name.is_top_row {
4318 point(bounds.right() - px(1.), bounds.top())
4319 } else {
4320 point(bounds.left(), bounds.top() - text_size / 2. - px(1.))
4321 };
4322 let mut name_element = div()
4323 .bg(self.color)
4324 .text_size(text_size)
4325 .px_0p5()
4326 .line_height(text_size + px(2.))
4327 .text_color(cursor_name.color)
4328 .child(cursor_name.string.clone())
4329 .into_any_element();
4330
4331 name_element.layout(
4332 name_origin,
4333 size(AvailableSpace::MinContent, AvailableSpace::MinContent),
4334 cx,
4335 );
4336
4337 self.cursor_name = Some(name_element);
4338 }
4339 }
4340
4341 pub fn paint(&mut self, origin: gpui::Point<Pixels>, cx: &mut ElementContext) {
4342 let bounds = self.bounds(origin);
4343
4344 //Draw background or border quad
4345 let cursor = if matches!(self.shape, CursorShape::Hollow) {
4346 outline(bounds, self.color)
4347 } else {
4348 fill(bounds, self.color)
4349 };
4350
4351 if let Some(name) = &mut self.cursor_name {
4352 name.paint(cx);
4353 }
4354
4355 cx.paint_quad(cursor);
4356
4357 if let Some(block_text) = &self.block_text {
4358 block_text
4359 .paint(self.origin + origin, self.line_height, cx)
4360 .log_err();
4361 }
4362 }
4363
4364 pub fn shape(&self) -> CursorShape {
4365 self.shape
4366 }
4367}
4368
4369#[derive(Debug)]
4370pub struct HighlightedRange {
4371 pub start_y: Pixels,
4372 pub line_height: Pixels,
4373 pub lines: Vec<HighlightedRangeLine>,
4374 pub color: Hsla,
4375 pub corner_radius: Pixels,
4376}
4377
4378#[derive(Debug)]
4379pub struct HighlightedRangeLine {
4380 pub start_x: Pixels,
4381 pub end_x: Pixels,
4382}
4383
4384impl HighlightedRange {
4385 pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut ElementContext) {
4386 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
4387 self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
4388 self.paint_lines(
4389 self.start_y + self.line_height,
4390 &self.lines[1..],
4391 bounds,
4392 cx,
4393 );
4394 } else {
4395 self.paint_lines(self.start_y, &self.lines, bounds, cx);
4396 }
4397 }
4398
4399 fn paint_lines(
4400 &self,
4401 start_y: Pixels,
4402 lines: &[HighlightedRangeLine],
4403 _bounds: Bounds<Pixels>,
4404 cx: &mut ElementContext,
4405 ) {
4406 if lines.is_empty() {
4407 return;
4408 }
4409
4410 let first_line = lines.first().unwrap();
4411 let last_line = lines.last().unwrap();
4412
4413 let first_top_left = point(first_line.start_x, start_y);
4414 let first_top_right = point(first_line.end_x, start_y);
4415
4416 let curve_height = point(Pixels::ZERO, self.corner_radius);
4417 let curve_width = |start_x: Pixels, end_x: Pixels| {
4418 let max = (end_x - start_x) / 2.;
4419 let width = if max < self.corner_radius {
4420 max
4421 } else {
4422 self.corner_radius
4423 };
4424
4425 point(width, Pixels::ZERO)
4426 };
4427
4428 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
4429 let mut path = gpui::Path::new(first_top_right - top_curve_width);
4430 path.curve_to(first_top_right + curve_height, first_top_right);
4431
4432 let mut iter = lines.iter().enumerate().peekable();
4433 while let Some((ix, line)) = iter.next() {
4434 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
4435
4436 if let Some((_, next_line)) = iter.peek() {
4437 let next_top_right = point(next_line.end_x, bottom_right.y);
4438
4439 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
4440 Ordering::Equal => {
4441 path.line_to(bottom_right);
4442 }
4443 Ordering::Less => {
4444 let curve_width = curve_width(next_top_right.x, bottom_right.x);
4445 path.line_to(bottom_right - curve_height);
4446 if self.corner_radius > Pixels::ZERO {
4447 path.curve_to(bottom_right - curve_width, bottom_right);
4448 }
4449 path.line_to(next_top_right + curve_width);
4450 if self.corner_radius > Pixels::ZERO {
4451 path.curve_to(next_top_right + curve_height, next_top_right);
4452 }
4453 }
4454 Ordering::Greater => {
4455 let curve_width = curve_width(bottom_right.x, next_top_right.x);
4456 path.line_to(bottom_right - curve_height);
4457 if self.corner_radius > Pixels::ZERO {
4458 path.curve_to(bottom_right + curve_width, bottom_right);
4459 }
4460 path.line_to(next_top_right - curve_width);
4461 if self.corner_radius > Pixels::ZERO {
4462 path.curve_to(next_top_right + curve_height, next_top_right);
4463 }
4464 }
4465 }
4466 } else {
4467 let curve_width = curve_width(line.start_x, line.end_x);
4468 path.line_to(bottom_right - curve_height);
4469 if self.corner_radius > Pixels::ZERO {
4470 path.curve_to(bottom_right - curve_width, bottom_right);
4471 }
4472
4473 let bottom_left = point(line.start_x, bottom_right.y);
4474 path.line_to(bottom_left + curve_width);
4475 if self.corner_radius > Pixels::ZERO {
4476 path.curve_to(bottom_left - curve_height, bottom_left);
4477 }
4478 }
4479 }
4480
4481 if first_line.start_x > last_line.start_x {
4482 let curve_width = curve_width(last_line.start_x, first_line.start_x);
4483 let second_top_left = point(last_line.start_x, start_y + self.line_height);
4484 path.line_to(second_top_left + curve_height);
4485 if self.corner_radius > Pixels::ZERO {
4486 path.curve_to(second_top_left + curve_width, second_top_left);
4487 }
4488 let first_bottom_left = point(first_line.start_x, second_top_left.y);
4489 path.line_to(first_bottom_left - curve_width);
4490 if self.corner_radius > Pixels::ZERO {
4491 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
4492 }
4493 }
4494
4495 path.line_to(first_top_left + curve_height);
4496 if self.corner_radius > Pixels::ZERO {
4497 path.curve_to(first_top_left + top_curve_width, first_top_left);
4498 }
4499 path.line_to(first_top_right - top_curve_width);
4500
4501 cx.paint_path(path, self.color);
4502 }
4503}
4504
4505pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
4506 (delta.pow(1.5) / 100.0).into()
4507}
4508
4509fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
4510 (delta.pow(1.2) / 300.0).into()
4511}
4512
4513#[cfg(test)]
4514mod tests {
4515 use super::*;
4516 use crate::{
4517 display_map::{BlockDisposition, BlockProperties},
4518 editor_tests::{init_test, update_test_language_settings},
4519 Editor, MultiBuffer,
4520 };
4521 use gpui::TestAppContext;
4522 use language::language_settings;
4523 use log::info;
4524 use std::num::NonZeroU32;
4525 use util::test::sample_text;
4526
4527 #[gpui::test]
4528 fn test_shape_line_numbers(cx: &mut TestAppContext) {
4529 init_test(cx, |_| {});
4530 let window = cx.add_window(|cx| {
4531 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
4532 Editor::new(EditorMode::Full, buffer, None, cx)
4533 });
4534
4535 let editor = window.root(cx).unwrap();
4536 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4537 let element = EditorElement::new(&editor, style);
4538 let snapshot = window.update(cx, |editor, cx| editor.snapshot(cx)).unwrap();
4539
4540 let layouts = cx
4541 .update_window(*window, |_, cx| {
4542 cx.with_element_context(|cx| {
4543 element
4544 .layout_line_numbers(
4545 0..6,
4546 (0..6).map(Some),
4547 &Default::default(),
4548 Some(DisplayPoint::new(0, 0)),
4549 &snapshot,
4550 cx,
4551 )
4552 .0
4553 })
4554 })
4555 .unwrap();
4556 assert_eq!(layouts.len(), 6);
4557
4558 let relative_rows = window
4559 .update(cx, |editor, cx| {
4560 let snapshot = editor.snapshot(cx);
4561 element.calculate_relative_line_numbers(&snapshot, &(0..6), Some(3))
4562 })
4563 .unwrap();
4564 assert_eq!(relative_rows[&0], 3);
4565 assert_eq!(relative_rows[&1], 2);
4566 assert_eq!(relative_rows[&2], 1);
4567 // current line has no relative number
4568 assert_eq!(relative_rows[&4], 1);
4569 assert_eq!(relative_rows[&5], 2);
4570
4571 // works if cursor is before screen
4572 let relative_rows = window
4573 .update(cx, |editor, cx| {
4574 let snapshot = editor.snapshot(cx);
4575 element.calculate_relative_line_numbers(&snapshot, &(3..6), Some(1))
4576 })
4577 .unwrap();
4578 assert_eq!(relative_rows.len(), 3);
4579 assert_eq!(relative_rows[&3], 2);
4580 assert_eq!(relative_rows[&4], 3);
4581 assert_eq!(relative_rows[&5], 4);
4582
4583 // works if cursor is after screen
4584 let relative_rows = window
4585 .update(cx, |editor, cx| {
4586 let snapshot = editor.snapshot(cx);
4587 element.calculate_relative_line_numbers(&snapshot, &(0..3), Some(6))
4588 })
4589 .unwrap();
4590 assert_eq!(relative_rows.len(), 3);
4591 assert_eq!(relative_rows[&0], 5);
4592 assert_eq!(relative_rows[&1], 4);
4593 assert_eq!(relative_rows[&2], 3);
4594 }
4595
4596 #[gpui::test]
4597 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
4598 init_test(cx, |_| {});
4599
4600 let window = cx.add_window(|cx| {
4601 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
4602 Editor::new(EditorMode::Full, buffer, None, cx)
4603 });
4604 let editor = window.root(cx).unwrap();
4605 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4606 let mut element = EditorElement::new(&editor, style);
4607
4608 window
4609 .update(cx, |editor, cx| {
4610 editor.cursor_shape = CursorShape::Block;
4611 editor.change_selections(None, cx, |s| {
4612 s.select_ranges([
4613 Point::new(0, 0)..Point::new(1, 0),
4614 Point::new(3, 2)..Point::new(3, 3),
4615 Point::new(5, 6)..Point::new(6, 0),
4616 ]);
4617 });
4618 })
4619 .unwrap();
4620 let state = cx
4621 .update_window(window.into(), |_view, cx| {
4622 cx.with_element_context(|cx| {
4623 element.after_layout(
4624 Bounds {
4625 origin: point(px(500.), px(500.)),
4626 size: size(px(500.), px(500.)),
4627 },
4628 &mut (),
4629 cx,
4630 )
4631 })
4632 })
4633 .unwrap();
4634
4635 assert_eq!(state.selections.len(), 1);
4636 let local_selections = &state.selections[0].1;
4637 assert_eq!(local_selections.len(), 3);
4638 // moves cursor back one line
4639 assert_eq!(local_selections[0].head, DisplayPoint::new(0, 6));
4640 assert_eq!(
4641 local_selections[0].range,
4642 DisplayPoint::new(0, 0)..DisplayPoint::new(1, 0)
4643 );
4644
4645 // moves cursor back one column
4646 assert_eq!(
4647 local_selections[1].range,
4648 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 3)
4649 );
4650 assert_eq!(local_selections[1].head, DisplayPoint::new(3, 2));
4651
4652 // leaves cursor on the max point
4653 assert_eq!(
4654 local_selections[2].range,
4655 DisplayPoint::new(5, 6)..DisplayPoint::new(6, 0)
4656 );
4657 assert_eq!(local_selections[2].head, DisplayPoint::new(6, 0));
4658
4659 // active lines does not include 1 (even though the range of the selection does)
4660 assert_eq!(
4661 state.active_rows.keys().cloned().collect::<Vec<u32>>(),
4662 vec![0, 3, 5, 6]
4663 );
4664
4665 // multi-buffer support
4666 // in DisplayPoint coordinates, this is what we're dealing with:
4667 // 0: [[file
4668 // 1: header]]
4669 // 2: aaaaaa
4670 // 3: bbbbbb
4671 // 4: cccccc
4672 // 5:
4673 // 6: ...
4674 // 7: ffffff
4675 // 8: gggggg
4676 // 9: hhhhhh
4677 // 10:
4678 // 11: [[file
4679 // 12: header]]
4680 // 13: bbbbbb
4681 // 14: cccccc
4682 // 15: dddddd
4683 let window = cx.add_window(|cx| {
4684 let buffer = MultiBuffer::build_multi(
4685 [
4686 (
4687 &(sample_text(8, 6, 'a') + "\n"),
4688 vec![
4689 Point::new(0, 0)..Point::new(3, 0),
4690 Point::new(4, 0)..Point::new(7, 0),
4691 ],
4692 ),
4693 (
4694 &(sample_text(8, 6, 'a') + "\n"),
4695 vec![Point::new(1, 0)..Point::new(3, 0)],
4696 ),
4697 ],
4698 cx,
4699 );
4700 Editor::new(EditorMode::Full, buffer, None, cx)
4701 });
4702 let editor = window.root(cx).unwrap();
4703 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4704 let mut element = EditorElement::new(&editor, style);
4705 let _state = window.update(cx, |editor, cx| {
4706 editor.cursor_shape = CursorShape::Block;
4707 editor.change_selections(None, cx, |s| {
4708 s.select_display_ranges([
4709 DisplayPoint::new(4, 0)..DisplayPoint::new(7, 0),
4710 DisplayPoint::new(10, 0)..DisplayPoint::new(13, 0),
4711 ]);
4712 });
4713 });
4714
4715 let state = cx
4716 .update_window(window.into(), |_view, cx| {
4717 cx.with_element_context(|cx| {
4718 element.after_layout(
4719 Bounds {
4720 origin: point(px(500.), px(500.)),
4721 size: size(px(500.), px(500.)),
4722 },
4723 &mut (),
4724 cx,
4725 )
4726 })
4727 })
4728 .unwrap();
4729 assert_eq!(state.selections.len(), 1);
4730 let local_selections = &state.selections[0].1;
4731 assert_eq!(local_selections.len(), 2);
4732
4733 // moves cursor on excerpt boundary back a line
4734 // and doesn't allow selection to bleed through
4735 assert_eq!(
4736 local_selections[0].range,
4737 DisplayPoint::new(4, 0)..DisplayPoint::new(6, 0)
4738 );
4739 assert_eq!(local_selections[0].head, DisplayPoint::new(5, 0));
4740 // moves cursor on buffer boundary back two lines
4741 // and doesn't allow selection to bleed through
4742 assert_eq!(
4743 local_selections[1].range,
4744 DisplayPoint::new(10, 0)..DisplayPoint::new(11, 0)
4745 );
4746 assert_eq!(local_selections[1].head, DisplayPoint::new(10, 0));
4747 }
4748
4749 #[gpui::test]
4750 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
4751 init_test(cx, |_| {});
4752
4753 let window = cx.add_window(|cx| {
4754 let buffer = MultiBuffer::build_simple("", cx);
4755 Editor::new(EditorMode::Full, buffer, None, cx)
4756 });
4757 let editor = window.root(cx).unwrap();
4758 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4759 window
4760 .update(cx, |editor, cx| {
4761 editor.set_placeholder_text("hello", cx);
4762 editor.insert_blocks(
4763 [BlockProperties {
4764 style: BlockStyle::Fixed,
4765 disposition: BlockDisposition::Above,
4766 height: 3,
4767 position: Anchor::min(),
4768 render: Box::new(|_| div().into_any()),
4769 }],
4770 None,
4771 cx,
4772 );
4773
4774 // Blur the editor so that it displays placeholder text.
4775 cx.blur();
4776 })
4777 .unwrap();
4778
4779 let mut element = EditorElement::new(&editor, style);
4780 let state = cx
4781 .update_window(window.into(), |_view, cx| {
4782 cx.with_element_context(|cx| {
4783 element.after_layout(
4784 Bounds {
4785 origin: point(px(500.), px(500.)),
4786 size: size(px(500.), px(500.)),
4787 },
4788 &mut (),
4789 cx,
4790 )
4791 })
4792 })
4793 .unwrap();
4794
4795 assert_eq!(state.position_map.line_layouts.len(), 4);
4796 assert_eq!(
4797 state
4798 .line_numbers
4799 .iter()
4800 .map(Option::is_some)
4801 .collect::<Vec<_>>(),
4802 &[false, false, false, true]
4803 );
4804 }
4805
4806 #[gpui::test]
4807 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
4808 const TAB_SIZE: u32 = 4;
4809
4810 let input_text = "\t \t|\t| a b";
4811 let expected_invisibles = vec![
4812 Invisible::Tab {
4813 line_start_offset: 0,
4814 },
4815 Invisible::Whitespace {
4816 line_offset: TAB_SIZE as usize,
4817 },
4818 Invisible::Tab {
4819 line_start_offset: TAB_SIZE as usize + 1,
4820 },
4821 Invisible::Tab {
4822 line_start_offset: TAB_SIZE as usize * 2 + 1,
4823 },
4824 Invisible::Whitespace {
4825 line_offset: TAB_SIZE as usize * 3 + 1,
4826 },
4827 Invisible::Whitespace {
4828 line_offset: TAB_SIZE as usize * 3 + 3,
4829 },
4830 ];
4831 assert_eq!(
4832 expected_invisibles.len(),
4833 input_text
4834 .chars()
4835 .filter(|initial_char| initial_char.is_whitespace())
4836 .count(),
4837 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
4838 );
4839
4840 init_test(cx, |s| {
4841 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4842 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
4843 });
4844
4845 let actual_invisibles =
4846 collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, px(500.0));
4847
4848 assert_eq!(expected_invisibles, actual_invisibles);
4849 }
4850
4851 #[gpui::test]
4852 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
4853 init_test(cx, |s| {
4854 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4855 s.defaults.tab_size = NonZeroU32::new(4);
4856 });
4857
4858 for editor_mode_without_invisibles in [
4859 EditorMode::SingleLine,
4860 EditorMode::AutoHeight { max_lines: 100 },
4861 ] {
4862 let invisibles = collect_invisibles_from_new_editor(
4863 cx,
4864 editor_mode_without_invisibles,
4865 "\t\t\t| | a b",
4866 px(500.0),
4867 );
4868 assert!(invisibles.is_empty(),
4869 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
4870 }
4871 }
4872
4873 #[gpui::test]
4874 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
4875 let tab_size = 4;
4876 let input_text = "a\tbcd ".repeat(9);
4877 let repeated_invisibles = [
4878 Invisible::Tab {
4879 line_start_offset: 1,
4880 },
4881 Invisible::Whitespace {
4882 line_offset: tab_size as usize + 3,
4883 },
4884 Invisible::Whitespace {
4885 line_offset: tab_size as usize + 4,
4886 },
4887 Invisible::Whitespace {
4888 line_offset: tab_size as usize + 5,
4889 },
4890 ];
4891 let expected_invisibles = std::iter::once(repeated_invisibles)
4892 .cycle()
4893 .take(9)
4894 .flatten()
4895 .collect::<Vec<_>>();
4896 assert_eq!(
4897 expected_invisibles.len(),
4898 input_text
4899 .chars()
4900 .filter(|initial_char| initial_char.is_whitespace())
4901 .count(),
4902 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
4903 );
4904 info!("Expected invisibles: {expected_invisibles:?}");
4905
4906 init_test(cx, |_| {});
4907
4908 // Put the same string with repeating whitespace pattern into editors of various size,
4909 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
4910 let resize_step = 10.0;
4911 let mut editor_width = 200.0;
4912 while editor_width <= 1000.0 {
4913 update_test_language_settings(cx, |s| {
4914 s.defaults.tab_size = NonZeroU32::new(tab_size);
4915 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4916 s.defaults.preferred_line_length = Some(editor_width as u32);
4917 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
4918 });
4919
4920 let actual_invisibles = collect_invisibles_from_new_editor(
4921 cx,
4922 EditorMode::Full,
4923 &input_text,
4924 px(editor_width),
4925 );
4926
4927 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
4928 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
4929 let mut i = 0;
4930 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
4931 i = actual_index;
4932 match expected_invisibles.get(i) {
4933 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
4934 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
4935 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
4936 _ => {
4937 panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
4938 }
4939 },
4940 None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
4941 }
4942 }
4943 let missing_expected_invisibles = &expected_invisibles[i + 1..];
4944 assert!(
4945 missing_expected_invisibles.is_empty(),
4946 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
4947 );
4948
4949 editor_width += resize_step;
4950 }
4951 }
4952
4953 fn collect_invisibles_from_new_editor(
4954 cx: &mut TestAppContext,
4955 editor_mode: EditorMode,
4956 input_text: &str,
4957 editor_width: Pixels,
4958 ) -> Vec<Invisible> {
4959 info!(
4960 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
4961 editor_width.0
4962 );
4963 let window = cx.add_window(|cx| {
4964 let buffer = MultiBuffer::build_simple(&input_text, cx);
4965 Editor::new(editor_mode, buffer, None, cx)
4966 });
4967 let editor = window.root(cx).unwrap();
4968 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4969 let mut element = EditorElement::new(&editor, style);
4970 window
4971 .update(cx, |editor, cx| {
4972 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
4973 editor.set_wrap_width(Some(editor_width), cx);
4974 })
4975 .unwrap();
4976 let layout_state = cx
4977 .update_window(window.into(), |_, cx| {
4978 cx.with_element_context(|cx| {
4979 element.after_layout(
4980 Bounds {
4981 origin: point(px(500.), px(500.)),
4982 size: size(px(500.), px(500.)),
4983 },
4984 &mut (),
4985 cx,
4986 )
4987 })
4988 })
4989 .unwrap();
4990
4991 layout_state
4992 .position_map
4993 .line_layouts
4994 .iter()
4995 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
4996 .cloned()
4997 .collect()
4998 }
4999}
5000
5001pub fn register_action<T: Action>(
5002 view: &View<Editor>,
5003 cx: &mut WindowContext,
5004 listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
5005) {
5006 let view = view.clone();
5007 cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
5008 let action = action.downcast_ref().unwrap();
5009 if phase == DispatchPhase::Bubble {
5010 view.update(cx, |editor, cx| {
5011 listener(editor, action, cx);
5012 })
5013 }
5014 })
5015}
5016
5017fn compute_auto_height_layout(
5018 editor: &mut Editor,
5019 max_lines: usize,
5020 max_line_number_width: Pixels,
5021 known_dimensions: Size<Option<Pixels>>,
5022 cx: &mut ViewContext<Editor>,
5023) -> Option<Size<Pixels>> {
5024 let width = known_dimensions.width?;
5025 if let Some(height) = known_dimensions.height {
5026 return Some(size(width, height));
5027 }
5028
5029 let style = editor.style.as_ref().unwrap();
5030 let font_id = cx.text_system().resolve_font(&style.text.font());
5031 let font_size = style.text.font_size.to_pixels(cx.rem_size());
5032 let line_height = style.text.line_height_in_pixels(cx.rem_size());
5033 let em_width = cx
5034 .text_system()
5035 .typographic_bounds(font_id, font_size, 'm')
5036 .unwrap()
5037 .size
5038 .width;
5039
5040 let mut snapshot = editor.snapshot(cx);
5041 let gutter_dimensions =
5042 snapshot.gutter_dimensions(font_id, font_size, em_width, max_line_number_width, cx);
5043
5044 editor.gutter_width = gutter_dimensions.width;
5045 let text_width = width - gutter_dimensions.width;
5046 let overscroll = size(em_width, px(0.));
5047
5048 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
5049 if editor.set_wrap_width(Some(editor_width), cx) {
5050 snapshot = editor.snapshot(cx);
5051 }
5052
5053 let scroll_height = Pixels::from(snapshot.max_point().row() + 1) * line_height;
5054 let height = scroll_height
5055 .max(line_height)
5056 .min(line_height * max_lines as f32);
5057
5058 Some(size(width, height))
5059}