1use crate::editor_settings::ScrollBeyondLastLine;
2use crate::TransformBlockId;
3use crate::{
4 blame_entry_tooltip::{blame_entry_relative_timestamp, BlameEntryTooltip},
5 display_map::{
6 BlockContext, BlockStyle, DisplaySnapshot, HighlightedChunk, ToDisplayPoint, TransformBlock,
7 },
8 editor_settings::{
9 CurrentLineHighlight, DoubleClickInMultibuffer, MultiCursorModifier, ShowScrollbar,
10 },
11 git::{
12 blame::{CommitDetails, GitBlame},
13 diff_hunk_to_display, DisplayDiffHunk,
14 },
15 hover_popover::{
16 self, hover_at, HOVER_POPOVER_GAP, MIN_POPOVER_CHARACTER_WIDTH, MIN_POPOVER_LINE_HEIGHT,
17 },
18 hunk_status,
19 items::BufferSearchHighlights,
20 mouse_context_menu::{self, MouseContextMenu},
21 scroll::scroll_amount::ScrollAmount,
22 CodeActionsMenu, CursorShape, DisplayPoint, DisplayRow, DocumentHighlightRead,
23 DocumentHighlightWrite, Editor, EditorMode, EditorSettings, EditorSnapshot, EditorStyle,
24 ExpandExcerpts, GutterDimensions, HalfPageDown, HalfPageUp, HoveredCursor, HunkToExpand,
25 LineDown, LineUp, OpenExcerpts, PageDown, PageUp, Point, RowExt, RowRangeExt, SelectPhase,
26 Selection, SoftWrap, ToPoint, CURSORS_VISIBLE_FOR, MAX_LINE_LEN,
27};
28use client::ParticipantIndex;
29use collections::{BTreeMap, HashMap};
30use git::{blame::BlameEntry, diff::DiffHunkStatus, Oid};
31use gpui::{
32 anchored, deferred, div, fill, outline, point, px, quad, relative, size, svg,
33 transparent_black, Action, AnchorCorner, AnyElement, AvailableSpace, Bounds, ClipboardItem,
34 ContentMask, Corners, CursorStyle, DispatchPhase, Edges, Element, ElementInputHandler, Entity,
35 EntityId, FontId, GlobalElementId, Hitbox, Hsla, InteractiveElement, IntoElement, Length,
36 ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PaintQuad,
37 ParentElement, Pixels, ScrollDelta, ScrollWheelEvent, ShapedLine, SharedString, Size,
38 StatefulInteractiveElement, Style, Styled, TextRun, TextStyle, TextStyleRefinement, View,
39 ViewContext, WeakView, WindowContext,
40};
41use itertools::Itertools;
42use language::language_settings::{
43 IndentGuideBackgroundColoring, IndentGuideColoring, IndentGuideSettings, ShowWhitespaceSetting,
44};
45use lsp::DiagnosticSeverity;
46use multi_buffer::{Anchor, MultiBufferPoint, MultiBufferRow};
47use project::{
48 project_settings::{GitGutterSetting, ProjectSettings},
49 ProjectPath,
50};
51use settings::Settings;
52use smallvec::{smallvec, SmallVec};
53use std::{
54 any::TypeId,
55 borrow::Cow,
56 cmp::{self, Ordering},
57 fmt::{self, Write},
58 iter, mem,
59 ops::{Deref, Range},
60 sync::Arc,
61};
62use sum_tree::Bias;
63use theme::{ActiveTheme, PlayerColor};
64use ui::prelude::*;
65use ui::{h_flex, ButtonLike, ButtonStyle, ContextMenu, Tooltip};
66use util::ResultExt;
67use workspace::{item::Item, Workspace};
68
69struct SelectionLayout {
70 head: DisplayPoint,
71 cursor_shape: CursorShape,
72 is_newest: bool,
73 is_local: bool,
74 range: Range<DisplayPoint>,
75 active_rows: Range<DisplayRow>,
76 user_name: Option<SharedString>,
77}
78
79impl SelectionLayout {
80 fn new<T: ToPoint + ToDisplayPoint + Clone>(
81 selection: Selection<T>,
82 line_mode: bool,
83 cursor_shape: CursorShape,
84 map: &DisplaySnapshot,
85 is_newest: bool,
86 is_local: bool,
87 user_name: Option<SharedString>,
88 ) -> Self {
89 let point_selection = selection.map(|p| p.to_point(&map.buffer_snapshot));
90 let display_selection = point_selection.map(|p| p.to_display_point(map));
91 let mut range = display_selection.range();
92 let mut head = display_selection.head();
93 let mut active_rows = map.prev_line_boundary(point_selection.start).1.row()
94 ..map.next_line_boundary(point_selection.end).1.row();
95
96 // vim visual line mode
97 if line_mode {
98 let point_range = map.expand_to_line(point_selection.range());
99 range = point_range.start.to_display_point(map)..point_range.end.to_display_point(map);
100 }
101
102 // any vim visual mode (including line mode)
103 if (cursor_shape == CursorShape::Block || cursor_shape == CursorShape::Hollow)
104 && !range.is_empty()
105 && !selection.reversed
106 {
107 if head.column() > 0 {
108 head = map.clip_point(DisplayPoint::new(head.row(), head.column() - 1), Bias::Left)
109 } else if head.row().0 > 0 && head != map.max_point() {
110 head = map.clip_point(
111 DisplayPoint::new(
112 head.row().previous_row(),
113 map.line_len(head.row().previous_row()),
114 ),
115 Bias::Left,
116 );
117 // updating range.end is a no-op unless you're cursor is
118 // on the newline containing a multi-buffer divider
119 // in which case the clip_point may have moved the head up
120 // an additional row.
121 range.end = DisplayPoint::new(head.row().next_row(), 0);
122 active_rows.end = head.row();
123 }
124 }
125
126 Self {
127 head,
128 cursor_shape,
129 is_newest,
130 is_local,
131 range,
132 active_rows,
133 user_name,
134 }
135 }
136}
137
138pub struct EditorElement {
139 editor: View<Editor>,
140 style: EditorStyle,
141}
142
143type DisplayRowDelta = u32;
144
145impl EditorElement {
146 pub(crate) const SCROLLBAR_WIDTH: Pixels = px(13.);
147
148 pub fn new(editor: &View<Editor>, style: EditorStyle) -> Self {
149 Self {
150 editor: editor.clone(),
151 style,
152 }
153 }
154
155 fn register_actions(&self, cx: &mut WindowContext) {
156 let view = &self.editor;
157 view.update(cx, |editor, cx| {
158 for action in editor.editor_actions.borrow().values() {
159 (action)(cx)
160 }
161 });
162
163 crate::rust_analyzer_ext::apply_related_actions(view, cx);
164 register_action(view, cx, Editor::move_left);
165 register_action(view, cx, Editor::move_right);
166 register_action(view, cx, Editor::move_down);
167 register_action(view, cx, Editor::move_down_by_lines);
168 register_action(view, cx, Editor::select_down_by_lines);
169 register_action(view, cx, Editor::move_up);
170 register_action(view, cx, Editor::move_up_by_lines);
171 register_action(view, cx, Editor::select_up_by_lines);
172 register_action(view, cx, Editor::select_page_down);
173 register_action(view, cx, Editor::select_page_up);
174 register_action(view, cx, Editor::cancel);
175 register_action(view, cx, Editor::newline);
176 register_action(view, cx, Editor::newline_above);
177 register_action(view, cx, Editor::newline_below);
178 register_action(view, cx, Editor::backspace);
179 register_action(view, cx, Editor::delete);
180 register_action(view, cx, Editor::tab);
181 register_action(view, cx, Editor::tab_prev);
182 register_action(view, cx, Editor::indent);
183 register_action(view, cx, Editor::outdent);
184 register_action(view, cx, Editor::delete_line);
185 register_action(view, cx, Editor::join_lines);
186 register_action(view, cx, Editor::sort_lines_case_sensitive);
187 register_action(view, cx, Editor::sort_lines_case_insensitive);
188 register_action(view, cx, Editor::reverse_lines);
189 register_action(view, cx, Editor::shuffle_lines);
190 register_action(view, cx, Editor::convert_to_upper_case);
191 register_action(view, cx, Editor::convert_to_lower_case);
192 register_action(view, cx, Editor::convert_to_title_case);
193 register_action(view, cx, Editor::convert_to_snake_case);
194 register_action(view, cx, Editor::convert_to_kebab_case);
195 register_action(view, cx, Editor::convert_to_upper_camel_case);
196 register_action(view, cx, Editor::convert_to_lower_camel_case);
197 register_action(view, cx, Editor::convert_to_opposite_case);
198 register_action(view, cx, Editor::delete_to_previous_word_start);
199 register_action(view, cx, Editor::delete_to_previous_subword_start);
200 register_action(view, cx, Editor::delete_to_next_word_end);
201 register_action(view, cx, Editor::delete_to_next_subword_end);
202 register_action(view, cx, Editor::delete_to_beginning_of_line);
203 register_action(view, cx, Editor::delete_to_end_of_line);
204 register_action(view, cx, Editor::cut_to_end_of_line);
205 register_action(view, cx, Editor::duplicate_line_up);
206 register_action(view, cx, Editor::duplicate_line_down);
207 register_action(view, cx, Editor::move_line_up);
208 register_action(view, cx, Editor::move_line_down);
209 register_action(view, cx, Editor::transpose);
210 register_action(view, cx, Editor::cut);
211 register_action(view, cx, Editor::copy);
212 register_action(view, cx, Editor::paste);
213 register_action(view, cx, Editor::undo);
214 register_action(view, cx, Editor::redo);
215 register_action(view, cx, Editor::move_page_up);
216 register_action(view, cx, Editor::move_page_down);
217 register_action(view, cx, Editor::next_screen);
218 register_action(view, cx, Editor::scroll_cursor_top);
219 register_action(view, cx, Editor::scroll_cursor_center);
220 register_action(view, cx, Editor::scroll_cursor_bottom);
221 register_action(view, cx, |editor, _: &LineDown, cx| {
222 editor.scroll_screen(&ScrollAmount::Line(1.), cx)
223 });
224 register_action(view, cx, |editor, _: &LineUp, cx| {
225 editor.scroll_screen(&ScrollAmount::Line(-1.), cx)
226 });
227 register_action(view, cx, |editor, _: &HalfPageDown, cx| {
228 editor.scroll_screen(&ScrollAmount::Page(0.5), cx)
229 });
230 register_action(view, cx, |editor, _: &HalfPageUp, cx| {
231 editor.scroll_screen(&ScrollAmount::Page(-0.5), cx)
232 });
233 register_action(view, cx, |editor, _: &PageDown, cx| {
234 editor.scroll_screen(&ScrollAmount::Page(1.), cx)
235 });
236 register_action(view, cx, |editor, _: &PageUp, cx| {
237 editor.scroll_screen(&ScrollAmount::Page(-1.), cx)
238 });
239 register_action(view, cx, Editor::move_to_previous_word_start);
240 register_action(view, cx, Editor::move_to_previous_subword_start);
241 register_action(view, cx, Editor::move_to_next_word_end);
242 register_action(view, cx, Editor::move_to_next_subword_end);
243 register_action(view, cx, Editor::move_to_beginning_of_line);
244 register_action(view, cx, Editor::move_to_end_of_line);
245 register_action(view, cx, Editor::move_to_start_of_paragraph);
246 register_action(view, cx, Editor::move_to_end_of_paragraph);
247 register_action(view, cx, Editor::move_to_beginning);
248 register_action(view, cx, Editor::move_to_end);
249 register_action(view, cx, Editor::select_up);
250 register_action(view, cx, Editor::select_down);
251 register_action(view, cx, Editor::select_left);
252 register_action(view, cx, Editor::select_right);
253 register_action(view, cx, Editor::select_to_previous_word_start);
254 register_action(view, cx, Editor::select_to_previous_subword_start);
255 register_action(view, cx, Editor::select_to_next_word_end);
256 register_action(view, cx, Editor::select_to_next_subword_end);
257 register_action(view, cx, Editor::select_to_beginning_of_line);
258 register_action(view, cx, Editor::select_to_end_of_line);
259 register_action(view, cx, Editor::select_to_start_of_paragraph);
260 register_action(view, cx, Editor::select_to_end_of_paragraph);
261 register_action(view, cx, Editor::select_to_beginning);
262 register_action(view, cx, Editor::select_to_end);
263 register_action(view, cx, Editor::select_all);
264 register_action(view, cx, |editor, action, cx| {
265 editor.select_all_matches(action, cx).log_err();
266 });
267 register_action(view, cx, Editor::select_line);
268 register_action(view, cx, Editor::split_selection_into_lines);
269 register_action(view, cx, Editor::add_selection_above);
270 register_action(view, cx, Editor::add_selection_below);
271 register_action(view, cx, |editor, action, cx| {
272 editor.select_next(action, cx).log_err();
273 });
274 register_action(view, cx, |editor, action, cx| {
275 editor.select_previous(action, cx).log_err();
276 });
277 register_action(view, cx, Editor::toggle_comments);
278 register_action(view, cx, Editor::select_larger_syntax_node);
279 register_action(view, cx, Editor::select_smaller_syntax_node);
280 register_action(view, cx, Editor::select_enclosing_symbol);
281 register_action(view, cx, Editor::move_to_enclosing_bracket);
282 register_action(view, cx, Editor::undo_selection);
283 register_action(view, cx, Editor::redo_selection);
284 if !view.read(cx).is_singleton(cx) {
285 register_action(view, cx, Editor::expand_excerpts);
286 register_action(view, cx, Editor::expand_excerpts_up);
287 register_action(view, cx, Editor::expand_excerpts_down);
288 }
289 register_action(view, cx, Editor::go_to_diagnostic);
290 register_action(view, cx, Editor::go_to_prev_diagnostic);
291 register_action(view, cx, Editor::go_to_hunk);
292 register_action(view, cx, Editor::go_to_prev_hunk);
293 register_action(view, cx, |editor, a, cx| {
294 editor.go_to_definition(a, cx).detach_and_log_err(cx);
295 });
296 register_action(view, cx, |editor, a, cx| {
297 editor.go_to_definition_split(a, cx).detach_and_log_err(cx);
298 });
299 register_action(view, cx, |editor, a, cx| {
300 editor.go_to_implementation(a, cx).detach_and_log_err(cx);
301 });
302 register_action(view, cx, |editor, a, cx| {
303 editor
304 .go_to_implementation_split(a, cx)
305 .detach_and_log_err(cx);
306 });
307 register_action(view, cx, |editor, a, cx| {
308 editor.go_to_type_definition(a, cx).detach_and_log_err(cx);
309 });
310 register_action(view, cx, |editor, a, cx| {
311 editor
312 .go_to_type_definition_split(a, cx)
313 .detach_and_log_err(cx);
314 });
315 register_action(view, cx, Editor::open_url);
316 register_action(view, cx, Editor::fold);
317 register_action(view, cx, Editor::fold_at);
318 register_action(view, cx, Editor::unfold_lines);
319 register_action(view, cx, Editor::unfold_at);
320 register_action(view, cx, Editor::fold_selected_ranges);
321 register_action(view, cx, Editor::show_completions);
322 register_action(view, cx, Editor::toggle_code_actions);
323 register_action(view, cx, Editor::open_excerpts);
324 register_action(view, cx, Editor::open_excerpts_in_split);
325 register_action(view, cx, Editor::toggle_soft_wrap);
326 register_action(view, cx, Editor::toggle_tab_bar);
327 register_action(view, cx, Editor::toggle_line_numbers);
328 register_action(view, cx, Editor::toggle_indent_guides);
329 register_action(view, cx, Editor::toggle_inlay_hints);
330 register_action(view, cx, hover_popover::hover);
331 register_action(view, cx, Editor::reveal_in_finder);
332 register_action(view, cx, Editor::copy_path);
333 register_action(view, cx, Editor::copy_relative_path);
334 register_action(view, cx, Editor::copy_highlight_json);
335 register_action(view, cx, Editor::copy_permalink_to_line);
336 register_action(view, cx, Editor::open_permalink_to_line);
337 register_action(view, cx, Editor::toggle_git_blame);
338 register_action(view, cx, Editor::toggle_git_blame_inline);
339 register_action(view, cx, Editor::toggle_hunk_diff);
340 register_action(view, cx, Editor::expand_all_hunk_diffs);
341 register_action(view, cx, |editor, action, cx| {
342 if let Some(task) = editor.format(action, cx) {
343 task.detach_and_log_err(cx);
344 } else {
345 cx.propagate();
346 }
347 });
348 register_action(view, cx, Editor::restart_language_server);
349 register_action(view, cx, Editor::cancel_language_server_work);
350 register_action(view, cx, Editor::show_character_palette);
351 register_action(view, cx, |editor, action, cx| {
352 if let Some(task) = editor.confirm_completion(action, cx) {
353 task.detach_and_log_err(cx);
354 } else {
355 cx.propagate();
356 }
357 });
358 register_action(view, cx, |editor, action, cx| {
359 if let Some(task) = editor.confirm_code_action(action, cx) {
360 task.detach_and_log_err(cx);
361 } else {
362 cx.propagate();
363 }
364 });
365 register_action(view, cx, |editor, action, cx| {
366 if let Some(task) = editor.rename(action, cx) {
367 task.detach_and_log_err(cx);
368 } else {
369 cx.propagate();
370 }
371 });
372 register_action(view, cx, |editor, action, cx| {
373 if let Some(task) = editor.confirm_rename(action, cx) {
374 task.detach_and_log_err(cx);
375 } else {
376 cx.propagate();
377 }
378 });
379 register_action(view, cx, |editor, action, cx| {
380 if let Some(task) = editor.find_all_references(action, cx) {
381 task.detach_and_log_err(cx);
382 } else {
383 cx.propagate();
384 }
385 });
386 register_action(view, cx, Editor::show_signature_help);
387 register_action(view, cx, Editor::next_inline_completion);
388 register_action(view, cx, Editor::previous_inline_completion);
389 register_action(view, cx, Editor::show_inline_completion);
390 register_action(view, cx, Editor::context_menu_first);
391 register_action(view, cx, Editor::context_menu_prev);
392 register_action(view, cx, Editor::context_menu_next);
393 register_action(view, cx, Editor::context_menu_last);
394 register_action(view, cx, Editor::display_cursor_names);
395 register_action(view, cx, Editor::unique_lines_case_insensitive);
396 register_action(view, cx, Editor::unique_lines_case_sensitive);
397 register_action(view, cx, Editor::accept_partial_inline_completion);
398 register_action(view, cx, Editor::accept_inline_completion);
399 register_action(view, cx, Editor::revert_selected_hunks);
400 register_action(view, cx, Editor::open_active_item_in_terminal)
401 }
402
403 fn register_key_listeners(&self, cx: &mut WindowContext, layout: &EditorLayout) {
404 let position_map = layout.position_map.clone();
405 cx.on_key_event({
406 let editor = self.editor.clone();
407 let text_hitbox = layout.text_hitbox.clone();
408 move |event: &ModifiersChangedEvent, phase, cx| {
409 if phase != DispatchPhase::Bubble {
410 return;
411 }
412 editor.update(cx, |editor, cx| {
413 if editor.hover_state.focused(cx) {
414 return;
415 }
416 Self::modifiers_changed(editor, event, &position_map, &text_hitbox, cx)
417 })
418 }
419 });
420 }
421
422 fn modifiers_changed(
423 editor: &mut Editor,
424 event: &ModifiersChangedEvent,
425 position_map: &PositionMap,
426 text_hitbox: &Hitbox,
427 cx: &mut ViewContext<Editor>,
428 ) {
429 let mouse_position = cx.mouse_position();
430 if !text_hitbox.is_hovered(cx) {
431 return;
432 }
433
434 editor.update_hovered_link(
435 position_map.point_for_position(text_hitbox.bounds, mouse_position),
436 &position_map.snapshot,
437 event.modifiers,
438 cx,
439 )
440 }
441
442 fn mouse_left_down(
443 editor: &mut Editor,
444 event: &MouseDownEvent,
445 hovered_hunk: Option<&HunkToExpand>,
446 position_map: &PositionMap,
447 text_hitbox: &Hitbox,
448 gutter_hitbox: &Hitbox,
449 cx: &mut ViewContext<Editor>,
450 ) {
451 if cx.default_prevented() {
452 return;
453 }
454
455 let mut click_count = event.click_count;
456 let mut modifiers = event.modifiers;
457
458 if let Some(hovered_hunk) = hovered_hunk {
459 editor.expand_diff_hunk(None, hovered_hunk, cx);
460 cx.notify();
461 return;
462 } else if gutter_hitbox.is_hovered(cx) {
463 click_count = 3; // Simulate triple-click when clicking the gutter to select lines
464 } else if !text_hitbox.is_hovered(cx) {
465 return;
466 }
467
468 if click_count == 2 && !editor.buffer().read(cx).is_singleton() {
469 match EditorSettings::get_global(cx).double_click_in_multibuffer {
470 DoubleClickInMultibuffer::Select => {
471 // do nothing special on double click, all selection logic is below
472 }
473 DoubleClickInMultibuffer::Open => {
474 if modifiers.alt {
475 // if double click is made with alt, pretend it's a regular double click without opening and alt,
476 // and run the selection logic.
477 modifiers.alt = false;
478 } else {
479 // if double click is made without alt, open the corresponding excerp
480 editor.open_excerpts(&OpenExcerpts, cx);
481 return;
482 }
483 }
484 }
485 }
486
487 let point_for_position =
488 position_map.point_for_position(text_hitbox.bounds, event.position);
489 let position = point_for_position.previous_valid;
490 if modifiers.shift && modifiers.alt {
491 editor.select(
492 SelectPhase::BeginColumnar {
493 position,
494 reset: false,
495 goal_column: point_for_position.exact_unclipped.column(),
496 },
497 cx,
498 );
499 } else if modifiers.shift && !modifiers.control && !modifiers.alt && !modifiers.secondary()
500 {
501 editor.select(
502 SelectPhase::Extend {
503 position,
504 click_count,
505 },
506 cx,
507 );
508 } else {
509 let multi_cursor_setting = EditorSettings::get_global(cx).multi_cursor_modifier;
510 let multi_cursor_modifier = match multi_cursor_setting {
511 MultiCursorModifier::Alt => modifiers.alt,
512 MultiCursorModifier::CmdOrCtrl => modifiers.secondary(),
513 };
514 editor.select(
515 SelectPhase::Begin {
516 position,
517 add: multi_cursor_modifier,
518 click_count,
519 },
520 cx,
521 );
522 }
523
524 cx.stop_propagation();
525 }
526
527 fn mouse_right_down(
528 editor: &mut Editor,
529 event: &MouseDownEvent,
530 position_map: &PositionMap,
531 text_hitbox: &Hitbox,
532 cx: &mut ViewContext<Editor>,
533 ) {
534 if !text_hitbox.is_hovered(cx) {
535 return;
536 }
537 let point_for_position =
538 position_map.point_for_position(text_hitbox.bounds, event.position);
539 mouse_context_menu::deploy_context_menu(
540 editor,
541 event.position,
542 point_for_position.previous_valid,
543 cx,
544 );
545 cx.stop_propagation();
546 }
547
548 fn mouse_middle_down(
549 editor: &mut Editor,
550 event: &MouseDownEvent,
551 position_map: &PositionMap,
552 text_hitbox: &Hitbox,
553 cx: &mut ViewContext<Editor>,
554 ) {
555 if !text_hitbox.is_hovered(cx) || cx.default_prevented() {
556 return;
557 }
558
559 let point_for_position =
560 position_map.point_for_position(text_hitbox.bounds, event.position);
561 let position = point_for_position.previous_valid;
562
563 editor.select(
564 SelectPhase::BeginColumnar {
565 position,
566 reset: true,
567 goal_column: point_for_position.exact_unclipped.column(),
568 },
569 cx,
570 );
571 }
572
573 fn mouse_up(
574 editor: &mut Editor,
575 event: &MouseUpEvent,
576 position_map: &PositionMap,
577 text_hitbox: &Hitbox,
578 cx: &mut ViewContext<Editor>,
579 ) {
580 let end_selection = editor.has_pending_selection();
581 let pending_nonempty_selections = editor.has_pending_nonempty_selection();
582
583 if end_selection {
584 editor.select(SelectPhase::End, cx);
585 }
586
587 let multi_cursor_setting = EditorSettings::get_global(cx).multi_cursor_modifier;
588 let multi_cursor_modifier = match multi_cursor_setting {
589 MultiCursorModifier::Alt => event.modifiers.secondary(),
590 MultiCursorModifier::CmdOrCtrl => event.modifiers.alt,
591 };
592
593 if !pending_nonempty_selections && multi_cursor_modifier && text_hitbox.is_hovered(cx) {
594 let point = position_map.point_for_position(text_hitbox.bounds, event.position);
595 editor.handle_click_hovered_link(point, event.modifiers, cx);
596
597 cx.stop_propagation();
598 } else if end_selection && pending_nonempty_selections {
599 cx.stop_propagation();
600 } else if cfg!(target_os = "linux") && event.button == MouseButton::Middle {
601 if !text_hitbox.is_hovered(cx) || editor.read_only(cx) {
602 return;
603 }
604
605 #[cfg(target_os = "linux")]
606 if let Some(item) = cx.read_from_primary() {
607 let point_for_position =
608 position_map.point_for_position(text_hitbox.bounds, event.position);
609 let position = point_for_position.previous_valid;
610
611 editor.select(
612 SelectPhase::Begin {
613 position,
614 add: false,
615 click_count: 1,
616 },
617 cx,
618 );
619 editor.insert(item.text(), cx);
620 }
621 cx.stop_propagation()
622 }
623 }
624
625 fn mouse_dragged(
626 editor: &mut Editor,
627 event: &MouseMoveEvent,
628 position_map: &PositionMap,
629 text_bounds: Bounds<Pixels>,
630 cx: &mut ViewContext<Editor>,
631 ) {
632 if !editor.has_pending_selection() {
633 return;
634 }
635
636 let point_for_position = position_map.point_for_position(text_bounds, event.position);
637 let mut scroll_delta = gpui::Point::<f32>::default();
638 let vertical_margin = position_map.line_height.min(text_bounds.size.height / 3.0);
639 let top = text_bounds.origin.y + vertical_margin;
640 let bottom = text_bounds.lower_left().y - vertical_margin;
641 if event.position.y < top {
642 scroll_delta.y = -scale_vertical_mouse_autoscroll_delta(top - event.position.y);
643 }
644 if event.position.y > bottom {
645 scroll_delta.y = scale_vertical_mouse_autoscroll_delta(event.position.y - bottom);
646 }
647
648 let horizontal_margin = position_map.line_height.min(text_bounds.size.width / 3.0);
649 let left = text_bounds.origin.x + horizontal_margin;
650 let right = text_bounds.upper_right().x - horizontal_margin;
651 if event.position.x < left {
652 scroll_delta.x = -scale_horizontal_mouse_autoscroll_delta(left - event.position.x);
653 }
654 if event.position.x > right {
655 scroll_delta.x = scale_horizontal_mouse_autoscroll_delta(event.position.x - right);
656 }
657
658 editor.select(
659 SelectPhase::Update {
660 position: point_for_position.previous_valid,
661 goal_column: point_for_position.exact_unclipped.column(),
662 scroll_delta,
663 },
664 cx,
665 );
666 }
667
668 fn mouse_moved(
669 editor: &mut Editor,
670 event: &MouseMoveEvent,
671 position_map: &PositionMap,
672 text_hitbox: &Hitbox,
673 gutter_hitbox: &Hitbox,
674 cx: &mut ViewContext<Editor>,
675 ) {
676 let modifiers = event.modifiers;
677 let gutter_hovered = gutter_hitbox.is_hovered(cx);
678 editor.set_gutter_hovered(gutter_hovered, cx);
679
680 // Don't trigger hover popover if mouse is hovering over context menu
681 if text_hitbox.is_hovered(cx) {
682 let point_for_position =
683 position_map.point_for_position(text_hitbox.bounds, event.position);
684
685 editor.update_hovered_link(point_for_position, &position_map.snapshot, modifiers, cx);
686
687 if let Some(point) = point_for_position.as_valid() {
688 let anchor = position_map
689 .snapshot
690 .buffer_snapshot
691 .anchor_before(point.to_offset(&position_map.snapshot, Bias::Left));
692 hover_at(editor, Some(anchor), cx);
693 Self::update_visible_cursor(editor, point, position_map, cx);
694 } else {
695 hover_at(editor, None, cx);
696 }
697 } else {
698 editor.hide_hovered_link(cx);
699 hover_at(editor, None, cx);
700 if gutter_hovered {
701 cx.stop_propagation();
702 }
703 }
704 }
705
706 fn update_visible_cursor(
707 editor: &mut Editor,
708 point: DisplayPoint,
709 position_map: &PositionMap,
710 cx: &mut ViewContext<Editor>,
711 ) {
712 let snapshot = &position_map.snapshot;
713 let Some(hub) = editor.collaboration_hub() else {
714 return;
715 };
716 let start = snapshot.display_snapshot.clip_point(
717 DisplayPoint::new(point.row(), point.column().saturating_sub(1)),
718 Bias::Left,
719 );
720 let end = snapshot.display_snapshot.clip_point(
721 DisplayPoint::new(
722 point.row(),
723 (point.column() + 1).min(snapshot.line_len(point.row())),
724 ),
725 Bias::Right,
726 );
727
728 let range = snapshot
729 .buffer_snapshot
730 .anchor_at(start.to_point(&snapshot.display_snapshot), Bias::Left)
731 ..snapshot
732 .buffer_snapshot
733 .anchor_at(end.to_point(&snapshot.display_snapshot), Bias::Right);
734
735 let Some(selection) = snapshot.remote_selections_in_range(&range, hub, cx).next() else {
736 return;
737 };
738 let key = crate::HoveredCursor {
739 replica_id: selection.replica_id,
740 selection_id: selection.selection.id,
741 };
742 editor.hovered_cursors.insert(
743 key.clone(),
744 cx.spawn(|editor, mut cx| async move {
745 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
746 editor
747 .update(&mut cx, |editor, cx| {
748 editor.hovered_cursors.remove(&key);
749 cx.notify();
750 })
751 .ok();
752 }),
753 );
754 cx.notify()
755 }
756
757 fn layout_selections(
758 &self,
759 start_anchor: Anchor,
760 end_anchor: Anchor,
761 snapshot: &EditorSnapshot,
762 start_row: DisplayRow,
763 end_row: DisplayRow,
764 cx: &mut WindowContext,
765 ) -> (
766 Vec<(PlayerColor, Vec<SelectionLayout>)>,
767 BTreeMap<DisplayRow, bool>,
768 Option<DisplayPoint>,
769 ) {
770 let mut selections: Vec<(PlayerColor, Vec<SelectionLayout>)> = Vec::new();
771 let mut active_rows = BTreeMap::new();
772 let mut newest_selection_head = None;
773 let editor = self.editor.read(cx);
774
775 if editor.show_local_selections {
776 let mut local_selections: Vec<Selection<Point>> = editor
777 .selections
778 .disjoint_in_range(start_anchor..end_anchor, cx);
779 local_selections.extend(editor.selections.pending(cx));
780 let mut layouts = Vec::new();
781 let newest = editor.selections.newest(cx);
782 for selection in local_selections.drain(..) {
783 let is_empty = selection.start == selection.end;
784 let is_newest = selection == newest;
785
786 let layout = SelectionLayout::new(
787 selection,
788 editor.selections.line_mode,
789 editor.cursor_shape,
790 &snapshot.display_snapshot,
791 is_newest,
792 editor.leader_peer_id.is_none(),
793 None,
794 );
795 if is_newest {
796 newest_selection_head = Some(layout.head);
797 }
798
799 for row in cmp::max(layout.active_rows.start.0, start_row.0)
800 ..=cmp::min(layout.active_rows.end.0, end_row.0)
801 {
802 let contains_non_empty_selection =
803 active_rows.entry(DisplayRow(row)).or_insert(!is_empty);
804 *contains_non_empty_selection |= !is_empty;
805 }
806 layouts.push(layout);
807 }
808
809 let player = if editor.read_only(cx) {
810 cx.theme().players().read_only()
811 } else {
812 self.style.local_player
813 };
814
815 selections.push((player, layouts));
816 }
817
818 if let Some(collaboration_hub) = &editor.collaboration_hub {
819 // When following someone, render the local selections in their color.
820 if let Some(leader_id) = editor.leader_peer_id {
821 if let Some(collaborator) = collaboration_hub.collaborators(cx).get(&leader_id) {
822 if let Some(participant_index) = collaboration_hub
823 .user_participant_indices(cx)
824 .get(&collaborator.user_id)
825 {
826 if let Some((local_selection_style, _)) = selections.first_mut() {
827 *local_selection_style = cx
828 .theme()
829 .players()
830 .color_for_participant(participant_index.0);
831 }
832 }
833 }
834 }
835
836 let mut remote_selections = HashMap::default();
837 for selection in snapshot.remote_selections_in_range(
838 &(start_anchor..end_anchor),
839 collaboration_hub.as_ref(),
840 cx,
841 ) {
842 let selection_style = Self::get_participant_color(selection.participant_index, cx);
843
844 // Don't re-render the leader's selections, since the local selections
845 // match theirs.
846 if Some(selection.peer_id) == editor.leader_peer_id {
847 continue;
848 }
849 let key = HoveredCursor {
850 replica_id: selection.replica_id,
851 selection_id: selection.selection.id,
852 };
853
854 let is_shown =
855 editor.show_cursor_names || editor.hovered_cursors.contains_key(&key);
856
857 remote_selections
858 .entry(selection.replica_id)
859 .or_insert((selection_style, Vec::new()))
860 .1
861 .push(SelectionLayout::new(
862 selection.selection,
863 selection.line_mode,
864 selection.cursor_shape,
865 &snapshot.display_snapshot,
866 false,
867 false,
868 if is_shown { selection.user_name } else { None },
869 ));
870 }
871
872 selections.extend(remote_selections.into_values());
873 } else if !editor.is_focused(cx) && editor.show_cursor_when_unfocused {
874 let player = if editor.read_only(cx) {
875 cx.theme().players().read_only()
876 } else {
877 self.style.local_player
878 };
879 let layouts = snapshot
880 .buffer_snapshot
881 .selections_in_range(&(start_anchor..end_anchor), true)
882 .map(move |(_, line_mode, cursor_shape, selection)| {
883 SelectionLayout::new(
884 selection,
885 line_mode,
886 cursor_shape,
887 &snapshot.display_snapshot,
888 false,
889 false,
890 None,
891 )
892 })
893 .collect::<Vec<_>>();
894 selections.push((player, layouts));
895 }
896 (selections, active_rows, newest_selection_head)
897 }
898
899 fn collect_cursors(
900 &self,
901 snapshot: &EditorSnapshot,
902 cx: &mut WindowContext,
903 ) -> Vec<(DisplayPoint, Hsla)> {
904 let editor = self.editor.read(cx);
905 let mut cursors = Vec::new();
906 let mut skip_local = false;
907 let mut add_cursor = |anchor: Anchor, color| {
908 cursors.push((anchor.to_display_point(&snapshot.display_snapshot), color));
909 };
910 // Remote cursors
911 if let Some(collaboration_hub) = &editor.collaboration_hub {
912 for remote_selection in snapshot.remote_selections_in_range(
913 &(Anchor::min()..Anchor::max()),
914 collaboration_hub.deref(),
915 cx,
916 ) {
917 let color = Self::get_participant_color(remote_selection.participant_index, cx);
918 add_cursor(remote_selection.selection.head(), color.cursor);
919 if Some(remote_selection.peer_id) == editor.leader_peer_id {
920 skip_local = true;
921 }
922 }
923 }
924 // Local cursors
925 if !skip_local {
926 let color = cx.theme().players().local().cursor;
927 editor.selections.disjoint.iter().for_each(|selection| {
928 add_cursor(selection.head(), color);
929 });
930 if let Some(ref selection) = editor.selections.pending_anchor() {
931 add_cursor(selection.head(), color);
932 }
933 }
934 cursors
935 }
936
937 #[allow(clippy::too_many_arguments)]
938 fn layout_visible_cursors(
939 &self,
940 snapshot: &EditorSnapshot,
941 selections: &[(PlayerColor, Vec<SelectionLayout>)],
942 visible_display_row_range: Range<DisplayRow>,
943 line_layouts: &[LineWithInvisibles],
944 text_hitbox: &Hitbox,
945 content_origin: gpui::Point<Pixels>,
946 scroll_position: gpui::Point<f32>,
947 scroll_pixel_position: gpui::Point<Pixels>,
948 line_height: Pixels,
949 em_width: Pixels,
950 autoscroll_containing_element: bool,
951 cx: &mut WindowContext,
952 ) -> Vec<CursorLayout> {
953 let mut autoscroll_bounds = None;
954 let cursor_layouts = self.editor.update(cx, |editor, cx| {
955 let mut cursors = Vec::new();
956 for (player_color, selections) in selections {
957 for selection in selections {
958 let cursor_position = selection.head;
959
960 let in_range = visible_display_row_range.contains(&cursor_position.row());
961 if (selection.is_local && !editor.show_local_cursors(cx)) || !in_range {
962 continue;
963 }
964
965 let cursor_row_layout = &line_layouts
966 [cursor_position.row().minus(visible_display_row_range.start) as usize];
967 let cursor_column = cursor_position.column() as usize;
968
969 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
970 let mut block_width =
971 cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
972 if block_width == Pixels::ZERO {
973 block_width = em_width;
974 }
975 let block_text = if let CursorShape::Block = selection.cursor_shape {
976 snapshot.display_chars_at(cursor_position).next().and_then(
977 |(character, _)| {
978 let text = if character == '\n' {
979 SharedString::from(" ")
980 } else {
981 SharedString::from(character.to_string())
982 };
983 let len = text.len();
984
985 let font = cursor_row_layout
986 .font_id_for_index(cursor_column)
987 .and_then(|cursor_font_id| {
988 cx.text_system().get_font_for_id(cursor_font_id)
989 })
990 .unwrap_or(self.style.text.font());
991
992 cx.text_system()
993 .shape_line(
994 text,
995 cursor_row_layout.font_size,
996 &[TextRun {
997 len,
998 font,
999 color: self.style.background,
1000 background_color: None,
1001 strikethrough: None,
1002 underline: None,
1003 }],
1004 )
1005 .log_err()
1006 },
1007 )
1008 } else {
1009 None
1010 };
1011
1012 let x = cursor_character_x - scroll_pixel_position.x;
1013 let y = (cursor_position.row().as_f32()
1014 - scroll_pixel_position.y / line_height)
1015 * line_height;
1016 if selection.is_newest {
1017 editor.pixel_position_of_newest_cursor = Some(point(
1018 text_hitbox.origin.x + x + block_width / 2.,
1019 text_hitbox.origin.y + y + line_height / 2.,
1020 ));
1021
1022 if autoscroll_containing_element {
1023 let top = text_hitbox.origin.y
1024 + (cursor_position.row().as_f32() - scroll_position.y - 3.).max(0.)
1025 * line_height;
1026 let left = text_hitbox.origin.x
1027 + (cursor_position.column() as f32 - scroll_position.x - 3.)
1028 .max(0.)
1029 * em_width;
1030
1031 let bottom = text_hitbox.origin.y
1032 + (cursor_position.row().as_f32() - scroll_position.y + 4.)
1033 * line_height;
1034 let right = text_hitbox.origin.x
1035 + (cursor_position.column() as f32 - scroll_position.x + 4.)
1036 * em_width;
1037
1038 autoscroll_bounds =
1039 Some(Bounds::from_corners(point(left, top), point(right, bottom)))
1040 }
1041 }
1042
1043 let mut cursor = CursorLayout {
1044 color: player_color.cursor,
1045 block_width,
1046 origin: point(x, y),
1047 line_height,
1048 shape: selection.cursor_shape,
1049 block_text,
1050 cursor_name: None,
1051 };
1052 let cursor_name = selection.user_name.clone().map(|name| CursorName {
1053 string: name,
1054 color: self.style.background,
1055 is_top_row: cursor_position.row().0 == 0,
1056 });
1057 cursor.layout(content_origin, cursor_name, cx);
1058 cursors.push(cursor);
1059 }
1060 }
1061 cursors
1062 });
1063
1064 if let Some(bounds) = autoscroll_bounds {
1065 cx.request_autoscroll(bounds);
1066 }
1067
1068 cursor_layouts
1069 }
1070
1071 fn layout_scrollbar(
1072 &self,
1073 snapshot: &EditorSnapshot,
1074 bounds: Bounds<Pixels>,
1075 scroll_position: gpui::Point<f32>,
1076 rows_per_page: f32,
1077 non_visible_cursors: bool,
1078 cx: &mut WindowContext,
1079 ) -> Option<ScrollbarLayout> {
1080 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
1081 let show_scrollbars = match scrollbar_settings.show {
1082 ShowScrollbar::Auto => {
1083 let editor = self.editor.read(cx);
1084 let is_singleton = editor.is_singleton(cx);
1085 // Git
1086 (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_git_diffs())
1087 ||
1088 // Buffer Search Results
1089 (is_singleton && scrollbar_settings.search_results && editor.has_background_highlights::<BufferSearchHighlights>())
1090 ||
1091 // Selected Symbol Occurrences
1092 (is_singleton && scrollbar_settings.selected_symbol && (editor.has_background_highlights::<DocumentHighlightRead>() || editor.has_background_highlights::<DocumentHighlightWrite>()))
1093 ||
1094 // Diagnostics
1095 (is_singleton && scrollbar_settings.diagnostics && snapshot.buffer_snapshot.has_diagnostics())
1096 ||
1097 // Cursors out of sight
1098 non_visible_cursors
1099 ||
1100 // Scrollmanager
1101 editor.scroll_manager.scrollbars_visible()
1102 }
1103 ShowScrollbar::System => self.editor.read(cx).scroll_manager.scrollbars_visible(),
1104 ShowScrollbar::Always => true,
1105 ShowScrollbar::Never => false,
1106 };
1107 if snapshot.mode != EditorMode::Full {
1108 return None;
1109 }
1110
1111 let visible_row_range = scroll_position.y..scroll_position.y + rows_per_page;
1112
1113 // If a drag took place after we started dragging the scrollbar,
1114 // cancel the scrollbar drag.
1115 if cx.has_active_drag() {
1116 self.editor.update(cx, |editor, cx| {
1117 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
1118 });
1119 }
1120
1121 let track_bounds = Bounds::from_corners(
1122 point(self.scrollbar_left(&bounds), bounds.origin.y),
1123 point(bounds.lower_right().x, bounds.lower_left().y),
1124 );
1125
1126 let settings = EditorSettings::get_global(cx);
1127 let scroll_beyond_last_line: f32 = match settings.scroll_beyond_last_line {
1128 ScrollBeyondLastLine::OnePage => rows_per_page,
1129 ScrollBeyondLastLine::Off => 1.0,
1130 ScrollBeyondLastLine::VerticalScrollMargin => 1.0 + settings.vertical_scroll_margin,
1131 };
1132 let total_rows =
1133 (snapshot.max_point().row().as_f32() + scroll_beyond_last_line).max(rows_per_page);
1134 let height = bounds.size.height;
1135 let px_per_row = height / total_rows;
1136 let thumb_height = (rows_per_page * px_per_row).max(ScrollbarLayout::MIN_THUMB_HEIGHT);
1137 let row_height = (height - thumb_height) / (total_rows - rows_per_page).max(0.);
1138
1139 Some(ScrollbarLayout {
1140 hitbox: cx.insert_hitbox(track_bounds, false),
1141 visible_row_range,
1142 row_height,
1143 visible: show_scrollbars,
1144 thumb_height,
1145 })
1146 }
1147
1148 #[allow(clippy::too_many_arguments)]
1149 fn prepaint_gutter_fold_toggles(
1150 &self,
1151 toggles: &mut [Option<AnyElement>],
1152 line_height: Pixels,
1153 gutter_dimensions: &GutterDimensions,
1154 gutter_settings: crate::editor_settings::Gutter,
1155 scroll_pixel_position: gpui::Point<Pixels>,
1156 gutter_hitbox: &Hitbox,
1157 cx: &mut WindowContext,
1158 ) {
1159 for (ix, fold_indicator) in toggles.iter_mut().enumerate() {
1160 if let Some(fold_indicator) = fold_indicator {
1161 debug_assert!(gutter_settings.folds);
1162 let available_space = size(
1163 AvailableSpace::MinContent,
1164 AvailableSpace::Definite(line_height * 0.55),
1165 );
1166 let fold_indicator_size = fold_indicator.layout_as_root(available_space, cx);
1167
1168 let position = point(
1169 gutter_dimensions.width - gutter_dimensions.right_padding,
1170 ix as f32 * line_height - (scroll_pixel_position.y % line_height),
1171 );
1172 let centering_offset = point(
1173 (gutter_dimensions.fold_area_width() - fold_indicator_size.width) / 2.,
1174 (line_height - fold_indicator_size.height) / 2.,
1175 );
1176 let origin = gutter_hitbox.origin + position + centering_offset;
1177 fold_indicator.prepaint_as_root(origin, available_space, cx);
1178 }
1179 }
1180 }
1181
1182 #[allow(clippy::too_many_arguments)]
1183 fn prepaint_crease_trailers(
1184 &self,
1185 trailers: Vec<Option<AnyElement>>,
1186 lines: &[LineWithInvisibles],
1187 line_height: Pixels,
1188 content_origin: gpui::Point<Pixels>,
1189 scroll_pixel_position: gpui::Point<Pixels>,
1190 em_width: Pixels,
1191 cx: &mut WindowContext,
1192 ) -> Vec<Option<CreaseTrailerLayout>> {
1193 trailers
1194 .into_iter()
1195 .enumerate()
1196 .map(|(ix, element)| {
1197 let mut element = element?;
1198 let available_space = size(
1199 AvailableSpace::MinContent,
1200 AvailableSpace::Definite(line_height),
1201 );
1202 let size = element.layout_as_root(available_space, cx);
1203
1204 let line = &lines[ix];
1205 let padding = if line.width == Pixels::ZERO {
1206 Pixels::ZERO
1207 } else {
1208 4. * em_width
1209 };
1210 let position = point(
1211 scroll_pixel_position.x + line.width + padding,
1212 ix as f32 * line_height - (scroll_pixel_position.y % line_height),
1213 );
1214 let centering_offset = point(px(0.), (line_height - size.height) / 2.);
1215 let origin = content_origin + position + centering_offset;
1216 element.prepaint_as_root(origin, available_space, cx);
1217 Some(CreaseTrailerLayout {
1218 element,
1219 bounds: Bounds::new(origin, size),
1220 })
1221 })
1222 .collect()
1223 }
1224
1225 // Folds contained in a hunk are ignored apart from shrinking visual size
1226 // If a fold contains any hunks then that fold line is marked as modified
1227 fn layout_git_gutters(
1228 &self,
1229 line_height: Pixels,
1230 gutter_hitbox: &Hitbox,
1231 display_rows: Range<DisplayRow>,
1232 snapshot: &EditorSnapshot,
1233 cx: &mut WindowContext,
1234 ) -> Vec<(DisplayDiffHunk, Option<Hitbox>)> {
1235 let buffer_snapshot = &snapshot.buffer_snapshot;
1236
1237 let buffer_start_row = MultiBufferRow(
1238 DisplayPoint::new(display_rows.start, 0)
1239 .to_point(snapshot)
1240 .row,
1241 );
1242 let buffer_end_row = MultiBufferRow(
1243 DisplayPoint::new(display_rows.end, 0)
1244 .to_point(snapshot)
1245 .row,
1246 );
1247
1248 let expanded_hunk_display_rows = self.editor.update(cx, |editor, _| {
1249 editor
1250 .expanded_hunks
1251 .hunks(false)
1252 .map(|expanded_hunk| {
1253 let start_row = expanded_hunk
1254 .hunk_range
1255 .start
1256 .to_display_point(snapshot)
1257 .row();
1258 let end_row = expanded_hunk
1259 .hunk_range
1260 .end
1261 .to_display_point(snapshot)
1262 .row();
1263 (start_row, end_row)
1264 })
1265 .collect::<HashMap<_, _>>()
1266 });
1267
1268 let git_gutter_setting = ProjectSettings::get_global(cx)
1269 .git
1270 .git_gutter
1271 .unwrap_or_default();
1272 buffer_snapshot
1273 .git_diff_hunks_in_range(buffer_start_row..buffer_end_row)
1274 .map(|hunk| diff_hunk_to_display(&hunk, snapshot))
1275 .dedup()
1276 .map(|hunk| match git_gutter_setting {
1277 GitGutterSetting::TrackedFiles => {
1278 let hitbox = if let DisplayDiffHunk::Unfolded {
1279 display_row_range, ..
1280 } = &hunk
1281 {
1282 let was_expanded = expanded_hunk_display_rows
1283 .get(&display_row_range.start)
1284 .map(|expanded_end_row| expanded_end_row == &display_row_range.end)
1285 .unwrap_or(false);
1286 if was_expanded {
1287 None
1288 } else {
1289 let hunk_bounds = Self::diff_hunk_bounds(
1290 &snapshot,
1291 line_height,
1292 gutter_hitbox.bounds,
1293 &hunk,
1294 );
1295 Some(cx.insert_hitbox(hunk_bounds, true))
1296 }
1297 } else {
1298 None
1299 };
1300 (hunk, hitbox)
1301 }
1302 GitGutterSetting::Hide => (hunk, None),
1303 })
1304 .collect()
1305 }
1306
1307 #[allow(clippy::too_many_arguments)]
1308 fn layout_inline_blame(
1309 &self,
1310 display_row: DisplayRow,
1311 display_snapshot: &DisplaySnapshot,
1312 line_layout: &LineWithInvisibles,
1313 crease_trailer: Option<&CreaseTrailerLayout>,
1314 em_width: Pixels,
1315 content_origin: gpui::Point<Pixels>,
1316 scroll_pixel_position: gpui::Point<Pixels>,
1317 line_height: Pixels,
1318 cx: &mut WindowContext,
1319 ) -> Option<AnyElement> {
1320 if !self
1321 .editor
1322 .update(cx, |editor, cx| editor.render_git_blame_inline(cx))
1323 {
1324 return None;
1325 }
1326
1327 let workspace = self
1328 .editor
1329 .read(cx)
1330 .workspace
1331 .as_ref()
1332 .map(|(w, _)| w.clone());
1333
1334 let display_point = DisplayPoint::new(display_row, 0);
1335 let buffer_row = MultiBufferRow(display_point.to_point(display_snapshot).row);
1336
1337 let blame = self.editor.read(cx).blame.clone()?;
1338 let blame_entry = blame
1339 .update(cx, |blame, cx| {
1340 blame.blame_for_rows([Some(buffer_row)], cx).next()
1341 })
1342 .flatten()?;
1343
1344 let mut element =
1345 render_inline_blame_entry(&blame, blame_entry, &self.style, workspace, cx);
1346
1347 let start_y = content_origin.y
1348 + line_height * (display_row.as_f32() - scroll_pixel_position.y / line_height);
1349
1350 let start_x = {
1351 const INLINE_BLAME_PADDING_EM_WIDTHS: f32 = 6.;
1352
1353 let line_end = if let Some(crease_trailer) = crease_trailer {
1354 crease_trailer.bounds.right()
1355 } else {
1356 content_origin.x - scroll_pixel_position.x + line_layout.width
1357 };
1358 let padded_line_end = line_end + em_width * INLINE_BLAME_PADDING_EM_WIDTHS;
1359
1360 let min_column_in_pixels = ProjectSettings::get_global(cx)
1361 .git
1362 .inline_blame
1363 .and_then(|settings| settings.min_column)
1364 .map(|col| self.column_pixels(col as usize, cx))
1365 .unwrap_or(px(0.));
1366 let min_start = content_origin.x - scroll_pixel_position.x + min_column_in_pixels;
1367
1368 cmp::max(padded_line_end, min_start)
1369 };
1370
1371 let absolute_offset = point(start_x, start_y);
1372 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1373
1374 element.prepaint_as_root(absolute_offset, available_space, cx);
1375
1376 Some(element)
1377 }
1378
1379 #[allow(clippy::too_many_arguments)]
1380 fn layout_blame_entries(
1381 &self,
1382 buffer_rows: impl Iterator<Item = Option<MultiBufferRow>>,
1383 em_width: Pixels,
1384 scroll_position: gpui::Point<f32>,
1385 line_height: Pixels,
1386 gutter_hitbox: &Hitbox,
1387 max_width: Option<Pixels>,
1388 cx: &mut WindowContext,
1389 ) -> Option<Vec<AnyElement>> {
1390 if !self
1391 .editor
1392 .update(cx, |editor, cx| editor.render_git_blame_gutter(cx))
1393 {
1394 return None;
1395 }
1396
1397 let blame = self.editor.read(cx).blame.clone()?;
1398 let blamed_rows: Vec<_> = blame.update(cx, |blame, cx| {
1399 blame.blame_for_rows(buffer_rows, cx).collect()
1400 });
1401
1402 let width = if let Some(max_width) = max_width {
1403 AvailableSpace::Definite(max_width)
1404 } else {
1405 AvailableSpace::MaxContent
1406 };
1407 let scroll_top = scroll_position.y * line_height;
1408 let start_x = em_width * 1;
1409
1410 let mut last_used_color: Option<(PlayerColor, Oid)> = None;
1411
1412 let shaped_lines = blamed_rows
1413 .into_iter()
1414 .enumerate()
1415 .flat_map(|(ix, blame_entry)| {
1416 if let Some(blame_entry) = blame_entry {
1417 let mut element = render_blame_entry(
1418 ix,
1419 &blame,
1420 blame_entry,
1421 &self.style,
1422 &mut last_used_color,
1423 self.editor.clone(),
1424 cx,
1425 );
1426
1427 let start_y = ix as f32 * line_height - (scroll_top % line_height);
1428 let absolute_offset = gutter_hitbox.origin + point(start_x, start_y);
1429
1430 element.prepaint_as_root(
1431 absolute_offset,
1432 size(width, AvailableSpace::MinContent),
1433 cx,
1434 );
1435
1436 Some(element)
1437 } else {
1438 None
1439 }
1440 })
1441 .collect();
1442
1443 Some(shaped_lines)
1444 }
1445
1446 #[allow(clippy::too_many_arguments)]
1447 fn layout_indent_guides(
1448 &self,
1449 content_origin: gpui::Point<Pixels>,
1450 text_origin: gpui::Point<Pixels>,
1451 visible_buffer_range: Range<MultiBufferRow>,
1452 scroll_pixel_position: gpui::Point<Pixels>,
1453 line_height: Pixels,
1454 snapshot: &DisplaySnapshot,
1455 cx: &mut WindowContext,
1456 ) -> Option<Vec<IndentGuideLayout>> {
1457 let indent_guides = self.editor.update(cx, |editor, cx| {
1458 editor.indent_guides(visible_buffer_range, snapshot, cx)
1459 })?;
1460
1461 let active_indent_guide_indices = self.editor.update(cx, |editor, cx| {
1462 editor
1463 .find_active_indent_guide_indices(&indent_guides, snapshot, cx)
1464 .unwrap_or_default()
1465 });
1466
1467 Some(
1468 indent_guides
1469 .into_iter()
1470 .enumerate()
1471 .filter_map(|(i, indent_guide)| {
1472 let single_indent_width =
1473 self.column_pixels(indent_guide.tab_size as usize, cx);
1474 let total_width = single_indent_width * indent_guide.depth as f32;
1475 let start_x = content_origin.x + total_width - scroll_pixel_position.x;
1476 if start_x >= text_origin.x {
1477 let (offset_y, length) = Self::calculate_indent_guide_bounds(
1478 indent_guide.multibuffer_row_range.clone(),
1479 line_height,
1480 snapshot,
1481 );
1482
1483 let start_y = content_origin.y + offset_y - scroll_pixel_position.y;
1484
1485 Some(IndentGuideLayout {
1486 origin: point(start_x, start_y),
1487 length,
1488 single_indent_width,
1489 depth: indent_guide.depth,
1490 active: active_indent_guide_indices.contains(&i),
1491 settings: indent_guide.settings,
1492 })
1493 } else {
1494 None
1495 }
1496 })
1497 .collect(),
1498 )
1499 }
1500
1501 fn calculate_indent_guide_bounds(
1502 row_range: Range<MultiBufferRow>,
1503 line_height: Pixels,
1504 snapshot: &DisplaySnapshot,
1505 ) -> (gpui::Pixels, gpui::Pixels) {
1506 let start_point = Point::new(row_range.start.0, 0);
1507 let end_point = Point::new(row_range.end.0, 0);
1508
1509 let row_range = start_point.to_display_point(snapshot).row()
1510 ..end_point.to_display_point(snapshot).row();
1511
1512 let mut prev_line = start_point;
1513 prev_line.row = prev_line.row.saturating_sub(1);
1514 let prev_line = prev_line.to_display_point(snapshot).row();
1515
1516 let mut cons_line = end_point;
1517 cons_line.row += 1;
1518 let cons_line = cons_line.to_display_point(snapshot).row();
1519
1520 let mut offset_y = row_range.start.0 as f32 * line_height;
1521 let mut length = (cons_line.0.saturating_sub(row_range.start.0)) as f32 * line_height;
1522
1523 // If we are at the end of the buffer, ensure that the indent guide extends to the end of the line.
1524 if row_range.end == cons_line {
1525 length += line_height;
1526 }
1527
1528 // If there is a block (e.g. diagnostic) in between the start of the indent guide and the line above,
1529 // we want to extend the indent guide to the start of the block.
1530 let mut block_height = 0;
1531 let mut block_offset = 0;
1532 let mut found_excerpt_header = false;
1533 for (_, block) in snapshot.blocks_in_range(prev_line..row_range.start) {
1534 if matches!(block, TransformBlock::ExcerptHeader { .. }) {
1535 found_excerpt_header = true;
1536 break;
1537 }
1538 block_offset += block.height();
1539 block_height += block.height();
1540 }
1541 if !found_excerpt_header {
1542 offset_y -= block_offset as f32 * line_height;
1543 length += block_height as f32 * line_height;
1544 }
1545
1546 // If there is a block (e.g. diagnostic) at the end of an multibuffer excerpt,
1547 // we want to ensure that the indent guide stops before the excerpt header.
1548 let mut block_height = 0;
1549 let mut found_excerpt_header = false;
1550 for (_, block) in snapshot.blocks_in_range(row_range.end..cons_line) {
1551 if matches!(block, TransformBlock::ExcerptHeader { .. }) {
1552 found_excerpt_header = true;
1553 }
1554 block_height += block.height();
1555 }
1556 if found_excerpt_header {
1557 length -= block_height as f32 * line_height;
1558 }
1559
1560 (offset_y, length)
1561 }
1562
1563 fn layout_run_indicators(
1564 &self,
1565 line_height: Pixels,
1566 scroll_pixel_position: gpui::Point<Pixels>,
1567 gutter_dimensions: &GutterDimensions,
1568 gutter_hitbox: &Hitbox,
1569 snapshot: &EditorSnapshot,
1570 cx: &mut WindowContext,
1571 ) -> Vec<AnyElement> {
1572 self.editor.update(cx, |editor, cx| {
1573 let active_task_indicator_row =
1574 if let Some(crate::ContextMenu::CodeActions(CodeActionsMenu {
1575 deployed_from_indicator,
1576 actions,
1577 ..
1578 })) = editor.context_menu.read().as_ref()
1579 {
1580 actions
1581 .tasks
1582 .as_ref()
1583 .map(|tasks| tasks.position.to_display_point(snapshot).row())
1584 .or_else(|| *deployed_from_indicator)
1585 } else {
1586 None
1587 };
1588 editor
1589 .tasks
1590 .iter()
1591 .filter_map(|(_, tasks)| {
1592 let multibuffer_point = tasks.offset.0.to_point(&snapshot.buffer_snapshot);
1593 let multibuffer_row = MultiBufferRow(multibuffer_point.row);
1594 if snapshot.is_line_folded(multibuffer_row) {
1595 return None;
1596 }
1597 let display_row = multibuffer_point.to_display_point(snapshot).row();
1598 let button = editor.render_run_indicator(
1599 &self.style,
1600 Some(display_row) == active_task_indicator_row,
1601 display_row,
1602 cx,
1603 );
1604
1605 let button = prepaint_gutter_button(
1606 button,
1607 display_row,
1608 line_height,
1609 gutter_dimensions,
1610 scroll_pixel_position,
1611 gutter_hitbox,
1612 cx,
1613 );
1614 Some(button)
1615 })
1616 .collect_vec()
1617 })
1618 }
1619
1620 fn layout_code_actions_indicator(
1621 &self,
1622 line_height: Pixels,
1623 newest_selection_head: DisplayPoint,
1624 scroll_pixel_position: gpui::Point<Pixels>,
1625 gutter_dimensions: &GutterDimensions,
1626 gutter_hitbox: &Hitbox,
1627 cx: &mut WindowContext,
1628 ) -> Option<AnyElement> {
1629 let mut active = false;
1630 let mut button = None;
1631 let row = newest_selection_head.row();
1632 self.editor.update(cx, |editor, cx| {
1633 if let Some(crate::ContextMenu::CodeActions(CodeActionsMenu {
1634 deployed_from_indicator,
1635 ..
1636 })) = editor.context_menu.read().as_ref()
1637 {
1638 active = deployed_from_indicator.map_or(true, |indicator_row| indicator_row == row);
1639 };
1640 button = editor.render_code_actions_indicator(&self.style, row, active, cx);
1641 });
1642
1643 let button = prepaint_gutter_button(
1644 button?,
1645 row,
1646 line_height,
1647 gutter_dimensions,
1648 scroll_pixel_position,
1649 gutter_hitbox,
1650 cx,
1651 );
1652
1653 Some(button)
1654 }
1655
1656 fn get_participant_color(
1657 participant_index: Option<ParticipantIndex>,
1658 cx: &WindowContext,
1659 ) -> PlayerColor {
1660 if let Some(index) = participant_index {
1661 cx.theme().players().color_for_participant(index.0)
1662 } else {
1663 cx.theme().players().absent()
1664 }
1665 }
1666
1667 fn calculate_relative_line_numbers(
1668 &self,
1669 snapshot: &EditorSnapshot,
1670 rows: &Range<DisplayRow>,
1671 relative_to: Option<DisplayRow>,
1672 ) -> HashMap<DisplayRow, DisplayRowDelta> {
1673 let mut relative_rows: HashMap<DisplayRow, DisplayRowDelta> = Default::default();
1674 let Some(relative_to) = relative_to else {
1675 return relative_rows;
1676 };
1677
1678 let start = rows.start.min(relative_to);
1679 let end = rows.end.max(relative_to);
1680
1681 let buffer_rows = snapshot
1682 .buffer_rows(start)
1683 .take(1 + end.minus(start) as usize)
1684 .collect::<Vec<_>>();
1685
1686 let head_idx = relative_to.minus(start);
1687 let mut delta = 1;
1688 let mut i = head_idx + 1;
1689 while i < buffer_rows.len() as u32 {
1690 if buffer_rows[i as usize].is_some() {
1691 if rows.contains(&DisplayRow(i + start.0)) {
1692 relative_rows.insert(DisplayRow(i + start.0), delta);
1693 }
1694 delta += 1;
1695 }
1696 i += 1;
1697 }
1698 delta = 1;
1699 i = head_idx.min(buffer_rows.len() as u32 - 1);
1700 while i > 0 && buffer_rows[i as usize].is_none() {
1701 i -= 1;
1702 }
1703
1704 while i > 0 {
1705 i -= 1;
1706 if buffer_rows[i as usize].is_some() {
1707 if rows.contains(&DisplayRow(i + start.0)) {
1708 relative_rows.insert(DisplayRow(i + start.0), delta);
1709 }
1710 delta += 1;
1711 }
1712 }
1713
1714 relative_rows
1715 }
1716
1717 fn layout_line_numbers(
1718 &self,
1719 rows: Range<DisplayRow>,
1720 buffer_rows: impl Iterator<Item = Option<MultiBufferRow>>,
1721 active_rows: &BTreeMap<DisplayRow, bool>,
1722 newest_selection_head: Option<DisplayPoint>,
1723 snapshot: &EditorSnapshot,
1724 cx: &mut WindowContext,
1725 ) -> Vec<Option<ShapedLine>> {
1726 let include_line_numbers = snapshot.show_line_numbers.unwrap_or_else(|| {
1727 EditorSettings::get_global(cx).gutter.line_numbers && snapshot.mode == EditorMode::Full
1728 });
1729 if !include_line_numbers {
1730 return Vec::new();
1731 }
1732
1733 let editor = self.editor.read(cx);
1734 let newest_selection_head = newest_selection_head.unwrap_or_else(|| {
1735 let newest = editor.selections.newest::<Point>(cx);
1736 SelectionLayout::new(
1737 newest,
1738 editor.selections.line_mode,
1739 editor.cursor_shape,
1740 &snapshot.display_snapshot,
1741 true,
1742 true,
1743 None,
1744 )
1745 .head
1746 });
1747 let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1748
1749 let is_relative = EditorSettings::get_global(cx).relative_line_numbers;
1750 let relative_to = if is_relative {
1751 Some(newest_selection_head.row())
1752 } else {
1753 None
1754 };
1755 let relative_rows = self.calculate_relative_line_numbers(snapshot, &rows, relative_to);
1756 let mut line_number = String::new();
1757 buffer_rows
1758 .into_iter()
1759 .enumerate()
1760 .map(|(ix, multibuffer_row)| {
1761 let multibuffer_row = multibuffer_row?;
1762 let display_row = DisplayRow(rows.start.0 + ix as u32);
1763 let color = if active_rows.contains_key(&display_row) {
1764 cx.theme().colors().editor_active_line_number
1765 } else {
1766 cx.theme().colors().editor_line_number
1767 };
1768 line_number.clear();
1769 let default_number = multibuffer_row.0 + 1;
1770 let number = relative_rows
1771 .get(&DisplayRow(ix as u32 + rows.start.0))
1772 .unwrap_or(&default_number);
1773 write!(&mut line_number, "{number}").unwrap();
1774 let run = TextRun {
1775 len: line_number.len(),
1776 font: self.style.text.font(),
1777 color,
1778 background_color: None,
1779 underline: None,
1780 strikethrough: None,
1781 };
1782 let shaped_line = cx
1783 .text_system()
1784 .shape_line(line_number.clone().into(), font_size, &[run])
1785 .unwrap();
1786 Some(shaped_line)
1787 })
1788 .collect()
1789 }
1790
1791 fn layout_gutter_fold_toggles(
1792 &self,
1793 rows: Range<DisplayRow>,
1794 buffer_rows: impl IntoIterator<Item = Option<MultiBufferRow>>,
1795 active_rows: &BTreeMap<DisplayRow, bool>,
1796 snapshot: &EditorSnapshot,
1797 cx: &mut WindowContext,
1798 ) -> Vec<Option<AnyElement>> {
1799 let include_fold_statuses = EditorSettings::get_global(cx).gutter.folds
1800 && snapshot.mode == EditorMode::Full
1801 && self.editor.read(cx).is_singleton(cx);
1802 if include_fold_statuses {
1803 buffer_rows
1804 .into_iter()
1805 .enumerate()
1806 .map(|(ix, row)| {
1807 if let Some(multibuffer_row) = row {
1808 let display_row = DisplayRow(rows.start.0 + ix as u32);
1809 let active = active_rows.contains_key(&display_row);
1810 snapshot.render_fold_toggle(
1811 multibuffer_row,
1812 active,
1813 self.editor.clone(),
1814 cx,
1815 )
1816 } else {
1817 None
1818 }
1819 })
1820 .collect()
1821 } else {
1822 Vec::new()
1823 }
1824 }
1825
1826 fn layout_crease_trailers(
1827 &self,
1828 buffer_rows: impl IntoIterator<Item = Option<MultiBufferRow>>,
1829 snapshot: &EditorSnapshot,
1830 cx: &mut WindowContext,
1831 ) -> Vec<Option<AnyElement>> {
1832 buffer_rows
1833 .into_iter()
1834 .map(|row| {
1835 if let Some(multibuffer_row) = row {
1836 snapshot.render_crease_trailer(multibuffer_row, cx)
1837 } else {
1838 None
1839 }
1840 })
1841 .collect()
1842 }
1843
1844 fn layout_lines(
1845 rows: Range<DisplayRow>,
1846 line_number_layouts: &[Option<ShapedLine>],
1847 snapshot: &EditorSnapshot,
1848 style: &EditorStyle,
1849 cx: &mut WindowContext,
1850 ) -> Vec<LineWithInvisibles> {
1851 if rows.start >= rows.end {
1852 return Vec::new();
1853 }
1854
1855 // Show the placeholder when the editor is empty
1856 if snapshot.is_empty() {
1857 let font_size = style.text.font_size.to_pixels(cx.rem_size());
1858 let placeholder_color = cx.theme().colors().text_placeholder;
1859 let placeholder_text = snapshot.placeholder_text();
1860
1861 let placeholder_lines = placeholder_text
1862 .as_ref()
1863 .map_or("", AsRef::as_ref)
1864 .split('\n')
1865 .skip(rows.start.0 as usize)
1866 .chain(iter::repeat(""))
1867 .take(rows.len());
1868 placeholder_lines
1869 .filter_map(move |line| {
1870 let run = TextRun {
1871 len: line.len(),
1872 font: style.text.font(),
1873 color: placeholder_color,
1874 background_color: None,
1875 underline: Default::default(),
1876 strikethrough: None,
1877 };
1878 cx.text_system()
1879 .shape_line(line.to_string().into(), font_size, &[run])
1880 .log_err()
1881 })
1882 .map(|line| LineWithInvisibles {
1883 width: line.width,
1884 len: line.len,
1885 fragments: smallvec![LineFragment::Text(line)],
1886 invisibles: Vec::new(),
1887 font_size,
1888 })
1889 .collect()
1890 } else {
1891 let chunks = snapshot.highlighted_chunks(rows.clone(), true, style);
1892 LineWithInvisibles::from_chunks(
1893 chunks,
1894 &style.text,
1895 MAX_LINE_LEN,
1896 rows.len(),
1897 line_number_layouts,
1898 snapshot.mode,
1899 cx,
1900 )
1901 }
1902 }
1903
1904 fn prepaint_lines(
1905 &self,
1906 start_row: DisplayRow,
1907 line_layouts: &mut [LineWithInvisibles],
1908 line_height: Pixels,
1909 scroll_pixel_position: gpui::Point<Pixels>,
1910 content_origin: gpui::Point<Pixels>,
1911 cx: &mut WindowContext,
1912 ) -> SmallVec<[AnyElement; 1]> {
1913 let mut line_elements = SmallVec::new();
1914 for (ix, line) in line_layouts.iter_mut().enumerate() {
1915 let row = start_row + DisplayRow(ix as u32);
1916 line.prepaint(
1917 line_height,
1918 scroll_pixel_position,
1919 row,
1920 content_origin,
1921 &mut line_elements,
1922 cx,
1923 );
1924 }
1925 line_elements
1926 }
1927
1928 #[allow(clippy::too_many_arguments)]
1929 fn build_blocks(
1930 &self,
1931 rows: Range<DisplayRow>,
1932 snapshot: &EditorSnapshot,
1933 hitbox: &Hitbox,
1934 text_hitbox: &Hitbox,
1935 scroll_width: &mut Pixels,
1936 gutter_dimensions: &GutterDimensions,
1937 em_width: Pixels,
1938 text_x: Pixels,
1939 line_height: Pixels,
1940 line_layouts: &[LineWithInvisibles],
1941 cx: &mut WindowContext,
1942 ) -> Vec<BlockLayout> {
1943 let (fixed_blocks, non_fixed_blocks) = snapshot
1944 .blocks_in_range(rows.clone())
1945 .partition::<Vec<_>, _>(|(_, block)| match block {
1946 TransformBlock::ExcerptHeader { .. } => false,
1947 TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
1948 TransformBlock::ExcerptFooter { .. } => false,
1949 });
1950
1951 let render_block = |block: &TransformBlock,
1952 available_space: Size<AvailableSpace>,
1953 block_id: TransformBlockId,
1954 block_row_start: DisplayRow,
1955 cx: &mut WindowContext| {
1956 let mut element = match block {
1957 TransformBlock::Custom(block) => {
1958 let align_to = block
1959 .position()
1960 .to_point(&snapshot.buffer_snapshot)
1961 .to_display_point(snapshot);
1962 let anchor_x = text_x
1963 + if rows.contains(&align_to.row()) {
1964 line_layouts[align_to.row().minus(rows.start) as usize]
1965 .x_for_index(align_to.column() as usize)
1966 } else {
1967 layout_line(align_to.row(), snapshot, &self.style, cx)
1968 .x_for_index(align_to.column() as usize)
1969 };
1970
1971 block.render(&mut BlockContext {
1972 context: cx,
1973 anchor_x,
1974 gutter_dimensions,
1975 line_height,
1976 em_width,
1977 transform_block_id: block_id,
1978 max_width: text_hitbox.size.width.max(*scroll_width),
1979 editor_style: &self.style,
1980 })
1981 }
1982
1983 TransformBlock::ExcerptHeader {
1984 buffer,
1985 range,
1986 starts_new_buffer,
1987 height,
1988 id,
1989 show_excerpt_controls,
1990 ..
1991 } => {
1992 let include_root = self
1993 .editor
1994 .read(cx)
1995 .project
1996 .as_ref()
1997 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
1998 .unwrap_or_default();
1999
2000 #[derive(Clone)]
2001 struct JumpData {
2002 position: Point,
2003 anchor: text::Anchor,
2004 path: ProjectPath,
2005 line_offset_from_top: u32,
2006 }
2007
2008 let jump_data = project::File::from_dyn(buffer.file()).map(|file| {
2009 let jump_path = ProjectPath {
2010 worktree_id: file.worktree_id(cx),
2011 path: file.path.clone(),
2012 };
2013 let jump_anchor = range
2014 .primary
2015 .as_ref()
2016 .map_or(range.context.start, |primary| primary.start);
2017
2018 let excerpt_start = range.context.start;
2019 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
2020 let offset_from_excerpt_start = if jump_anchor == excerpt_start {
2021 0
2022 } else {
2023 let excerpt_start_row =
2024 language::ToPoint::to_point(&jump_anchor, buffer).row;
2025 jump_position.row - excerpt_start_row
2026 };
2027
2028 let line_offset_from_top =
2029 block_row_start.0 + *height as u32 + offset_from_excerpt_start
2030 - snapshot
2031 .scroll_anchor
2032 .scroll_position(&snapshot.display_snapshot)
2033 .y as u32;
2034
2035 JumpData {
2036 position: jump_position,
2037 anchor: jump_anchor,
2038 path: jump_path,
2039 line_offset_from_top,
2040 }
2041 });
2042
2043 let icon_offset = gutter_dimensions.width
2044 - (gutter_dimensions.left_padding + gutter_dimensions.margin);
2045
2046 let element = if *starts_new_buffer {
2047 let path = buffer.resolve_file_path(cx, include_root);
2048 let mut filename = None;
2049 let mut parent_path = None;
2050 // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
2051 if let Some(path) = path {
2052 filename = path.file_name().map(|f| f.to_string_lossy().to_string());
2053 parent_path = path
2054 .parent()
2055 .map(|p| SharedString::from(p.to_string_lossy().to_string() + "/"));
2056 }
2057
2058 let header_padding = px(6.0);
2059
2060 v_flex()
2061 .id(("path excerpt header", EntityId::from(block_id)))
2062 .size_full()
2063 .p(header_padding)
2064 .child(
2065 h_flex()
2066 .flex_basis(Length::Definite(DefiniteLength::Fraction(0.667)))
2067 .id("path header block")
2068 .pl(gpui::px(12.))
2069 .pr(gpui::px(8.))
2070 .rounded_md()
2071 .shadow_md()
2072 .border_1()
2073 .border_color(cx.theme().colors().border)
2074 .bg(cx.theme().colors().editor_subheader_background)
2075 .justify_between()
2076 .hover(|style| style.bg(cx.theme().colors().element_hover))
2077 .child(
2078 h_flex().gap_3().child(
2079 h_flex()
2080 .gap_2()
2081 .child(
2082 filename
2083 .map(SharedString::from)
2084 .unwrap_or_else(|| "untitled".into()),
2085 )
2086 .when_some(parent_path, |then, path| {
2087 then.child(
2088 div().child(path).text_color(
2089 cx.theme().colors().text_muted,
2090 ),
2091 )
2092 }),
2093 ),
2094 )
2095 .when_some(jump_data.clone(), |el, jump_data| {
2096 el.child(Icon::new(IconName::ArrowUpRight))
2097 .cursor_pointer()
2098 .tooltip(|cx| {
2099 Tooltip::for_action(
2100 "Jump to File",
2101 &OpenExcerpts,
2102 cx,
2103 )
2104 })
2105 .on_mouse_down(MouseButton::Left, |_, cx| {
2106 cx.stop_propagation()
2107 })
2108 .on_click(cx.listener_for(&self.editor, {
2109 move |editor, _, cx| {
2110 editor.jump(
2111 jump_data.path.clone(),
2112 jump_data.position,
2113 jump_data.anchor,
2114 jump_data.line_offset_from_top,
2115 cx,
2116 );
2117 }
2118 }))
2119 }),
2120 )
2121 .children(show_excerpt_controls.then(|| {
2122 h_flex()
2123 .flex_basis(Length::Definite(DefiniteLength::Fraction(0.333)))
2124 .pt_1()
2125 .justify_end()
2126 .flex_none()
2127 .w(icon_offset - header_padding)
2128 .child(
2129 ButtonLike::new("expand-icon")
2130 .style(ButtonStyle::Transparent)
2131 .child(
2132 svg()
2133 .path(IconName::ArrowUpFromLine.path())
2134 .size(IconSize::XSmall.rems())
2135 .text_color(
2136 cx.theme().colors().editor_line_number,
2137 )
2138 .group("")
2139 .hover(|style| {
2140 style.text_color(
2141 cx.theme()
2142 .colors()
2143 .editor_active_line_number,
2144 )
2145 }),
2146 )
2147 .on_click(cx.listener_for(&self.editor, {
2148 let id = *id;
2149 move |editor, _, cx| {
2150 editor.expand_excerpt(
2151 id,
2152 multi_buffer::ExpandExcerptDirection::Up,
2153 cx,
2154 );
2155 }
2156 }))
2157 .tooltip({
2158 move |cx| {
2159 Tooltip::for_action(
2160 "Expand Excerpt",
2161 &ExpandExcerpts { lines: 0 },
2162 cx,
2163 )
2164 }
2165 }),
2166 )
2167 }))
2168 } else {
2169 v_flex()
2170 .id(("excerpt header", EntityId::from(block_id)))
2171 .size_full()
2172 .child(
2173 div()
2174 .flex()
2175 .v_flex()
2176 .justify_start()
2177 .id("jump to collapsed context")
2178 .w(relative(1.0))
2179 .h_full()
2180 .child(
2181 div()
2182 .h_px()
2183 .w_full()
2184 .bg(cx.theme().colors().border_variant)
2185 .group_hover("excerpt-jump-action", |style| {
2186 style.bg(cx.theme().colors().border)
2187 }),
2188 ),
2189 )
2190 .child(
2191 h_flex()
2192 .justify_end()
2193 .flex_none()
2194 .w(icon_offset)
2195 .h_full()
2196 .child(
2197 show_excerpt_controls.then(|| {
2198 ButtonLike::new("expand-icon")
2199 .style(ButtonStyle::Transparent)
2200 .child(
2201 svg()
2202 .path(IconName::ArrowUpFromLine.path())
2203 .size(IconSize::XSmall.rems())
2204 .text_color(
2205 cx.theme().colors().editor_line_number,
2206 )
2207 .group("")
2208 .hover(|style| {
2209 style.text_color(
2210 cx.theme()
2211 .colors()
2212 .editor_active_line_number,
2213 )
2214 }),
2215 )
2216 .on_click(cx.listener_for(&self.editor, {
2217 let id = *id;
2218 move |editor, _, cx| {
2219 editor.expand_excerpt(
2220 id,
2221 multi_buffer::ExpandExcerptDirection::Up,
2222 cx,
2223 );
2224 }
2225 }))
2226 .tooltip({
2227 move |cx| {
2228 Tooltip::for_action(
2229 "Expand Excerpt",
2230 &ExpandExcerpts { lines: 0 },
2231 cx,
2232 )
2233 }
2234 })
2235 }).unwrap_or_else(|| {
2236 ButtonLike::new("jump-icon")
2237 .style(ButtonStyle::Transparent)
2238 .child(
2239 svg()
2240 .path(IconName::ArrowUpRight.path())
2241 .size(IconSize::XSmall.rems())
2242 .text_color(
2243 cx.theme().colors().border_variant,
2244 )
2245 .group("excerpt-jump-action")
2246 .group_hover("excerpt-jump-action", |style| {
2247 style.text_color(
2248 cx.theme().colors().border
2249
2250 )
2251 })
2252 )
2253 .when_some(jump_data.clone(), |this, jump_data| {
2254 this.on_click(cx.listener_for(&self.editor, {
2255 let path = jump_data.path.clone();
2256 move |editor, _, cx| {
2257 cx.stop_propagation();
2258
2259 editor.jump(
2260 path.clone(),
2261 jump_data.position,
2262 jump_data.anchor,
2263 jump_data.line_offset_from_top,
2264 cx,
2265 );
2266 }
2267 }))
2268 .tooltip(move |cx| {
2269 Tooltip::for_action(
2270 format!(
2271 "Jump to {}:L{}",
2272 jump_data.path.path.display(),
2273 jump_data.position.row + 1
2274 ),
2275 &OpenExcerpts,
2276 cx,
2277 )
2278 })
2279 })
2280 })
2281
2282 ),
2283 )
2284 .group("excerpt-jump-action")
2285 .cursor_pointer()
2286 .when_some(jump_data.clone(), |this, jump_data| {
2287 this.on_click(cx.listener_for(&self.editor, {
2288 let path = jump_data.path.clone();
2289 move |editor, _, cx| {
2290 cx.stop_propagation();
2291
2292 editor.jump(
2293 path.clone(),
2294 jump_data.position,
2295 jump_data.anchor,
2296 jump_data.line_offset_from_top,
2297 cx,
2298 );
2299 }
2300 }))
2301 .tooltip(move |cx| {
2302 Tooltip::for_action(
2303 format!(
2304 "Jump to {}:L{}",
2305 jump_data.path.path.display(),
2306 jump_data.position.row + 1
2307 ),
2308 &OpenExcerpts,
2309 cx,
2310 )
2311 })
2312 })
2313 };
2314 element.into_any()
2315 }
2316
2317 TransformBlock::ExcerptFooter { id, .. } => {
2318 let element = v_flex()
2319 .id(("excerpt footer", EntityId::from(block_id)))
2320 .size_full()
2321 .child(
2322 h_flex()
2323 .justify_end()
2324 .flex_none()
2325 .w(gutter_dimensions.width
2326 - (gutter_dimensions.left_padding + gutter_dimensions.margin))
2327 .h_full()
2328 .child(
2329 ButtonLike::new("expand-icon")
2330 .style(ButtonStyle::Transparent)
2331 .child(
2332 svg()
2333 .path(IconName::ArrowDownFromLine.path())
2334 .size(IconSize::XSmall.rems())
2335 .text_color(cx.theme().colors().editor_line_number)
2336 .group("")
2337 .hover(|style| {
2338 style.text_color(
2339 cx.theme()
2340 .colors()
2341 .editor_active_line_number,
2342 )
2343 }),
2344 )
2345 .on_click(cx.listener_for(&self.editor, {
2346 let id = *id;
2347 move |editor, _, cx| {
2348 editor.expand_excerpt(
2349 id,
2350 multi_buffer::ExpandExcerptDirection::Down,
2351 cx,
2352 );
2353 }
2354 }))
2355 .tooltip({
2356 move |cx| {
2357 Tooltip::for_action(
2358 "Expand Excerpt",
2359 &ExpandExcerpts { lines: 0 },
2360 cx,
2361 )
2362 }
2363 }),
2364 ),
2365 );
2366 element.into_any()
2367 }
2368 };
2369
2370 let size = element.layout_as_root(available_space, cx);
2371 (element, size)
2372 };
2373
2374 let mut fixed_block_max_width = Pixels::ZERO;
2375 let mut blocks = Vec::new();
2376 for (row, block) in fixed_blocks {
2377 let available_space = size(
2378 AvailableSpace::MinContent,
2379 AvailableSpace::Definite(block.height() as f32 * line_height),
2380 );
2381 let block_id = block.id();
2382 let (element, element_size) = render_block(block, available_space, block_id, row, cx);
2383 fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
2384 blocks.push(BlockLayout {
2385 row,
2386 element,
2387 available_space,
2388 style: BlockStyle::Fixed,
2389 });
2390 }
2391 for (row, block) in non_fixed_blocks {
2392 let style = match block {
2393 TransformBlock::Custom(block) => block.style(),
2394 TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
2395 TransformBlock::ExcerptFooter { .. } => BlockStyle::Sticky,
2396 };
2397 let width = match style {
2398 BlockStyle::Sticky => hitbox.size.width,
2399 BlockStyle::Flex => hitbox
2400 .size
2401 .width
2402 .max(fixed_block_max_width)
2403 .max(gutter_dimensions.width + *scroll_width),
2404 BlockStyle::Fixed => unreachable!(),
2405 };
2406 let available_space = size(
2407 AvailableSpace::Definite(width),
2408 AvailableSpace::Definite(block.height() as f32 * line_height),
2409 );
2410 let block_id = block.id();
2411 let (element, _) = render_block(block, available_space, block_id, row, cx);
2412 blocks.push(BlockLayout {
2413 row,
2414 element,
2415 available_space,
2416 style,
2417 });
2418 }
2419
2420 *scroll_width = (*scroll_width).max(fixed_block_max_width - gutter_dimensions.width);
2421 blocks
2422 }
2423
2424 fn layout_blocks(
2425 &self,
2426 blocks: &mut Vec<BlockLayout>,
2427 hitbox: &Hitbox,
2428 line_height: Pixels,
2429 scroll_pixel_position: gpui::Point<Pixels>,
2430 cx: &mut WindowContext,
2431 ) {
2432 for block in blocks {
2433 let mut origin = hitbox.origin
2434 + point(
2435 Pixels::ZERO,
2436 block.row.as_f32() * line_height - scroll_pixel_position.y,
2437 );
2438 if !matches!(block.style, BlockStyle::Sticky) {
2439 origin += point(-scroll_pixel_position.x, Pixels::ZERO);
2440 }
2441 block
2442 .element
2443 .prepaint_as_root(origin, block.available_space, cx);
2444 }
2445 }
2446
2447 #[allow(clippy::too_many_arguments)]
2448 fn layout_context_menu(
2449 &self,
2450 line_height: Pixels,
2451 hitbox: &Hitbox,
2452 text_hitbox: &Hitbox,
2453 content_origin: gpui::Point<Pixels>,
2454 start_row: DisplayRow,
2455 scroll_pixel_position: gpui::Point<Pixels>,
2456 line_layouts: &[LineWithInvisibles],
2457 newest_selection_head: DisplayPoint,
2458 gutter_overshoot: Pixels,
2459 cx: &mut WindowContext,
2460 ) -> bool {
2461 let max_height = cmp::min(
2462 12. * line_height,
2463 cmp::max(3. * line_height, (hitbox.size.height - line_height) / 2.),
2464 );
2465 let Some((position, mut context_menu)) = self.editor.update(cx, |editor, cx| {
2466 if editor.context_menu_visible() {
2467 editor.render_context_menu(newest_selection_head, &self.style, max_height, cx)
2468 } else {
2469 None
2470 }
2471 }) else {
2472 return false;
2473 };
2474
2475 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
2476 let context_menu_size = context_menu.layout_as_root(available_space, cx);
2477
2478 let (x, y) = match position {
2479 crate::ContextMenuOrigin::EditorPoint(point) => {
2480 let cursor_row_layout = &line_layouts[point.row().minus(start_row) as usize];
2481 let x = cursor_row_layout.x_for_index(point.column() as usize)
2482 - scroll_pixel_position.x;
2483 let y = point.row().next_row().as_f32() * line_height - scroll_pixel_position.y;
2484 (x, y)
2485 }
2486 crate::ContextMenuOrigin::GutterIndicator(row) => {
2487 // Context menu was spawned via a click on a gutter. Ensure it's a bit closer to the indicator than just a plain first column of the
2488 // text field.
2489 let x = -gutter_overshoot;
2490 let y = row.next_row().as_f32() * line_height - scroll_pixel_position.y;
2491 (x, y)
2492 }
2493 };
2494
2495 let mut list_origin = content_origin + point(x, y);
2496 let list_width = context_menu_size.width;
2497 let list_height = context_menu_size.height;
2498
2499 // Snap the right edge of the list to the right edge of the window if
2500 // its horizontal bounds overflow.
2501 if list_origin.x + list_width > cx.viewport_size().width {
2502 list_origin.x = (cx.viewport_size().width - list_width).max(Pixels::ZERO);
2503 }
2504
2505 if list_origin.y + list_height > text_hitbox.lower_right().y {
2506 list_origin.y -= line_height + list_height;
2507 }
2508
2509 cx.defer_draw(context_menu, list_origin, 1);
2510 true
2511 }
2512
2513 fn layout_mouse_context_menu(&self, cx: &mut WindowContext) -> Option<AnyElement> {
2514 let mouse_context_menu = self.editor.read(cx).mouse_context_menu.as_ref()?;
2515 let mut element = deferred(
2516 anchored()
2517 .position(mouse_context_menu.position)
2518 .child(mouse_context_menu.context_menu.clone())
2519 .anchor(AnchorCorner::TopLeft)
2520 .snap_to_window(),
2521 )
2522 .with_priority(1)
2523 .into_any();
2524
2525 element.prepaint_as_root(gpui::Point::default(), AvailableSpace::min_size(), cx);
2526 Some(element)
2527 }
2528
2529 #[allow(clippy::too_many_arguments)]
2530 fn layout_hover_popovers(
2531 &self,
2532 snapshot: &EditorSnapshot,
2533 hitbox: &Hitbox,
2534 text_hitbox: &Hitbox,
2535 visible_display_row_range: Range<DisplayRow>,
2536 content_origin: gpui::Point<Pixels>,
2537 scroll_pixel_position: gpui::Point<Pixels>,
2538 line_layouts: &[LineWithInvisibles],
2539 line_height: Pixels,
2540 em_width: Pixels,
2541 cx: &mut WindowContext,
2542 ) {
2543 struct MeasuredHoverPopover {
2544 element: AnyElement,
2545 size: Size<Pixels>,
2546 horizontal_offset: Pixels,
2547 }
2548
2549 let max_size = size(
2550 (120. * em_width) // Default size
2551 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
2552 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2553 (16. * line_height) // Default size
2554 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
2555 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2556 );
2557
2558 let hover_popovers = self.editor.update(cx, |editor, cx| {
2559 editor.hover_state.render(
2560 &snapshot,
2561 &self.style,
2562 visible_display_row_range.clone(),
2563 max_size,
2564 editor.workspace.as_ref().map(|(w, _)| w.clone()),
2565 cx,
2566 )
2567 });
2568 let Some((position, hover_popovers)) = hover_popovers else {
2569 return;
2570 };
2571
2572 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
2573
2574 // This is safe because we check on layout whether the required row is available
2575 let hovered_row_layout =
2576 &line_layouts[position.row().minus(visible_display_row_range.start) as usize];
2577
2578 // Compute Hovered Point
2579 let x =
2580 hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
2581 let y = position.row().as_f32() * line_height - scroll_pixel_position.y;
2582 let hovered_point = content_origin + point(x, y);
2583
2584 let mut overall_height = Pixels::ZERO;
2585 let mut measured_hover_popovers = Vec::new();
2586 for mut hover_popover in hover_popovers {
2587 let size = hover_popover.layout_as_root(available_space, cx);
2588 let horizontal_offset =
2589 (text_hitbox.upper_right().x - (hovered_point.x + size.width)).min(Pixels::ZERO);
2590
2591 overall_height += HOVER_POPOVER_GAP + size.height;
2592
2593 measured_hover_popovers.push(MeasuredHoverPopover {
2594 element: hover_popover,
2595 size,
2596 horizontal_offset,
2597 });
2598 }
2599 overall_height += HOVER_POPOVER_GAP;
2600
2601 fn draw_occluder(width: Pixels, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
2602 let mut occlusion = div()
2603 .size_full()
2604 .occlude()
2605 .on_mouse_move(|_, cx| cx.stop_propagation())
2606 .into_any_element();
2607 occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), cx);
2608 cx.defer_draw(occlusion, origin, 2);
2609 }
2610
2611 if hovered_point.y > overall_height {
2612 // There is enough space above. Render popovers above the hovered point
2613 let mut current_y = hovered_point.y;
2614 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
2615 let size = popover.size;
2616 let popover_origin = point(
2617 hovered_point.x + popover.horizontal_offset,
2618 current_y - size.height,
2619 );
2620
2621 cx.defer_draw(popover.element, popover_origin, 2);
2622 if position != itertools::Position::Last {
2623 let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
2624 draw_occluder(size.width, origin, cx);
2625 }
2626
2627 current_y = popover_origin.y - HOVER_POPOVER_GAP;
2628 }
2629 } else {
2630 // There is not enough space above. Render popovers below the hovered point
2631 let mut current_y = hovered_point.y + line_height;
2632 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
2633 let size = popover.size;
2634 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
2635
2636 cx.defer_draw(popover.element, popover_origin, 2);
2637 if position != itertools::Position::Last {
2638 let origin = point(popover_origin.x, popover_origin.y + size.height);
2639 draw_occluder(size.width, origin, cx);
2640 }
2641
2642 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
2643 }
2644 }
2645 }
2646
2647 #[allow(clippy::too_many_arguments)]
2648 fn layout_signature_help(
2649 &self,
2650 hitbox: &Hitbox,
2651 content_origin: gpui::Point<Pixels>,
2652 scroll_pixel_position: gpui::Point<Pixels>,
2653 newest_selection_head: Option<DisplayPoint>,
2654 start_row: DisplayRow,
2655 line_layouts: &[LineWithInvisibles],
2656 line_height: Pixels,
2657 em_width: Pixels,
2658 cx: &mut WindowContext,
2659 ) {
2660 let Some(newest_selection_head) = newest_selection_head else {
2661 return;
2662 };
2663 let selection_row = newest_selection_head.row();
2664 if selection_row < start_row {
2665 return;
2666 }
2667 let Some(cursor_row_layout) = line_layouts.get(selection_row.minus(start_row) as usize)
2668 else {
2669 return;
2670 };
2671
2672 let start_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
2673 - scroll_pixel_position.x
2674 + content_origin.x;
2675 let start_y =
2676 selection_row.as_f32() * line_height + content_origin.y - scroll_pixel_position.y;
2677
2678 let max_size = size(
2679 (120. * em_width) // Default size
2680 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
2681 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2682 (16. * line_height) // Default size
2683 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
2684 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2685 );
2686
2687 let maybe_element = self.editor.update(cx, |editor, cx| {
2688 if let Some(popover) = editor.signature_help_state.popover_mut() {
2689 let element = popover.render(
2690 &self.style,
2691 max_size,
2692 editor.workspace.as_ref().map(|(w, _)| w.clone()),
2693 cx,
2694 );
2695 Some(element)
2696 } else {
2697 None
2698 }
2699 });
2700 if let Some(mut element) = maybe_element {
2701 let window_size = cx.viewport_size();
2702 let size = element.layout_as_root(Size::<AvailableSpace>::default(), cx);
2703 let mut point = point(start_x, start_y - size.height);
2704
2705 // Adjusting to ensure the popover does not overflow in the X-axis direction.
2706 if point.x + size.width >= window_size.width {
2707 point.x = window_size.width - size.width;
2708 }
2709
2710 cx.defer_draw(element, point, 1)
2711 }
2712 }
2713
2714 fn paint_background(&self, layout: &EditorLayout, cx: &mut WindowContext) {
2715 cx.paint_layer(layout.hitbox.bounds, |cx| {
2716 let scroll_top = layout.position_map.snapshot.scroll_position().y;
2717 let gutter_bg = cx.theme().colors().editor_gutter_background;
2718 cx.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
2719 cx.paint_quad(fill(layout.text_hitbox.bounds, self.style.background));
2720
2721 if let EditorMode::Full = layout.mode {
2722 let mut active_rows = layout.active_rows.iter().peekable();
2723 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
2724 let mut end_row = start_row.0;
2725 while active_rows
2726 .peek()
2727 .map_or(false, |(active_row, has_selection)| {
2728 active_row.0 == end_row + 1
2729 && *has_selection == contains_non_empty_selection
2730 })
2731 {
2732 active_rows.next().unwrap();
2733 end_row += 1;
2734 }
2735
2736 if !contains_non_empty_selection {
2737 let highlight_h_range =
2738 match layout.position_map.snapshot.current_line_highlight {
2739 CurrentLineHighlight::Gutter => Some(Range {
2740 start: layout.hitbox.left(),
2741 end: layout.gutter_hitbox.right(),
2742 }),
2743 CurrentLineHighlight::Line => Some(Range {
2744 start: layout.text_hitbox.bounds.left(),
2745 end: layout.text_hitbox.bounds.right(),
2746 }),
2747 CurrentLineHighlight::All => Some(Range {
2748 start: layout.hitbox.left(),
2749 end: layout.hitbox.right(),
2750 }),
2751 CurrentLineHighlight::None => None,
2752 };
2753 if let Some(range) = highlight_h_range {
2754 let active_line_bg = cx.theme().colors().editor_active_line_background;
2755 let bounds = Bounds {
2756 origin: point(
2757 range.start,
2758 layout.hitbox.origin.y
2759 + (start_row.as_f32() - scroll_top)
2760 * layout.position_map.line_height,
2761 ),
2762 size: size(
2763 range.end - range.start,
2764 layout.position_map.line_height
2765 * (end_row - start_row.0 + 1) as f32,
2766 ),
2767 };
2768 cx.paint_quad(fill(bounds, active_line_bg));
2769 }
2770 }
2771 }
2772
2773 let mut paint_highlight =
2774 |highlight_row_start: DisplayRow, highlight_row_end: DisplayRow, color| {
2775 let origin = point(
2776 layout.hitbox.origin.x,
2777 layout.hitbox.origin.y
2778 + (highlight_row_start.as_f32() - scroll_top)
2779 * layout.position_map.line_height,
2780 );
2781 let size = size(
2782 layout.hitbox.size.width,
2783 layout.position_map.line_height
2784 * highlight_row_end.next_row().minus(highlight_row_start) as f32,
2785 );
2786 cx.paint_quad(fill(Bounds { origin, size }, color));
2787 };
2788
2789 let mut current_paint: Option<(Hsla, Range<DisplayRow>)> = None;
2790 for (&new_row, &new_color) in &layout.highlighted_rows {
2791 match &mut current_paint {
2792 Some((current_color, current_range)) => {
2793 let current_color = *current_color;
2794 let new_range_started = current_color != new_color
2795 || current_range.end.next_row() != new_row;
2796 if new_range_started {
2797 paint_highlight(
2798 current_range.start,
2799 current_range.end,
2800 current_color,
2801 );
2802 current_paint = Some((new_color, new_row..new_row));
2803 continue;
2804 } else {
2805 current_range.end = current_range.end.next_row();
2806 }
2807 }
2808 None => current_paint = Some((new_color, new_row..new_row)),
2809 };
2810 }
2811 if let Some((color, range)) = current_paint {
2812 paint_highlight(range.start, range.end, color);
2813 }
2814
2815 let scroll_left =
2816 layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
2817
2818 for (wrap_position, active) in layout.wrap_guides.iter() {
2819 let x = (layout.text_hitbox.origin.x
2820 + *wrap_position
2821 + layout.position_map.em_width / 2.)
2822 - scroll_left;
2823
2824 let show_scrollbars = layout
2825 .scrollbar_layout
2826 .as_ref()
2827 .map_or(false, |scrollbar| scrollbar.visible);
2828 if x < layout.text_hitbox.origin.x
2829 || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
2830 {
2831 continue;
2832 }
2833
2834 let color = if *active {
2835 cx.theme().colors().editor_active_wrap_guide
2836 } else {
2837 cx.theme().colors().editor_wrap_guide
2838 };
2839 cx.paint_quad(fill(
2840 Bounds {
2841 origin: point(x, layout.text_hitbox.origin.y),
2842 size: size(px(1.), layout.text_hitbox.size.height),
2843 },
2844 color,
2845 ));
2846 }
2847 }
2848 })
2849 }
2850
2851 fn paint_indent_guides(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2852 let Some(indent_guides) = &layout.indent_guides else {
2853 return;
2854 };
2855
2856 let faded_color = |color: Hsla, alpha: f32| {
2857 let mut faded = color;
2858 faded.a = alpha;
2859 faded
2860 };
2861
2862 for indent_guide in indent_guides {
2863 let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
2864 let settings = indent_guide.settings;
2865
2866 // TODO fixed for now, expose them through themes later
2867 const INDENT_AWARE_ALPHA: f32 = 0.2;
2868 const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
2869 const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
2870 const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
2871
2872 let line_color = match (settings.coloring, indent_guide.active) {
2873 (IndentGuideColoring::Disabled, _) => None,
2874 (IndentGuideColoring::Fixed, false) => {
2875 Some(cx.theme().colors().editor_indent_guide)
2876 }
2877 (IndentGuideColoring::Fixed, true) => {
2878 Some(cx.theme().colors().editor_indent_guide_active)
2879 }
2880 (IndentGuideColoring::IndentAware, false) => {
2881 Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
2882 }
2883 (IndentGuideColoring::IndentAware, true) => {
2884 Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
2885 }
2886 };
2887
2888 let background_color = match (settings.background_coloring, indent_guide.active) {
2889 (IndentGuideBackgroundColoring::Disabled, _) => None,
2890 (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
2891 indent_accent_colors,
2892 INDENT_AWARE_BACKGROUND_ALPHA,
2893 )),
2894 (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
2895 indent_accent_colors,
2896 INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
2897 )),
2898 };
2899
2900 let requested_line_width = if indent_guide.active {
2901 settings.active_line_width
2902 } else {
2903 settings.line_width
2904 }
2905 .clamp(1, 10);
2906 let mut line_indicator_width = 0.;
2907 if let Some(color) = line_color {
2908 cx.paint_quad(fill(
2909 Bounds {
2910 origin: indent_guide.origin,
2911 size: size(px(requested_line_width as f32), indent_guide.length),
2912 },
2913 color,
2914 ));
2915 line_indicator_width = requested_line_width as f32;
2916 }
2917
2918 if let Some(color) = background_color {
2919 let width = indent_guide.single_indent_width - px(line_indicator_width);
2920 cx.paint_quad(fill(
2921 Bounds {
2922 origin: point(
2923 indent_guide.origin.x + px(line_indicator_width),
2924 indent_guide.origin.y,
2925 ),
2926 size: size(width, indent_guide.length),
2927 },
2928 color,
2929 ));
2930 }
2931 }
2932 }
2933
2934 fn paint_line_numbers(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2935 let line_height = layout.position_map.line_height;
2936 let scroll_position = layout.position_map.snapshot.scroll_position();
2937 let scroll_top = scroll_position.y * line_height;
2938
2939 cx.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
2940
2941 for (ix, line) in layout.line_numbers.iter().enumerate() {
2942 if let Some(line) = line {
2943 let line_origin = layout.gutter_hitbox.origin
2944 + point(
2945 layout.gutter_hitbox.size.width
2946 - line.width
2947 - layout.gutter_dimensions.right_padding,
2948 ix as f32 * line_height - (scroll_top % line_height),
2949 );
2950
2951 line.paint(line_origin, line_height, cx).log_err();
2952 }
2953 }
2954 }
2955
2956 fn paint_diff_hunks(layout: &EditorLayout, cx: &mut WindowContext) {
2957 if layout.display_hunks.is_empty() {
2958 return;
2959 }
2960
2961 let line_height = layout.position_map.line_height;
2962 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2963 for (hunk, hitbox) in &layout.display_hunks {
2964 let hunk_to_paint = match hunk {
2965 DisplayDiffHunk::Folded { .. } => {
2966 let hunk_bounds = Self::diff_hunk_bounds(
2967 &layout.position_map.snapshot,
2968 line_height,
2969 layout.gutter_hitbox.bounds,
2970 &hunk,
2971 );
2972 Some((
2973 hunk_bounds,
2974 cx.theme().status().modified,
2975 Corners::all(1. * line_height),
2976 ))
2977 }
2978 DisplayDiffHunk::Unfolded { status, .. } => {
2979 hitbox.as_ref().map(|hunk_hitbox| match status {
2980 DiffHunkStatus::Added => (
2981 hunk_hitbox.bounds,
2982 cx.theme().status().created,
2983 Corners::all(0.05 * line_height),
2984 ),
2985 DiffHunkStatus::Modified => (
2986 hunk_hitbox.bounds,
2987 cx.theme().status().modified,
2988 Corners::all(0.05 * line_height),
2989 ),
2990 DiffHunkStatus::Removed => (
2991 Bounds::new(
2992 point(
2993 hunk_hitbox.origin.x - hunk_hitbox.size.width,
2994 hunk_hitbox.origin.y,
2995 ),
2996 size(hunk_hitbox.size.width * px(2.), hunk_hitbox.size.height),
2997 ),
2998 cx.theme().status().deleted,
2999 Corners::all(1. * line_height),
3000 ),
3001 })
3002 }
3003 };
3004
3005 if let Some((hunk_bounds, background_color, corner_radii)) = hunk_to_paint {
3006 cx.paint_quad(quad(
3007 hunk_bounds,
3008 corner_radii,
3009 background_color,
3010 Edges::default(),
3011 transparent_black(),
3012 ));
3013 }
3014 }
3015 });
3016 }
3017
3018 fn diff_hunk_bounds(
3019 snapshot: &EditorSnapshot,
3020 line_height: Pixels,
3021 bounds: Bounds<Pixels>,
3022 hunk: &DisplayDiffHunk,
3023 ) -> Bounds<Pixels> {
3024 let scroll_position = snapshot.scroll_position();
3025 let scroll_top = scroll_position.y * line_height;
3026
3027 match hunk {
3028 DisplayDiffHunk::Folded { display_row, .. } => {
3029 let start_y = display_row.as_f32() * line_height - scroll_top;
3030 let end_y = start_y + line_height;
3031
3032 let width = 0.275 * line_height;
3033 let highlight_origin = bounds.origin + point(px(0.), start_y);
3034 let highlight_size = size(width, end_y - start_y);
3035 Bounds::new(highlight_origin, highlight_size)
3036 }
3037 DisplayDiffHunk::Unfolded {
3038 display_row_range,
3039 status,
3040 ..
3041 } => match status {
3042 DiffHunkStatus::Added | DiffHunkStatus::Modified => {
3043 let start_row = display_row_range.start;
3044 let end_row = display_row_range.end;
3045 // If we're in a multibuffer, row range span might include an
3046 // excerpt header, so if we were to draw the marker straight away,
3047 // the hunk might include the rows of that header.
3048 // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
3049 // Instead, we simply check whether the range we're dealing with includes
3050 // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
3051 let end_row_in_current_excerpt = snapshot
3052 .blocks_in_range(start_row..end_row)
3053 .find_map(|(start_row, block)| {
3054 if matches!(block, TransformBlock::ExcerptHeader { .. }) {
3055 Some(start_row)
3056 } else {
3057 None
3058 }
3059 })
3060 .unwrap_or(end_row);
3061
3062 let start_y = start_row.as_f32() * line_height - scroll_top;
3063 let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
3064
3065 let width = 0.275 * line_height;
3066 let highlight_origin = bounds.origin + point(px(0.), start_y);
3067 let highlight_size = size(width, end_y - start_y);
3068 Bounds::new(highlight_origin, highlight_size)
3069 }
3070 DiffHunkStatus::Removed => {
3071 let row = display_row_range.start;
3072
3073 let offset = line_height / 2.;
3074 let start_y = row.as_f32() * line_height - offset - scroll_top;
3075 let end_y = start_y + line_height;
3076
3077 let width = 0.35 * line_height;
3078 let highlight_origin = bounds.origin + point(px(0.), start_y);
3079 let highlight_size = size(width, end_y - start_y);
3080 Bounds::new(highlight_origin, highlight_size)
3081 }
3082 },
3083 }
3084 }
3085
3086 fn paint_gutter_indicators(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3087 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3088 cx.with_element_namespace("gutter_fold_toggles", |cx| {
3089 for fold_indicator in layout.gutter_fold_toggles.iter_mut().flatten() {
3090 fold_indicator.paint(cx);
3091 }
3092 });
3093
3094 for test_indicators in layout.test_indicators.iter_mut() {
3095 test_indicators.paint(cx);
3096 }
3097
3098 if let Some(indicator) = layout.code_actions_indicator.as_mut() {
3099 indicator.paint(cx);
3100 }
3101 });
3102 }
3103
3104 fn paint_gutter_highlights(&self, layout: &EditorLayout, cx: &mut WindowContext) {
3105 for (_, hunk_hitbox) in &layout.display_hunks {
3106 if let Some(hunk_hitbox) = hunk_hitbox {
3107 cx.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
3108 }
3109 }
3110
3111 let show_git_gutter = layout
3112 .position_map
3113 .snapshot
3114 .show_git_diff_gutter
3115 .unwrap_or_else(|| {
3116 matches!(
3117 ProjectSettings::get_global(cx).git.git_gutter,
3118 Some(GitGutterSetting::TrackedFiles)
3119 )
3120 });
3121 if show_git_gutter {
3122 Self::paint_diff_hunks(layout, cx)
3123 }
3124
3125 let highlight_width = 0.275 * layout.position_map.line_height;
3126 let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
3127 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3128 for (range, color) in &layout.highlighted_gutter_ranges {
3129 let start_row = if range.start.row() < layout.visible_display_row_range.start {
3130 layout.visible_display_row_range.start - DisplayRow(1)
3131 } else {
3132 range.start.row()
3133 };
3134 let end_row = if range.end.row() > layout.visible_display_row_range.end {
3135 layout.visible_display_row_range.end + DisplayRow(1)
3136 } else {
3137 range.end.row()
3138 };
3139
3140 let start_y = layout.gutter_hitbox.top()
3141 + start_row.0 as f32 * layout.position_map.line_height
3142 - layout.position_map.scroll_pixel_position.y;
3143 let end_y = layout.gutter_hitbox.top()
3144 + (end_row.0 + 1) as f32 * layout.position_map.line_height
3145 - layout.position_map.scroll_pixel_position.y;
3146 let bounds = Bounds::from_corners(
3147 point(layout.gutter_hitbox.left(), start_y),
3148 point(layout.gutter_hitbox.left() + highlight_width, end_y),
3149 );
3150 cx.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
3151 }
3152 });
3153 }
3154
3155 fn paint_blamed_display_rows(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3156 let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
3157 return;
3158 };
3159
3160 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3161 for mut blame_element in blamed_display_rows.into_iter() {
3162 blame_element.paint(cx);
3163 }
3164 })
3165 }
3166
3167 fn paint_text(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3168 cx.with_content_mask(
3169 Some(ContentMask {
3170 bounds: layout.text_hitbox.bounds,
3171 }),
3172 |cx| {
3173 let cursor_style = if self
3174 .editor
3175 .read(cx)
3176 .hovered_link_state
3177 .as_ref()
3178 .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
3179 {
3180 CursorStyle::PointingHand
3181 } else {
3182 CursorStyle::IBeam
3183 };
3184 cx.set_cursor_style(cursor_style, &layout.text_hitbox);
3185
3186 let invisible_display_ranges = self.paint_highlights(layout, cx);
3187 self.paint_lines(&invisible_display_ranges, layout, cx);
3188 self.paint_redactions(layout, cx);
3189 self.paint_cursors(layout, cx);
3190 self.paint_inline_blame(layout, cx);
3191 cx.with_element_namespace("crease_trailers", |cx| {
3192 for trailer in layout.crease_trailers.iter_mut().flatten() {
3193 trailer.element.paint(cx);
3194 }
3195 });
3196 },
3197 )
3198 }
3199
3200 fn paint_highlights(
3201 &mut self,
3202 layout: &mut EditorLayout,
3203 cx: &mut WindowContext,
3204 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
3205 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3206 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
3207 let line_end_overshoot = 0.15 * layout.position_map.line_height;
3208 for (range, color) in &layout.highlighted_ranges {
3209 self.paint_highlighted_range(
3210 range.clone(),
3211 *color,
3212 Pixels::ZERO,
3213 line_end_overshoot,
3214 layout,
3215 cx,
3216 );
3217 }
3218
3219 let corner_radius = 0.15 * layout.position_map.line_height;
3220
3221 for (player_color, selections) in &layout.selections {
3222 for selection in selections.into_iter() {
3223 self.paint_highlighted_range(
3224 selection.range.clone(),
3225 player_color.selection,
3226 corner_radius,
3227 corner_radius * 2.,
3228 layout,
3229 cx,
3230 );
3231
3232 if selection.is_local && !selection.range.is_empty() {
3233 invisible_display_ranges.push(selection.range.clone());
3234 }
3235 }
3236 }
3237 invisible_display_ranges
3238 })
3239 }
3240
3241 fn paint_lines(
3242 &mut self,
3243 invisible_display_ranges: &[Range<DisplayPoint>],
3244 layout: &mut EditorLayout,
3245 cx: &mut WindowContext,
3246 ) {
3247 let whitespace_setting = self
3248 .editor
3249 .read(cx)
3250 .buffer
3251 .read(cx)
3252 .settings_at(0, cx)
3253 .show_whitespaces;
3254
3255 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
3256 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
3257 line_with_invisibles.draw(
3258 layout,
3259 row,
3260 layout.content_origin,
3261 whitespace_setting,
3262 invisible_display_ranges,
3263 cx,
3264 )
3265 }
3266
3267 for line_element in &mut layout.line_elements {
3268 line_element.paint(cx);
3269 }
3270 }
3271
3272 fn paint_redactions(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
3273 if layout.redacted_ranges.is_empty() {
3274 return;
3275 }
3276
3277 let line_end_overshoot = layout.line_end_overshoot();
3278
3279 // A softer than perfect black
3280 let redaction_color = gpui::rgb(0x0e1111);
3281
3282 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3283 for range in layout.redacted_ranges.iter() {
3284 self.paint_highlighted_range(
3285 range.clone(),
3286 redaction_color.into(),
3287 Pixels::ZERO,
3288 line_end_overshoot,
3289 layout,
3290 cx,
3291 );
3292 }
3293 });
3294 }
3295
3296 fn paint_cursors(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3297 for cursor in &mut layout.visible_cursors {
3298 cursor.paint(layout.content_origin, cx);
3299 }
3300 }
3301
3302 fn paint_scrollbar(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3303 let Some(scrollbar_layout) = layout.scrollbar_layout.as_ref() else {
3304 return;
3305 };
3306
3307 let thumb_bounds = scrollbar_layout.thumb_bounds();
3308 if scrollbar_layout.visible {
3309 cx.paint_layer(scrollbar_layout.hitbox.bounds, |cx| {
3310 cx.paint_quad(quad(
3311 scrollbar_layout.hitbox.bounds,
3312 Corners::default(),
3313 cx.theme().colors().scrollbar_track_background,
3314 Edges {
3315 top: Pixels::ZERO,
3316 right: Pixels::ZERO,
3317 bottom: Pixels::ZERO,
3318 left: ScrollbarLayout::BORDER_WIDTH,
3319 },
3320 cx.theme().colors().scrollbar_track_border,
3321 ));
3322
3323 let fast_markers =
3324 self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
3325 // Refresh slow scrollbar markers in the background. Below, we paint whatever markers have already been computed.
3326 self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, cx);
3327
3328 let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
3329 for marker in markers.iter().chain(&fast_markers) {
3330 let mut marker = marker.clone();
3331 marker.bounds.origin += scrollbar_layout.hitbox.origin;
3332 cx.paint_quad(marker);
3333 }
3334
3335 cx.paint_quad(quad(
3336 thumb_bounds,
3337 Corners::default(),
3338 cx.theme().colors().scrollbar_thumb_background,
3339 Edges {
3340 top: Pixels::ZERO,
3341 right: Pixels::ZERO,
3342 bottom: Pixels::ZERO,
3343 left: ScrollbarLayout::BORDER_WIDTH,
3344 },
3345 cx.theme().colors().scrollbar_thumb_border,
3346 ));
3347 });
3348 }
3349
3350 cx.set_cursor_style(CursorStyle::Arrow, &scrollbar_layout.hitbox);
3351
3352 let row_height = scrollbar_layout.row_height;
3353 let row_range = scrollbar_layout.visible_row_range.clone();
3354
3355 cx.on_mouse_event({
3356 let editor = self.editor.clone();
3357 let hitbox = scrollbar_layout.hitbox.clone();
3358 let mut mouse_position = cx.mouse_position();
3359 move |event: &MouseMoveEvent, phase, cx| {
3360 if phase == DispatchPhase::Capture {
3361 return;
3362 }
3363
3364 editor.update(cx, |editor, cx| {
3365 if event.pressed_button == Some(MouseButton::Left)
3366 && editor.scroll_manager.is_dragging_scrollbar()
3367 {
3368 let y = mouse_position.y;
3369 let new_y = event.position.y;
3370 if (hitbox.top()..hitbox.bottom()).contains(&y) {
3371 let mut position = editor.scroll_position(cx);
3372 position.y += (new_y - y) / row_height;
3373 if position.y < 0.0 {
3374 position.y = 0.0;
3375 }
3376 editor.set_scroll_position(position, cx);
3377 }
3378
3379 cx.stop_propagation();
3380 } else {
3381 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
3382 if hitbox.is_hovered(cx) {
3383 editor.scroll_manager.show_scrollbar(cx);
3384 }
3385 }
3386 mouse_position = event.position;
3387 })
3388 }
3389 });
3390
3391 if self.editor.read(cx).scroll_manager.is_dragging_scrollbar() {
3392 cx.on_mouse_event({
3393 let editor = self.editor.clone();
3394 move |_: &MouseUpEvent, phase, cx| {
3395 if phase == DispatchPhase::Capture {
3396 return;
3397 }
3398
3399 editor.update(cx, |editor, cx| {
3400 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
3401 cx.stop_propagation();
3402 });
3403 }
3404 });
3405 } else {
3406 cx.on_mouse_event({
3407 let editor = self.editor.clone();
3408 let hitbox = scrollbar_layout.hitbox.clone();
3409 move |event: &MouseDownEvent, phase, cx| {
3410 if phase == DispatchPhase::Capture || !hitbox.is_hovered(cx) {
3411 return;
3412 }
3413
3414 editor.update(cx, |editor, cx| {
3415 editor.scroll_manager.set_is_dragging_scrollbar(true, cx);
3416
3417 let y = event.position.y;
3418 if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
3419 let center_row = ((y - hitbox.top()) / row_height).round() as u32;
3420 let top_row = center_row
3421 .saturating_sub((row_range.end - row_range.start) as u32 / 2);
3422 let mut position = editor.scroll_position(cx);
3423 position.y = top_row as f32;
3424 editor.set_scroll_position(position, cx);
3425 } else {
3426 editor.scroll_manager.show_scrollbar(cx);
3427 }
3428
3429 cx.stop_propagation();
3430 });
3431 }
3432 });
3433 }
3434 }
3435
3436 fn collect_fast_scrollbar_markers(
3437 &self,
3438 layout: &EditorLayout,
3439 scrollbar_layout: &ScrollbarLayout,
3440 cx: &mut WindowContext,
3441 ) -> Vec<PaintQuad> {
3442 const LIMIT: usize = 100;
3443 if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
3444 return vec![];
3445 }
3446 let cursor_ranges = layout
3447 .cursors
3448 .iter()
3449 .map(|(point, color)| ColoredRange {
3450 start: point.row(),
3451 end: point.row(),
3452 color: *color,
3453 })
3454 .collect_vec();
3455 scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
3456 }
3457
3458 fn refresh_slow_scrollbar_markers(
3459 &self,
3460 layout: &EditorLayout,
3461 scrollbar_layout: &ScrollbarLayout,
3462 cx: &mut WindowContext,
3463 ) {
3464 self.editor.update(cx, |editor, cx| {
3465 if !editor.is_singleton(cx)
3466 || !editor
3467 .scrollbar_marker_state
3468 .should_refresh(scrollbar_layout.hitbox.size)
3469 {
3470 return;
3471 }
3472
3473 let scrollbar_layout = scrollbar_layout.clone();
3474 let background_highlights = editor.background_highlights.clone();
3475 let snapshot = layout.position_map.snapshot.clone();
3476 let theme = cx.theme().clone();
3477 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
3478
3479 editor.scrollbar_marker_state.dirty = false;
3480 editor.scrollbar_marker_state.pending_refresh =
3481 Some(cx.spawn(|editor, mut cx| async move {
3482 let scrollbar_size = scrollbar_layout.hitbox.size;
3483 let scrollbar_markers = cx
3484 .background_executor()
3485 .spawn(async move {
3486 let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
3487 let mut marker_quads = Vec::new();
3488 if scrollbar_settings.git_diff {
3489 let marker_row_ranges = snapshot
3490 .buffer_snapshot
3491 .git_diff_hunks_in_range(
3492 MultiBufferRow::MIN..MultiBufferRow::MAX,
3493 )
3494 .map(|hunk| {
3495 let start_display_row =
3496 MultiBufferPoint::new(hunk.associated_range.start.0, 0)
3497 .to_display_point(&snapshot.display_snapshot)
3498 .row();
3499 let mut end_display_row =
3500 MultiBufferPoint::new(hunk.associated_range.end.0, 0)
3501 .to_display_point(&snapshot.display_snapshot)
3502 .row();
3503 if end_display_row != start_display_row {
3504 end_display_row.0 -= 1;
3505 }
3506 let color = match hunk_status(&hunk) {
3507 DiffHunkStatus::Added => theme.status().created,
3508 DiffHunkStatus::Modified => theme.status().modified,
3509 DiffHunkStatus::Removed => theme.status().deleted,
3510 };
3511 ColoredRange {
3512 start: start_display_row,
3513 end: end_display_row,
3514 color,
3515 }
3516 });
3517
3518 marker_quads.extend(
3519 scrollbar_layout
3520 .marker_quads_for_ranges(marker_row_ranges, Some(0)),
3521 );
3522 }
3523
3524 for (background_highlight_id, (_, background_ranges)) in
3525 background_highlights.iter()
3526 {
3527 let is_search_highlights = *background_highlight_id
3528 == TypeId::of::<BufferSearchHighlights>();
3529 let is_symbol_occurrences = *background_highlight_id
3530 == TypeId::of::<DocumentHighlightRead>()
3531 || *background_highlight_id
3532 == TypeId::of::<DocumentHighlightWrite>();
3533 if (is_search_highlights && scrollbar_settings.search_results)
3534 || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
3535 {
3536 let mut color = theme.status().info;
3537 if is_symbol_occurrences {
3538 color.fade_out(0.5);
3539 }
3540 let marker_row_ranges =
3541 background_ranges.into_iter().map(|range| {
3542 let display_start = range
3543 .start
3544 .to_display_point(&snapshot.display_snapshot);
3545 let display_end = range
3546 .end
3547 .to_display_point(&snapshot.display_snapshot);
3548 ColoredRange {
3549 start: display_start.row(),
3550 end: display_end.row(),
3551 color,
3552 }
3553 });
3554 marker_quads.extend(
3555 scrollbar_layout
3556 .marker_quads_for_ranges(marker_row_ranges, Some(1)),
3557 );
3558 }
3559 }
3560
3561 if scrollbar_settings.diagnostics {
3562 let diagnostics = snapshot
3563 .buffer_snapshot
3564 .diagnostics_in_range::<_, Point>(
3565 Point::zero()..max_point,
3566 false,
3567 )
3568 // We want to sort by severity, in order to paint the most severe diagnostics last.
3569 .sorted_by_key(|diagnostic| {
3570 std::cmp::Reverse(diagnostic.diagnostic.severity)
3571 });
3572
3573 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
3574 let start_display = diagnostic
3575 .range
3576 .start
3577 .to_display_point(&snapshot.display_snapshot);
3578 let end_display = diagnostic
3579 .range
3580 .end
3581 .to_display_point(&snapshot.display_snapshot);
3582 let color = match diagnostic.diagnostic.severity {
3583 DiagnosticSeverity::ERROR => theme.status().error,
3584 DiagnosticSeverity::WARNING => theme.status().warning,
3585 DiagnosticSeverity::INFORMATION => theme.status().info,
3586 _ => theme.status().hint,
3587 };
3588 ColoredRange {
3589 start: start_display.row(),
3590 end: end_display.row(),
3591 color,
3592 }
3593 });
3594 marker_quads.extend(
3595 scrollbar_layout
3596 .marker_quads_for_ranges(marker_row_ranges, Some(2)),
3597 );
3598 }
3599
3600 Arc::from(marker_quads)
3601 })
3602 .await;
3603
3604 editor.update(&mut cx, |editor, cx| {
3605 editor.scrollbar_marker_state.markers = scrollbar_markers;
3606 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
3607 editor.scrollbar_marker_state.pending_refresh = None;
3608 cx.notify();
3609 })?;
3610
3611 Ok(())
3612 }));
3613 });
3614 }
3615
3616 #[allow(clippy::too_many_arguments)]
3617 fn paint_highlighted_range(
3618 &self,
3619 range: Range<DisplayPoint>,
3620 color: Hsla,
3621 corner_radius: Pixels,
3622 line_end_overshoot: Pixels,
3623 layout: &EditorLayout,
3624 cx: &mut WindowContext,
3625 ) {
3626 let start_row = layout.visible_display_row_range.start;
3627 let end_row = layout.visible_display_row_range.end;
3628 if range.start != range.end {
3629 let row_range = if range.end.column() == 0 {
3630 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
3631 } else {
3632 cmp::max(range.start.row(), start_row)
3633 ..cmp::min(range.end.row().next_row(), end_row)
3634 };
3635
3636 let highlighted_range = HighlightedRange {
3637 color,
3638 line_height: layout.position_map.line_height,
3639 corner_radius,
3640 start_y: layout.content_origin.y
3641 + row_range.start.as_f32() * layout.position_map.line_height
3642 - layout.position_map.scroll_pixel_position.y,
3643 lines: row_range
3644 .iter_rows()
3645 .map(|row| {
3646 let line_layout =
3647 &layout.position_map.line_layouts[row.minus(start_row) as usize];
3648 HighlightedRangeLine {
3649 start_x: if row == range.start.row() {
3650 layout.content_origin.x
3651 + line_layout.x_for_index(range.start.column() as usize)
3652 - layout.position_map.scroll_pixel_position.x
3653 } else {
3654 layout.content_origin.x
3655 - layout.position_map.scroll_pixel_position.x
3656 },
3657 end_x: if row == range.end.row() {
3658 layout.content_origin.x
3659 + line_layout.x_for_index(range.end.column() as usize)
3660 - layout.position_map.scroll_pixel_position.x
3661 } else {
3662 layout.content_origin.x + line_layout.width + line_end_overshoot
3663 - layout.position_map.scroll_pixel_position.x
3664 },
3665 }
3666 })
3667 .collect(),
3668 };
3669
3670 highlighted_range.paint(layout.text_hitbox.bounds, cx);
3671 }
3672 }
3673
3674 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3675 if let Some(mut inline_blame) = layout.inline_blame.take() {
3676 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3677 inline_blame.paint(cx);
3678 })
3679 }
3680 }
3681
3682 fn paint_blocks(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3683 for mut block in layout.blocks.drain(..) {
3684 block.element.paint(cx);
3685 }
3686 }
3687
3688 fn paint_mouse_context_menu(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3689 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
3690 mouse_context_menu.paint(cx);
3691 }
3692 }
3693
3694 fn paint_scroll_wheel_listener(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
3695 cx.on_mouse_event({
3696 let position_map = layout.position_map.clone();
3697 let editor = self.editor.clone();
3698 let hitbox = layout.hitbox.clone();
3699 let mut delta = ScrollDelta::default();
3700
3701 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
3702 // accidentally turn off their scrolling.
3703 let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
3704
3705 move |event: &ScrollWheelEvent, phase, cx| {
3706 if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
3707 delta = delta.coalesce(event.delta);
3708 editor.update(cx, |editor, cx| {
3709 let position_map: &PositionMap = &position_map;
3710
3711 let line_height = position_map.line_height;
3712 let max_glyph_width = position_map.em_width;
3713 let (delta, axis) = match delta {
3714 gpui::ScrollDelta::Pixels(mut pixels) => {
3715 //Trackpad
3716 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
3717 (pixels, axis)
3718 }
3719
3720 gpui::ScrollDelta::Lines(lines) => {
3721 //Not trackpad
3722 let pixels =
3723 point(lines.x * max_glyph_width, lines.y * line_height);
3724 (pixels, None)
3725 }
3726 };
3727
3728 let current_scroll_position = position_map.snapshot.scroll_position();
3729 let x = (current_scroll_position.x * max_glyph_width
3730 - (delta.x * scroll_sensitivity))
3731 / max_glyph_width;
3732 let y = (current_scroll_position.y * line_height
3733 - (delta.y * scroll_sensitivity))
3734 / line_height;
3735 let mut scroll_position =
3736 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
3737 let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
3738 if forbid_vertical_scroll {
3739 scroll_position.y = current_scroll_position.y;
3740 }
3741
3742 if scroll_position != current_scroll_position {
3743 editor.scroll(scroll_position, axis, cx);
3744 cx.stop_propagation();
3745 } else if y < 0. {
3746 // Due to clamping, we may fail to detect cases of overscroll to the top;
3747 // We want the scroll manager to get an update in such cases and detect the change of direction
3748 // on the next frame.
3749 cx.notify();
3750 }
3751 });
3752 }
3753 }
3754 });
3755 }
3756
3757 fn paint_mouse_listeners(
3758 &mut self,
3759 layout: &EditorLayout,
3760 hovered_hunk: Option<HunkToExpand>,
3761 cx: &mut WindowContext,
3762 ) {
3763 self.paint_scroll_wheel_listener(layout, cx);
3764
3765 cx.on_mouse_event({
3766 let position_map = layout.position_map.clone();
3767 let editor = self.editor.clone();
3768 let text_hitbox = layout.text_hitbox.clone();
3769 let gutter_hitbox = layout.gutter_hitbox.clone();
3770
3771 move |event: &MouseDownEvent, phase, cx| {
3772 if phase == DispatchPhase::Bubble {
3773 match event.button {
3774 MouseButton::Left => editor.update(cx, |editor, cx| {
3775 Self::mouse_left_down(
3776 editor,
3777 event,
3778 hovered_hunk.as_ref(),
3779 &position_map,
3780 &text_hitbox,
3781 &gutter_hitbox,
3782 cx,
3783 );
3784 }),
3785 MouseButton::Right => editor.update(cx, |editor, cx| {
3786 Self::mouse_right_down(editor, event, &position_map, &text_hitbox, cx);
3787 }),
3788 MouseButton::Middle => editor.update(cx, |editor, cx| {
3789 Self::mouse_middle_down(editor, event, &position_map, &text_hitbox, cx);
3790 }),
3791 _ => {}
3792 };
3793 }
3794 }
3795 });
3796
3797 cx.on_mouse_event({
3798 let editor = self.editor.clone();
3799 let position_map = layout.position_map.clone();
3800 let text_hitbox = layout.text_hitbox.clone();
3801
3802 move |event: &MouseUpEvent, phase, cx| {
3803 if phase == DispatchPhase::Bubble {
3804 editor.update(cx, |editor, cx| {
3805 Self::mouse_up(editor, event, &position_map, &text_hitbox, cx)
3806 });
3807 }
3808 }
3809 });
3810 cx.on_mouse_event({
3811 let position_map = layout.position_map.clone();
3812 let editor = self.editor.clone();
3813 let text_hitbox = layout.text_hitbox.clone();
3814 let gutter_hitbox = layout.gutter_hitbox.clone();
3815
3816 move |event: &MouseMoveEvent, phase, cx| {
3817 if phase == DispatchPhase::Bubble {
3818 editor.update(cx, |editor, cx| {
3819 if editor.hover_state.focused(cx) {
3820 return;
3821 }
3822 if event.pressed_button == Some(MouseButton::Left)
3823 || event.pressed_button == Some(MouseButton::Middle)
3824 {
3825 Self::mouse_dragged(
3826 editor,
3827 event,
3828 &position_map,
3829 text_hitbox.bounds,
3830 cx,
3831 )
3832 }
3833
3834 Self::mouse_moved(
3835 editor,
3836 event,
3837 &position_map,
3838 &text_hitbox,
3839 &gutter_hitbox,
3840 cx,
3841 )
3842 });
3843 }
3844 }
3845 });
3846 }
3847
3848 fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
3849 bounds.upper_right().x - self.style.scrollbar_width
3850 }
3851
3852 fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
3853 let style = &self.style;
3854 let font_size = style.text.font_size.to_pixels(cx.rem_size());
3855 let layout = cx
3856 .text_system()
3857 .shape_line(
3858 SharedString::from(" ".repeat(column)),
3859 font_size,
3860 &[TextRun {
3861 len: column,
3862 font: style.text.font(),
3863 color: Hsla::default(),
3864 background_color: None,
3865 underline: None,
3866 strikethrough: None,
3867 }],
3868 )
3869 .unwrap();
3870
3871 layout.width
3872 }
3873
3874 fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
3875 let digit_count = snapshot
3876 .max_buffer_row()
3877 .next_row()
3878 .as_f32()
3879 .log10()
3880 .floor() as usize
3881 + 1;
3882 self.column_pixels(digit_count, cx)
3883 }
3884}
3885
3886fn prepaint_gutter_button(
3887 button: IconButton,
3888 row: DisplayRow,
3889 line_height: Pixels,
3890 gutter_dimensions: &GutterDimensions,
3891 scroll_pixel_position: gpui::Point<Pixels>,
3892 gutter_hitbox: &Hitbox,
3893 cx: &mut WindowContext<'_>,
3894) -> AnyElement {
3895 let mut button = button.into_any_element();
3896 let available_space = size(
3897 AvailableSpace::MinContent,
3898 AvailableSpace::Definite(line_height),
3899 );
3900 let indicator_size = button.layout_as_root(available_space, cx);
3901
3902 let blame_width = gutter_dimensions
3903 .git_blame_entries_width
3904 .unwrap_or(Pixels::ZERO);
3905
3906 let mut x = blame_width;
3907 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
3908 - indicator_size.width
3909 - blame_width;
3910 x += available_width / 2.;
3911
3912 let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
3913 y += (line_height - indicator_size.height) / 2.;
3914
3915 button.prepaint_as_root(gutter_hitbox.origin + point(x, y), available_space, cx);
3916 button
3917}
3918
3919fn render_inline_blame_entry(
3920 blame: &gpui::Model<GitBlame>,
3921 blame_entry: BlameEntry,
3922 style: &EditorStyle,
3923 workspace: Option<WeakView<Workspace>>,
3924 cx: &mut WindowContext<'_>,
3925) -> AnyElement {
3926 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
3927
3928 let author = blame_entry.author.as_deref().unwrap_or_default();
3929 let text = format!("{}, {}", author, relative_timestamp);
3930
3931 let details = blame.read(cx).details_for_entry(&blame_entry);
3932
3933 let tooltip = cx.new_view(|_| BlameEntryTooltip::new(blame_entry, details, style, workspace));
3934
3935 h_flex()
3936 .id("inline-blame")
3937 .w_full()
3938 .font_family(style.text.font().family)
3939 .text_color(cx.theme().status().hint)
3940 .line_height(style.text.line_height)
3941 .child(Icon::new(IconName::FileGit).color(Color::Hint))
3942 .child(text)
3943 .gap_2()
3944 .hoverable_tooltip(move |_| tooltip.clone().into())
3945 .into_any()
3946}
3947
3948fn render_blame_entry(
3949 ix: usize,
3950 blame: &gpui::Model<GitBlame>,
3951 blame_entry: BlameEntry,
3952 style: &EditorStyle,
3953 last_used_color: &mut Option<(PlayerColor, Oid)>,
3954 editor: View<Editor>,
3955 cx: &mut WindowContext<'_>,
3956) -> AnyElement {
3957 let mut sha_color = cx
3958 .theme()
3959 .players()
3960 .color_for_participant(blame_entry.sha.into());
3961 // If the last color we used is the same as the one we get for this line, but
3962 // the commit SHAs are different, then we try again to get a different color.
3963 match *last_used_color {
3964 Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
3965 let index: u32 = blame_entry.sha.into();
3966 sha_color = cx.theme().players().color_for_participant(index + 1);
3967 }
3968 _ => {}
3969 };
3970 last_used_color.replace((sha_color, blame_entry.sha));
3971
3972 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
3973
3974 let short_commit_id = blame_entry.sha.display_short();
3975
3976 let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
3977 let name = util::truncate_and_trailoff(author_name, 20);
3978
3979 let details = blame.read(cx).details_for_entry(&blame_entry);
3980
3981 let workspace = editor.read(cx).workspace.as_ref().map(|(w, _)| w.clone());
3982
3983 let tooltip = cx.new_view(|_| {
3984 BlameEntryTooltip::new(blame_entry.clone(), details.clone(), style, workspace)
3985 });
3986
3987 h_flex()
3988 .w_full()
3989 .font_family(style.text.font().family)
3990 .line_height(style.text.line_height)
3991 .id(("blame", ix))
3992 .children([
3993 div()
3994 .text_color(sha_color.cursor)
3995 .child(short_commit_id)
3996 .mr_2(),
3997 div()
3998 .w_full()
3999 .h_flex()
4000 .justify_between()
4001 .text_color(cx.theme().status().hint)
4002 .child(name)
4003 .child(relative_timestamp),
4004 ])
4005 .on_mouse_down(MouseButton::Right, {
4006 let blame_entry = blame_entry.clone();
4007 let details = details.clone();
4008 move |event, cx| {
4009 deploy_blame_entry_context_menu(
4010 &blame_entry,
4011 details.as_ref(),
4012 editor.clone(),
4013 event.position,
4014 cx,
4015 );
4016 }
4017 })
4018 .hover(|style| style.bg(cx.theme().colors().element_hover))
4019 .when_some(
4020 details.and_then(|details| details.permalink),
4021 |this, url| {
4022 let url = url.clone();
4023 this.cursor_pointer().on_click(move |_, cx| {
4024 cx.stop_propagation();
4025 cx.open_url(url.as_str())
4026 })
4027 },
4028 )
4029 .hoverable_tooltip(move |_| tooltip.clone().into())
4030 .into_any()
4031}
4032
4033fn deploy_blame_entry_context_menu(
4034 blame_entry: &BlameEntry,
4035 details: Option<&CommitDetails>,
4036 editor: View<Editor>,
4037 position: gpui::Point<Pixels>,
4038 cx: &mut WindowContext<'_>,
4039) {
4040 let context_menu = ContextMenu::build(cx, move |this, _| {
4041 let sha = format!("{}", blame_entry.sha);
4042 this.entry("Copy commit SHA", None, move |cx| {
4043 cx.write_to_clipboard(ClipboardItem::new(sha.clone()));
4044 })
4045 .when_some(
4046 details.and_then(|details| details.permalink.clone()),
4047 |this, url| this.entry("Open permalink", None, move |cx| cx.open_url(url.as_str())),
4048 )
4049 });
4050
4051 editor.update(cx, move |editor, cx| {
4052 editor.mouse_context_menu = Some(MouseContextMenu::new(position, context_menu, cx));
4053 cx.notify();
4054 });
4055}
4056
4057#[derive(Debug)]
4058pub(crate) struct LineWithInvisibles {
4059 fragments: SmallVec<[LineFragment; 1]>,
4060 invisibles: Vec<Invisible>,
4061 len: usize,
4062 width: Pixels,
4063 font_size: Pixels,
4064}
4065
4066#[allow(clippy::large_enum_variant)]
4067enum LineFragment {
4068 Text(ShapedLine),
4069 Element {
4070 element: Option<AnyElement>,
4071 size: Size<Pixels>,
4072 len: usize,
4073 },
4074}
4075
4076impl fmt::Debug for LineFragment {
4077 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4078 match self {
4079 LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
4080 LineFragment::Element { size, len, .. } => f
4081 .debug_struct("Element")
4082 .field("size", size)
4083 .field("len", len)
4084 .finish(),
4085 }
4086 }
4087}
4088
4089impl LineWithInvisibles {
4090 fn from_chunks<'a>(
4091 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
4092 text_style: &TextStyle,
4093 max_line_len: usize,
4094 max_line_count: usize,
4095 line_number_layouts: &[Option<ShapedLine>],
4096 editor_mode: EditorMode,
4097 cx: &mut WindowContext,
4098 ) -> Vec<Self> {
4099 let mut layouts = Vec::with_capacity(max_line_count);
4100 let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
4101 let mut line = String::new();
4102 let mut invisibles = Vec::new();
4103 let mut width = Pixels::ZERO;
4104 let mut len = 0;
4105 let mut styles = Vec::new();
4106 let mut non_whitespace_added = false;
4107 let mut row = 0;
4108 let mut line_exceeded_max_len = false;
4109 let font_size = text_style.font_size.to_pixels(cx.rem_size());
4110
4111 let ellipsis = SharedString::from("⋯");
4112
4113 for highlighted_chunk in chunks.chain([HighlightedChunk {
4114 text: "\n",
4115 style: None,
4116 is_tab: false,
4117 renderer: None,
4118 }]) {
4119 if let Some(renderer) = highlighted_chunk.renderer {
4120 if !line.is_empty() {
4121 let shaped_line = cx
4122 .text_system()
4123 .shape_line(line.clone().into(), font_size, &styles)
4124 .unwrap();
4125 width += shaped_line.width;
4126 len += shaped_line.len;
4127 fragments.push(LineFragment::Text(shaped_line));
4128 line.clear();
4129 styles.clear();
4130 }
4131
4132 let available_width = if renderer.constrain_width {
4133 let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
4134 ellipsis.clone()
4135 } else {
4136 SharedString::from(Arc::from(highlighted_chunk.text))
4137 };
4138 let shaped_line = cx
4139 .text_system()
4140 .shape_line(
4141 chunk,
4142 font_size,
4143 &[text_style.to_run(highlighted_chunk.text.len())],
4144 )
4145 .unwrap();
4146 AvailableSpace::Definite(shaped_line.width)
4147 } else {
4148 AvailableSpace::MinContent
4149 };
4150
4151 let mut element = (renderer.render)(cx);
4152 let line_height = text_style.line_height_in_pixels(cx.rem_size());
4153 let size = element.layout_as_root(
4154 size(available_width, AvailableSpace::Definite(line_height)),
4155 cx,
4156 );
4157
4158 width += size.width;
4159 len += highlighted_chunk.text.len();
4160 fragments.push(LineFragment::Element {
4161 element: Some(element),
4162 size,
4163 len: highlighted_chunk.text.len(),
4164 });
4165 } else {
4166 for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
4167 if ix > 0 {
4168 let shaped_line = cx
4169 .text_system()
4170 .shape_line(line.clone().into(), font_size, &styles)
4171 .unwrap();
4172 width += shaped_line.width;
4173 len += shaped_line.len;
4174 fragments.push(LineFragment::Text(shaped_line));
4175 layouts.push(Self {
4176 width: mem::take(&mut width),
4177 len: mem::take(&mut len),
4178 fragments: mem::take(&mut fragments),
4179 invisibles: std::mem::take(&mut invisibles),
4180 font_size,
4181 });
4182
4183 line.clear();
4184 styles.clear();
4185 row += 1;
4186 line_exceeded_max_len = false;
4187 non_whitespace_added = false;
4188 if row == max_line_count {
4189 return layouts;
4190 }
4191 }
4192
4193 if !line_chunk.is_empty() && !line_exceeded_max_len {
4194 let text_style = if let Some(style) = highlighted_chunk.style {
4195 Cow::Owned(text_style.clone().highlight(style))
4196 } else {
4197 Cow::Borrowed(text_style)
4198 };
4199
4200 if line.len() + line_chunk.len() > max_line_len {
4201 let mut chunk_len = max_line_len - line.len();
4202 while !line_chunk.is_char_boundary(chunk_len) {
4203 chunk_len -= 1;
4204 }
4205 line_chunk = &line_chunk[..chunk_len];
4206 line_exceeded_max_len = true;
4207 }
4208
4209 styles.push(TextRun {
4210 len: line_chunk.len(),
4211 font: text_style.font(),
4212 color: text_style.color,
4213 background_color: text_style.background_color,
4214 underline: text_style.underline,
4215 strikethrough: text_style.strikethrough,
4216 });
4217
4218 if editor_mode == EditorMode::Full {
4219 // Line wrap pads its contents with fake whitespaces,
4220 // avoid printing them
4221 let inside_wrapped_string = line_number_layouts
4222 .get(row)
4223 .and_then(|layout| layout.as_ref())
4224 .is_none();
4225 if highlighted_chunk.is_tab {
4226 if non_whitespace_added || !inside_wrapped_string {
4227 invisibles.push(Invisible::Tab {
4228 line_start_offset: line.len(),
4229 line_end_offset: line.len() + line_chunk.len(),
4230 });
4231 }
4232 } else {
4233 invisibles.extend(
4234 line_chunk
4235 .bytes()
4236 .enumerate()
4237 .filter(|(_, line_byte)| {
4238 let is_whitespace =
4239 (*line_byte as char).is_whitespace();
4240 non_whitespace_added |= !is_whitespace;
4241 is_whitespace
4242 && (non_whitespace_added || !inside_wrapped_string)
4243 })
4244 .map(|(whitespace_index, _)| Invisible::Whitespace {
4245 line_offset: line.len() + whitespace_index,
4246 }),
4247 )
4248 }
4249 }
4250
4251 line.push_str(line_chunk);
4252 }
4253 }
4254 }
4255 }
4256
4257 layouts
4258 }
4259
4260 fn prepaint(
4261 &mut self,
4262 line_height: Pixels,
4263 scroll_pixel_position: gpui::Point<Pixels>,
4264 row: DisplayRow,
4265 content_origin: gpui::Point<Pixels>,
4266 line_elements: &mut SmallVec<[AnyElement; 1]>,
4267 cx: &mut WindowContext,
4268 ) {
4269 let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
4270 let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
4271 for fragment in &mut self.fragments {
4272 match fragment {
4273 LineFragment::Text(line) => {
4274 fragment_origin.x += line.width;
4275 }
4276 LineFragment::Element { element, size, .. } => {
4277 let mut element = element
4278 .take()
4279 .expect("you can't prepaint LineWithInvisibles twice");
4280
4281 // Center the element vertically within the line.
4282 let mut element_origin = fragment_origin;
4283 element_origin.y += (line_height - size.height) / 2.;
4284 element.prepaint_at(element_origin, cx);
4285 line_elements.push(element);
4286
4287 fragment_origin.x += size.width;
4288 }
4289 }
4290 }
4291 }
4292
4293 fn draw(
4294 &self,
4295 layout: &EditorLayout,
4296 row: DisplayRow,
4297 content_origin: gpui::Point<Pixels>,
4298 whitespace_setting: ShowWhitespaceSetting,
4299 selection_ranges: &[Range<DisplayPoint>],
4300 cx: &mut WindowContext,
4301 ) {
4302 let line_height = layout.position_map.line_height;
4303 let line_y = line_height
4304 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
4305
4306 let mut fragment_origin =
4307 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
4308
4309 for fragment in &self.fragments {
4310 match fragment {
4311 LineFragment::Text(line) => {
4312 line.paint(fragment_origin, line_height, cx).log_err();
4313 fragment_origin.x += line.width;
4314 }
4315 LineFragment::Element { size, .. } => {
4316 fragment_origin.x += size.width;
4317 }
4318 }
4319 }
4320
4321 self.draw_invisibles(
4322 &selection_ranges,
4323 layout,
4324 content_origin,
4325 line_y,
4326 row,
4327 line_height,
4328 whitespace_setting,
4329 cx,
4330 );
4331 }
4332
4333 #[allow(clippy::too_many_arguments)]
4334 fn draw_invisibles(
4335 &self,
4336 selection_ranges: &[Range<DisplayPoint>],
4337 layout: &EditorLayout,
4338 content_origin: gpui::Point<Pixels>,
4339 line_y: Pixels,
4340 row: DisplayRow,
4341 line_height: Pixels,
4342 whitespace_setting: ShowWhitespaceSetting,
4343 cx: &mut WindowContext,
4344 ) {
4345 let extract_whitespace_info = |invisible: &Invisible| {
4346 let (token_offset, token_end_offset, invisible_symbol) = match invisible {
4347 Invisible::Tab {
4348 line_start_offset,
4349 line_end_offset,
4350 } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
4351 Invisible::Whitespace { line_offset } => {
4352 (*line_offset, line_offset + 1, &layout.space_invisible)
4353 }
4354 };
4355
4356 let x_offset = self.x_for_index(token_offset);
4357 let invisible_offset =
4358 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
4359 let origin = content_origin
4360 + gpui::point(
4361 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
4362 line_y,
4363 );
4364
4365 (
4366 [token_offset, token_end_offset],
4367 Box::new(move |cx: &mut WindowContext| {
4368 invisible_symbol.paint(origin, line_height, cx).log_err();
4369 }),
4370 )
4371 };
4372
4373 let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
4374 match whitespace_setting {
4375 ShowWhitespaceSetting::None => return,
4376 ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(cx)),
4377 ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
4378 let invisible_point = DisplayPoint::new(row, start as u32);
4379 if !selection_ranges
4380 .iter()
4381 .any(|region| region.start <= invisible_point && invisible_point < region.end)
4382 {
4383 return;
4384 }
4385
4386 paint(cx);
4387 }),
4388
4389 // For a whitespace to be on a boundary, any of the following conditions need to be met:
4390 // - It is a tab
4391 // - It is adjacent to an edge (start or end)
4392 // - It is adjacent to a whitespace (left or right)
4393 ShowWhitespaceSetting::Boundary => {
4394 // We'll need to keep track of the last invisible we've seen and then check if we are adjacent to it for some of
4395 // the above cases.
4396 // Note: We zip in the original `invisibles` to check for tab equality
4397 let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut WindowContext)>)> = None;
4398 for (([start, end], paint), invisible) in
4399 invisible_iter.zip_eq(self.invisibles.iter())
4400 {
4401 let should_render = match (&last_seen, invisible) {
4402 (_, Invisible::Tab { .. }) => true,
4403 (Some((_, last_end, _)), _) => *last_end == start,
4404 _ => false,
4405 };
4406
4407 if should_render || start == 0 || end == self.len {
4408 paint(cx);
4409
4410 // Since we are scanning from the left, we will skip over the first available whitespace that is part
4411 // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
4412 if let Some((should_render_last, last_end, paint_last)) = last_seen {
4413 // Note that we need to make sure that the last one is actually adjacent
4414 if !should_render_last && last_end == start {
4415 paint_last(cx);
4416 }
4417 }
4418 }
4419
4420 // Manually render anything within a selection
4421 let invisible_point = DisplayPoint::new(row, start as u32);
4422 if selection_ranges.iter().any(|region| {
4423 region.start <= invisible_point && invisible_point < region.end
4424 }) {
4425 paint(cx);
4426 }
4427
4428 last_seen = Some((should_render, end, paint));
4429 }
4430 }
4431 };
4432 }
4433
4434 pub fn x_for_index(&self, index: usize) -> Pixels {
4435 let mut fragment_start_x = Pixels::ZERO;
4436 let mut fragment_start_index = 0;
4437
4438 for fragment in &self.fragments {
4439 match fragment {
4440 LineFragment::Text(shaped_line) => {
4441 let fragment_end_index = fragment_start_index + shaped_line.len;
4442 if index < fragment_end_index {
4443 return fragment_start_x
4444 + shaped_line.x_for_index(index - fragment_start_index);
4445 }
4446 fragment_start_x += shaped_line.width;
4447 fragment_start_index = fragment_end_index;
4448 }
4449 LineFragment::Element { len, size, .. } => {
4450 let fragment_end_index = fragment_start_index + len;
4451 if index < fragment_end_index {
4452 return fragment_start_x;
4453 }
4454 fragment_start_x += size.width;
4455 fragment_start_index = fragment_end_index;
4456 }
4457 }
4458 }
4459
4460 fragment_start_x
4461 }
4462
4463 pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
4464 let mut fragment_start_x = Pixels::ZERO;
4465 let mut fragment_start_index = 0;
4466
4467 for fragment in &self.fragments {
4468 match fragment {
4469 LineFragment::Text(shaped_line) => {
4470 let fragment_end_x = fragment_start_x + shaped_line.width;
4471 if x < fragment_end_x {
4472 return Some(
4473 fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
4474 );
4475 }
4476 fragment_start_x = fragment_end_x;
4477 fragment_start_index += shaped_line.len;
4478 }
4479 LineFragment::Element { len, size, .. } => {
4480 let fragment_end_x = fragment_start_x + size.width;
4481 if x < fragment_end_x {
4482 return Some(fragment_start_index);
4483 }
4484 fragment_start_index += len;
4485 fragment_start_x = fragment_end_x;
4486 }
4487 }
4488 }
4489
4490 None
4491 }
4492
4493 pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
4494 let mut fragment_start_index = 0;
4495
4496 for fragment in &self.fragments {
4497 match fragment {
4498 LineFragment::Text(shaped_line) => {
4499 let fragment_end_index = fragment_start_index + shaped_line.len;
4500 if index < fragment_end_index {
4501 return shaped_line.font_id_for_index(index - fragment_start_index);
4502 }
4503 fragment_start_index = fragment_end_index;
4504 }
4505 LineFragment::Element { len, .. } => {
4506 let fragment_end_index = fragment_start_index + len;
4507 if index < fragment_end_index {
4508 return None;
4509 }
4510 fragment_start_index = fragment_end_index;
4511 }
4512 }
4513 }
4514
4515 None
4516 }
4517}
4518
4519#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4520enum Invisible {
4521 /// A tab character
4522 ///
4523 /// A tab character is internally represented by spaces (configured by the user's tab width)
4524 /// aligned to the nearest column, so it's necessary to store the start and end offset for
4525 /// adjacency checks.
4526 Tab {
4527 line_start_offset: usize,
4528 line_end_offset: usize,
4529 },
4530 Whitespace {
4531 line_offset: usize,
4532 },
4533}
4534
4535impl EditorElement {
4536 /// Returns the rem size to use when rendering the [`EditorElement`].
4537 ///
4538 /// This allows UI elements to scale based on the `buffer_font_size`.
4539 fn rem_size(&self, cx: &WindowContext) -> Option<Pixels> {
4540 match self.editor.read(cx).mode {
4541 EditorMode::Full => {
4542 let buffer_font_size = self.style.text.font_size;
4543 match buffer_font_size {
4544 AbsoluteLength::Pixels(pixels) => {
4545 let rem_size_scale = {
4546 // Our default UI font size is 14px on a 16px base scale.
4547 // This means the default UI font size is 0.875rems.
4548 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
4549
4550 // We then determine the delta between a single rem and the default font
4551 // size scale.
4552 let default_font_size_delta = 1. - default_font_size_scale;
4553
4554 // Finally, we add this delta to 1rem to get the scale factor that
4555 // should be used to scale up the UI.
4556 1. + default_font_size_delta
4557 };
4558
4559 Some(pixels * rem_size_scale)
4560 }
4561 AbsoluteLength::Rems(rems) => {
4562 Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
4563 }
4564 }
4565 }
4566 // We currently use single-line and auto-height editors in UI contexts,
4567 // so we don't want to scale everything with the buffer font size, as it
4568 // ends up looking off.
4569 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => None,
4570 }
4571 }
4572}
4573
4574impl Element for EditorElement {
4575 type RequestLayoutState = ();
4576 type PrepaintState = EditorLayout;
4577
4578 fn id(&self) -> Option<ElementId> {
4579 None
4580 }
4581
4582 fn request_layout(
4583 &mut self,
4584 _: Option<&GlobalElementId>,
4585 cx: &mut WindowContext,
4586 ) -> (gpui::LayoutId, ()) {
4587 let rem_size = self.rem_size(cx);
4588 cx.with_rem_size(rem_size, |cx| {
4589 self.editor.update(cx, |editor, cx| {
4590 editor.set_style(self.style.clone(), cx);
4591
4592 let layout_id = match editor.mode {
4593 EditorMode::SingleLine { auto_width } => {
4594 let rem_size = cx.rem_size();
4595
4596 let height = self.style.text.line_height_in_pixels(rem_size);
4597 if auto_width {
4598 let editor_handle = cx.view().clone();
4599 let style = self.style.clone();
4600 cx.request_measured_layout(Style::default(), move |_, _, cx| {
4601 let editor_snapshot =
4602 editor_handle.update(cx, |editor, cx| editor.snapshot(cx));
4603 let line = Self::layout_lines(
4604 DisplayRow(0)..DisplayRow(1),
4605 &[],
4606 &editor_snapshot,
4607 &style,
4608 cx,
4609 )
4610 .pop()
4611 .unwrap();
4612
4613 let font_id = cx.text_system().resolve_font(&style.text.font());
4614 let font_size = style.text.font_size.to_pixels(cx.rem_size());
4615 let em_width = cx
4616 .text_system()
4617 .typographic_bounds(font_id, font_size, 'm')
4618 .unwrap()
4619 .size
4620 .width;
4621
4622 size(line.width + em_width, height)
4623 })
4624 } else {
4625 let mut style = Style::default();
4626 style.size.height = height.into();
4627 style.size.width = relative(1.).into();
4628 cx.request_layout(style, None)
4629 }
4630 }
4631 EditorMode::AutoHeight { max_lines } => {
4632 let editor_handle = cx.view().clone();
4633 let max_line_number_width =
4634 self.max_line_number_width(&editor.snapshot(cx), cx);
4635 cx.request_measured_layout(
4636 Style::default(),
4637 move |known_dimensions, available_space, cx| {
4638 editor_handle
4639 .update(cx, |editor, cx| {
4640 compute_auto_height_layout(
4641 editor,
4642 max_lines,
4643 max_line_number_width,
4644 known_dimensions,
4645 available_space.width,
4646 cx,
4647 )
4648 })
4649 .unwrap_or_default()
4650 },
4651 )
4652 }
4653 EditorMode::Full => {
4654 let mut style = Style::default();
4655 style.size.width = relative(1.).into();
4656 style.size.height = relative(1.).into();
4657 cx.request_layout(style, None)
4658 }
4659 };
4660
4661 (layout_id, ())
4662 })
4663 })
4664 }
4665
4666 fn prepaint(
4667 &mut self,
4668 _: Option<&GlobalElementId>,
4669 bounds: Bounds<Pixels>,
4670 _: &mut Self::RequestLayoutState,
4671 cx: &mut WindowContext,
4672 ) -> Self::PrepaintState {
4673 let text_style = TextStyleRefinement {
4674 font_size: Some(self.style.text.font_size),
4675 line_height: Some(self.style.text.line_height),
4676 ..Default::default()
4677 };
4678 cx.set_view_id(self.editor.entity_id());
4679
4680 let rem_size = self.rem_size(cx);
4681 cx.with_rem_size(rem_size, |cx| {
4682 cx.with_text_style(Some(text_style), |cx| {
4683 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
4684 let mut snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
4685 let style = self.style.clone();
4686
4687 let font_id = cx.text_system().resolve_font(&style.text.font());
4688 let font_size = style.text.font_size.to_pixels(cx.rem_size());
4689 let line_height = style.text.line_height_in_pixels(cx.rem_size());
4690 let em_width = cx
4691 .text_system()
4692 .typographic_bounds(font_id, font_size, 'm')
4693 .unwrap()
4694 .size
4695 .width;
4696 let em_advance = cx
4697 .text_system()
4698 .advance(font_id, font_size, 'm')
4699 .unwrap()
4700 .width;
4701
4702 let gutter_dimensions = snapshot.gutter_dimensions(
4703 font_id,
4704 font_size,
4705 em_width,
4706 self.max_line_number_width(&snapshot, cx),
4707 cx,
4708 );
4709 let text_width = bounds.size.width - gutter_dimensions.width;
4710
4711 let right_margin = if snapshot.mode == EditorMode::Full {
4712 EditorElement::SCROLLBAR_WIDTH
4713 } else {
4714 px(0.)
4715 };
4716 let overscroll = size(em_width + right_margin, px(0.));
4717
4718 snapshot = self.editor.update(cx, |editor, cx| {
4719 editor.last_bounds = Some(bounds);
4720 editor.gutter_dimensions = gutter_dimensions;
4721 editor.set_visible_line_count(bounds.size.height / line_height, cx);
4722
4723 let editor_width =
4724 text_width - gutter_dimensions.margin - overscroll.width - em_width;
4725 let wrap_width = match editor.soft_wrap_mode(cx) {
4726 SoftWrap::None => None,
4727 SoftWrap::PreferLine => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
4728 SoftWrap::EditorWidth => Some(editor_width),
4729 SoftWrap::Column(column) => {
4730 Some(editor_width.min(column as f32 * em_advance))
4731 }
4732 };
4733
4734 if editor.set_wrap_width(wrap_width, cx) {
4735 editor.snapshot(cx)
4736 } else {
4737 snapshot
4738 }
4739 });
4740
4741 let wrap_guides = self
4742 .editor
4743 .read(cx)
4744 .wrap_guides(cx)
4745 .iter()
4746 .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
4747 .collect::<SmallVec<[_; 2]>>();
4748
4749 let hitbox = cx.insert_hitbox(bounds, false);
4750 let gutter_hitbox = cx.insert_hitbox(
4751 Bounds {
4752 origin: bounds.origin,
4753 size: size(gutter_dimensions.width, bounds.size.height),
4754 },
4755 false,
4756 );
4757 let text_hitbox = cx.insert_hitbox(
4758 Bounds {
4759 origin: gutter_hitbox.upper_right(),
4760 size: size(text_width, bounds.size.height),
4761 },
4762 false,
4763 );
4764 // Offset the content_bounds from the text_bounds by the gutter margin (which
4765 // is roughly half a character wide) to make hit testing work more like how we want.
4766 let content_origin =
4767 text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
4768
4769 let height_in_lines = bounds.size.height / line_height;
4770 let max_row = snapshot.max_point().row().as_f32();
4771 let max_scroll_top = if matches!(snapshot.mode, EditorMode::AutoHeight { .. }) {
4772 (max_row - height_in_lines + 1.).max(0.)
4773 } else {
4774 let settings = EditorSettings::get_global(cx);
4775 match settings.scroll_beyond_last_line {
4776 ScrollBeyondLastLine::OnePage => max_row,
4777 ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
4778 ScrollBeyondLastLine::VerticalScrollMargin => {
4779 (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
4780 .max(0.)
4781 }
4782 }
4783 };
4784
4785 let mut autoscroll_containing_element = false;
4786 let mut autoscroll_horizontally = false;
4787 self.editor.update(cx, |editor, cx| {
4788 autoscroll_containing_element =
4789 editor.autoscroll_requested() || editor.has_pending_selection();
4790 autoscroll_horizontally =
4791 editor.autoscroll_vertically(bounds, line_height, max_scroll_top, cx);
4792 snapshot = editor.snapshot(cx);
4793 });
4794
4795 let mut scroll_position = snapshot.scroll_position();
4796 // The scroll position is a fractional point, the whole number of which represents
4797 // the top of the window in terms of display rows.
4798 let start_row = DisplayRow(scroll_position.y as u32);
4799 let max_row = snapshot.max_point().row();
4800 let end_row = cmp::min(
4801 (scroll_position.y + height_in_lines).ceil() as u32,
4802 max_row.next_row().0,
4803 );
4804 let end_row = DisplayRow(end_row);
4805
4806 let buffer_rows = snapshot
4807 .buffer_rows(start_row)
4808 .take((start_row..end_row).len())
4809 .collect::<Vec<_>>();
4810
4811 let start_anchor = if start_row == Default::default() {
4812 Anchor::min()
4813 } else {
4814 snapshot.buffer_snapshot.anchor_before(
4815 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
4816 )
4817 };
4818 let end_anchor = if end_row > max_row {
4819 Anchor::max()
4820 } else {
4821 snapshot.buffer_snapshot.anchor_before(
4822 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
4823 )
4824 };
4825
4826 let highlighted_rows = self
4827 .editor
4828 .update(cx, |editor, cx| editor.highlighted_display_rows(cx));
4829 let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
4830 start_anchor..end_anchor,
4831 &snapshot.display_snapshot,
4832 cx.theme().colors(),
4833 );
4834 let highlighted_gutter_ranges =
4835 self.editor.read(cx).gutter_highlights_in_range(
4836 start_anchor..end_anchor,
4837 &snapshot.display_snapshot,
4838 cx,
4839 );
4840
4841 let redacted_ranges = self.editor.read(cx).redacted_ranges(
4842 start_anchor..end_anchor,
4843 &snapshot.display_snapshot,
4844 cx,
4845 );
4846
4847 let (selections, active_rows, newest_selection_head) = self.layout_selections(
4848 start_anchor,
4849 end_anchor,
4850 &snapshot,
4851 start_row,
4852 end_row,
4853 cx,
4854 );
4855
4856 let line_numbers = self.layout_line_numbers(
4857 start_row..end_row,
4858 buffer_rows.iter().copied(),
4859 &active_rows,
4860 newest_selection_head,
4861 &snapshot,
4862 cx,
4863 );
4864
4865 let mut gutter_fold_toggles =
4866 cx.with_element_namespace("gutter_fold_toggles", |cx| {
4867 self.layout_gutter_fold_toggles(
4868 start_row..end_row,
4869 buffer_rows.iter().copied(),
4870 &active_rows,
4871 &snapshot,
4872 cx,
4873 )
4874 });
4875 let crease_trailers = cx.with_element_namespace("crease_trailers", |cx| {
4876 self.layout_crease_trailers(buffer_rows.iter().copied(), &snapshot, cx)
4877 });
4878
4879 let display_hunks = self.layout_git_gutters(
4880 line_height,
4881 &gutter_hitbox,
4882 start_row..end_row,
4883 &snapshot,
4884 cx,
4885 );
4886
4887 let mut max_visible_line_width = Pixels::ZERO;
4888 let mut line_layouts = Self::layout_lines(
4889 start_row..end_row,
4890 &line_numbers,
4891 &snapshot,
4892 &self.style,
4893 cx,
4894 );
4895 for line_with_invisibles in &line_layouts {
4896 if line_with_invisibles.width > max_visible_line_width {
4897 max_visible_line_width = line_with_invisibles.width;
4898 }
4899 }
4900
4901 let longest_line_width =
4902 layout_line(snapshot.longest_row(), &snapshot, &style, cx).width;
4903 let mut scroll_width =
4904 longest_line_width.max(max_visible_line_width) + overscroll.width;
4905
4906 let mut blocks = cx.with_element_namespace("blocks", |cx| {
4907 self.build_blocks(
4908 start_row..end_row,
4909 &snapshot,
4910 &hitbox,
4911 &text_hitbox,
4912 &mut scroll_width,
4913 &gutter_dimensions,
4914 em_width,
4915 gutter_dimensions.full_width(),
4916 line_height,
4917 &line_layouts,
4918 cx,
4919 )
4920 });
4921
4922 let start_buffer_row =
4923 MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
4924 let end_buffer_row =
4925 MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
4926
4927 let scroll_max = point(
4928 ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
4929 max_row.as_f32(),
4930 );
4931
4932 self.editor.update(cx, |editor, cx| {
4933 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
4934
4935 let autoscrolled = if autoscroll_horizontally {
4936 editor.autoscroll_horizontally(
4937 start_row,
4938 text_hitbox.size.width,
4939 scroll_width,
4940 em_width,
4941 &line_layouts,
4942 cx,
4943 )
4944 } else {
4945 false
4946 };
4947
4948 if clamped || autoscrolled {
4949 snapshot = editor.snapshot(cx);
4950 scroll_position = snapshot.scroll_position();
4951 }
4952 });
4953
4954 let scroll_pixel_position = point(
4955 scroll_position.x * em_width,
4956 scroll_position.y * line_height,
4957 );
4958
4959 let indent_guides = self.layout_indent_guides(
4960 content_origin,
4961 text_hitbox.origin,
4962 start_buffer_row..end_buffer_row,
4963 scroll_pixel_position,
4964 line_height,
4965 &snapshot,
4966 cx,
4967 );
4968
4969 let crease_trailers = cx.with_element_namespace("crease_trailers", |cx| {
4970 self.prepaint_crease_trailers(
4971 crease_trailers,
4972 &line_layouts,
4973 line_height,
4974 content_origin,
4975 scroll_pixel_position,
4976 em_width,
4977 cx,
4978 )
4979 });
4980
4981 let mut inline_blame = None;
4982 if let Some(newest_selection_head) = newest_selection_head {
4983 let display_row = newest_selection_head.row();
4984 if (start_row..end_row).contains(&display_row) {
4985 let line_ix = display_row.minus(start_row) as usize;
4986 let line_layout = &line_layouts[line_ix];
4987 let crease_trailer_layout = crease_trailers[line_ix].as_ref();
4988 inline_blame = self.layout_inline_blame(
4989 display_row,
4990 &snapshot.display_snapshot,
4991 line_layout,
4992 crease_trailer_layout,
4993 em_width,
4994 content_origin,
4995 scroll_pixel_position,
4996 line_height,
4997 cx,
4998 );
4999 }
5000 }
5001
5002 let blamed_display_rows = self.layout_blame_entries(
5003 buffer_rows.into_iter(),
5004 em_width,
5005 scroll_position,
5006 line_height,
5007 &gutter_hitbox,
5008 gutter_dimensions.git_blame_entries_width,
5009 cx,
5010 );
5011
5012 let scroll_max = point(
5013 ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
5014 max_scroll_top,
5015 );
5016
5017 self.editor.update(cx, |editor, cx| {
5018 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
5019
5020 let autoscrolled = if autoscroll_horizontally {
5021 editor.autoscroll_horizontally(
5022 start_row,
5023 text_hitbox.size.width,
5024 scroll_width,
5025 em_width,
5026 &line_layouts,
5027 cx,
5028 )
5029 } else {
5030 false
5031 };
5032
5033 if clamped || autoscrolled {
5034 snapshot = editor.snapshot(cx);
5035 scroll_position = snapshot.scroll_position();
5036 }
5037 });
5038
5039 let line_elements = self.prepaint_lines(
5040 start_row,
5041 &mut line_layouts,
5042 line_height,
5043 scroll_pixel_position,
5044 content_origin,
5045 cx,
5046 );
5047
5048 cx.with_element_namespace("blocks", |cx| {
5049 self.layout_blocks(
5050 &mut blocks,
5051 &hitbox,
5052 line_height,
5053 scroll_pixel_position,
5054 cx,
5055 );
5056 });
5057
5058 let cursors = self.collect_cursors(&snapshot, cx);
5059 let visible_row_range = start_row..end_row;
5060 let non_visible_cursors = cursors
5061 .iter()
5062 .any(move |c| !visible_row_range.contains(&c.0.row()));
5063
5064 let visible_cursors = self.layout_visible_cursors(
5065 &snapshot,
5066 &selections,
5067 start_row..end_row,
5068 &line_layouts,
5069 &text_hitbox,
5070 content_origin,
5071 scroll_position,
5072 scroll_pixel_position,
5073 line_height,
5074 em_width,
5075 autoscroll_containing_element,
5076 cx,
5077 );
5078
5079 let scrollbar_layout = self.layout_scrollbar(
5080 &snapshot,
5081 bounds,
5082 scroll_position,
5083 height_in_lines,
5084 non_visible_cursors,
5085 cx,
5086 );
5087
5088 let gutter_settings = EditorSettings::get_global(cx).gutter;
5089
5090 let mut _context_menu_visible = false;
5091 let mut code_actions_indicator = None;
5092 if let Some(newest_selection_head) = newest_selection_head {
5093 if (start_row..end_row).contains(&newest_selection_head.row()) {
5094 _context_menu_visible = self.layout_context_menu(
5095 line_height,
5096 &hitbox,
5097 &text_hitbox,
5098 content_origin,
5099 start_row,
5100 scroll_pixel_position,
5101 &line_layouts,
5102 newest_selection_head,
5103 gutter_dimensions.width - gutter_dimensions.left_padding,
5104 cx,
5105 );
5106
5107 let show_code_actions = snapshot
5108 .show_code_actions
5109 .unwrap_or_else(|| gutter_settings.code_actions);
5110 if show_code_actions {
5111 let newest_selection_point =
5112 newest_selection_head.to_point(&snapshot.display_snapshot);
5113 let buffer = snapshot.buffer_snapshot.buffer_line_for_row(
5114 MultiBufferRow(newest_selection_point.row),
5115 );
5116 if let Some((buffer, range)) = buffer {
5117 let buffer_id = buffer.remote_id();
5118 let row = range.start.row;
5119 let has_test_indicator =
5120 self.editor.read(cx).tasks.contains_key(&(buffer_id, row));
5121
5122 if !has_test_indicator {
5123 code_actions_indicator = self
5124 .layout_code_actions_indicator(
5125 line_height,
5126 newest_selection_head,
5127 scroll_pixel_position,
5128 &gutter_dimensions,
5129 &gutter_hitbox,
5130 cx,
5131 );
5132 }
5133 }
5134 }
5135 }
5136 }
5137
5138 let test_indicators = if gutter_settings.runnables {
5139 self.layout_run_indicators(
5140 line_height,
5141 scroll_pixel_position,
5142 &gutter_dimensions,
5143 &gutter_hitbox,
5144 &snapshot,
5145 cx,
5146 )
5147 } else {
5148 vec![]
5149 };
5150
5151 self.layout_signature_help(
5152 &hitbox,
5153 content_origin,
5154 scroll_pixel_position,
5155 newest_selection_head,
5156 start_row,
5157 &line_layouts,
5158 line_height,
5159 em_width,
5160 cx,
5161 );
5162
5163 if !cx.has_active_drag() {
5164 self.layout_hover_popovers(
5165 &snapshot,
5166 &hitbox,
5167 &text_hitbox,
5168 start_row..end_row,
5169 content_origin,
5170 scroll_pixel_position,
5171 &line_layouts,
5172 line_height,
5173 em_width,
5174 cx,
5175 );
5176 }
5177
5178 let mouse_context_menu = self.layout_mouse_context_menu(cx);
5179
5180 cx.with_element_namespace("gutter_fold_toggles", |cx| {
5181 self.prepaint_gutter_fold_toggles(
5182 &mut gutter_fold_toggles,
5183 line_height,
5184 &gutter_dimensions,
5185 gutter_settings,
5186 scroll_pixel_position,
5187 &gutter_hitbox,
5188 cx,
5189 )
5190 });
5191
5192 let invisible_symbol_font_size = font_size / 2.;
5193 let tab_invisible = cx
5194 .text_system()
5195 .shape_line(
5196 "→".into(),
5197 invisible_symbol_font_size,
5198 &[TextRun {
5199 len: "→".len(),
5200 font: self.style.text.font(),
5201 color: cx.theme().colors().editor_invisible,
5202 background_color: None,
5203 underline: None,
5204 strikethrough: None,
5205 }],
5206 )
5207 .unwrap();
5208 let space_invisible = cx
5209 .text_system()
5210 .shape_line(
5211 "•".into(),
5212 invisible_symbol_font_size,
5213 &[TextRun {
5214 len: "•".len(),
5215 font: self.style.text.font(),
5216 color: cx.theme().colors().editor_invisible,
5217 background_color: None,
5218 underline: None,
5219 strikethrough: None,
5220 }],
5221 )
5222 .unwrap();
5223
5224 EditorLayout {
5225 mode: snapshot.mode,
5226 position_map: Arc::new(PositionMap {
5227 size: bounds.size,
5228 scroll_pixel_position,
5229 scroll_max,
5230 line_layouts,
5231 line_height,
5232 em_width,
5233 em_advance,
5234 snapshot,
5235 }),
5236 visible_display_row_range: start_row..end_row,
5237 wrap_guides,
5238 indent_guides,
5239 hitbox,
5240 text_hitbox,
5241 gutter_hitbox,
5242 gutter_dimensions,
5243 content_origin,
5244 scrollbar_layout,
5245 active_rows,
5246 highlighted_rows,
5247 highlighted_ranges,
5248 highlighted_gutter_ranges,
5249 redacted_ranges,
5250 line_elements,
5251 line_numbers,
5252 display_hunks,
5253 blamed_display_rows,
5254 inline_blame,
5255 blocks,
5256 cursors,
5257 visible_cursors,
5258 selections,
5259 mouse_context_menu,
5260 test_indicators,
5261 code_actions_indicator,
5262 gutter_fold_toggles,
5263 crease_trailers,
5264 tab_invisible,
5265 space_invisible,
5266 }
5267 })
5268 })
5269 })
5270 }
5271
5272 fn paint(
5273 &mut self,
5274 _: Option<&GlobalElementId>,
5275 bounds: Bounds<gpui::Pixels>,
5276 _: &mut Self::RequestLayoutState,
5277 layout: &mut Self::PrepaintState,
5278 cx: &mut WindowContext,
5279 ) {
5280 let focus_handle = self.editor.focus_handle(cx);
5281 let key_context = self.editor.read(cx).key_context(cx);
5282 cx.set_focus_handle(&focus_handle);
5283 cx.set_key_context(key_context);
5284 cx.handle_input(
5285 &focus_handle,
5286 ElementInputHandler::new(bounds, self.editor.clone()),
5287 );
5288 self.register_actions(cx);
5289 self.register_key_listeners(cx, layout);
5290
5291 let text_style = TextStyleRefinement {
5292 font_size: Some(self.style.text.font_size),
5293 line_height: Some(self.style.text.line_height),
5294 ..Default::default()
5295 };
5296 let mouse_position = cx.mouse_position();
5297 let hovered_hunk = layout
5298 .display_hunks
5299 .iter()
5300 .find_map(|(hunk, hunk_hitbox)| match hunk {
5301 DisplayDiffHunk::Folded { .. } => None,
5302 DisplayDiffHunk::Unfolded {
5303 diff_base_byte_range,
5304 multi_buffer_range,
5305 status,
5306 ..
5307 } => {
5308 if hunk_hitbox
5309 .as_ref()
5310 .map(|hitbox| hitbox.contains(&mouse_position))
5311 .unwrap_or(false)
5312 {
5313 Some(HunkToExpand {
5314 status: *status,
5315 multi_buffer_range: multi_buffer_range.clone(),
5316 diff_base_byte_range: diff_base_byte_range.clone(),
5317 })
5318 } else {
5319 None
5320 }
5321 }
5322 });
5323 let rem_size = self.rem_size(cx);
5324 cx.with_rem_size(rem_size, |cx| {
5325 cx.with_text_style(Some(text_style), |cx| {
5326 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
5327 self.paint_mouse_listeners(layout, hovered_hunk, cx);
5328 self.paint_background(layout, cx);
5329 self.paint_indent_guides(layout, cx);
5330
5331 if layout.gutter_hitbox.size.width > Pixels::ZERO {
5332 self.paint_blamed_display_rows(layout, cx);
5333 self.paint_line_numbers(layout, cx);
5334 }
5335
5336 self.paint_text(layout, cx);
5337
5338 if !layout.blocks.is_empty() {
5339 cx.with_element_namespace("blocks", |cx| {
5340 self.paint_blocks(layout, cx);
5341 });
5342 }
5343
5344 if layout.gutter_hitbox.size.width > Pixels::ZERO {
5345 self.paint_gutter_highlights(layout, cx);
5346 self.paint_gutter_indicators(layout, cx);
5347 }
5348
5349 self.paint_scrollbar(layout, cx);
5350 self.paint_mouse_context_menu(layout, cx);
5351 });
5352 })
5353 })
5354 }
5355}
5356
5357impl IntoElement for EditorElement {
5358 type Element = Self;
5359
5360 fn into_element(self) -> Self::Element {
5361 self
5362 }
5363}
5364
5365pub struct EditorLayout {
5366 position_map: Arc<PositionMap>,
5367 hitbox: Hitbox,
5368 text_hitbox: Hitbox,
5369 gutter_hitbox: Hitbox,
5370 gutter_dimensions: GutterDimensions,
5371 content_origin: gpui::Point<Pixels>,
5372 scrollbar_layout: Option<ScrollbarLayout>,
5373 mode: EditorMode,
5374 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
5375 indent_guides: Option<Vec<IndentGuideLayout>>,
5376 visible_display_row_range: Range<DisplayRow>,
5377 active_rows: BTreeMap<DisplayRow, bool>,
5378 highlighted_rows: BTreeMap<DisplayRow, Hsla>,
5379 line_elements: SmallVec<[AnyElement; 1]>,
5380 line_numbers: Vec<Option<ShapedLine>>,
5381 display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
5382 blamed_display_rows: Option<Vec<AnyElement>>,
5383 inline_blame: Option<AnyElement>,
5384 blocks: Vec<BlockLayout>,
5385 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
5386 highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
5387 redacted_ranges: Vec<Range<DisplayPoint>>,
5388 cursors: Vec<(DisplayPoint, Hsla)>,
5389 visible_cursors: Vec<CursorLayout>,
5390 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
5391 code_actions_indicator: Option<AnyElement>,
5392 test_indicators: Vec<AnyElement>,
5393 gutter_fold_toggles: Vec<Option<AnyElement>>,
5394 crease_trailers: Vec<Option<CreaseTrailerLayout>>,
5395 mouse_context_menu: Option<AnyElement>,
5396 tab_invisible: ShapedLine,
5397 space_invisible: ShapedLine,
5398}
5399
5400impl EditorLayout {
5401 fn line_end_overshoot(&self) -> Pixels {
5402 0.15 * self.position_map.line_height
5403 }
5404}
5405
5406struct ColoredRange<T> {
5407 start: T,
5408 end: T,
5409 color: Hsla,
5410}
5411
5412#[derive(Clone)]
5413struct ScrollbarLayout {
5414 hitbox: Hitbox,
5415 visible_row_range: Range<f32>,
5416 visible: bool,
5417 row_height: Pixels,
5418 thumb_height: Pixels,
5419}
5420
5421impl ScrollbarLayout {
5422 const BORDER_WIDTH: Pixels = px(1.0);
5423 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
5424 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
5425 const MIN_THUMB_HEIGHT: Pixels = px(20.0);
5426
5427 fn thumb_bounds(&self) -> Bounds<Pixels> {
5428 let thumb_top = self.y_for_row(self.visible_row_range.start);
5429 let thumb_bottom = thumb_top + self.thumb_height;
5430 Bounds::from_corners(
5431 point(self.hitbox.left(), thumb_top),
5432 point(self.hitbox.right(), thumb_bottom),
5433 )
5434 }
5435
5436 fn y_for_row(&self, row: f32) -> Pixels {
5437 self.hitbox.top() + row * self.row_height
5438 }
5439
5440 fn marker_quads_for_ranges(
5441 &self,
5442 row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
5443 column: Option<usize>,
5444 ) -> Vec<PaintQuad> {
5445 struct MinMax {
5446 min: Pixels,
5447 max: Pixels,
5448 }
5449 let (x_range, height_limit) = if let Some(column) = column {
5450 let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
5451 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
5452 let end = start + column_width;
5453 (
5454 Range { start, end },
5455 MinMax {
5456 min: Self::MIN_MARKER_HEIGHT,
5457 max: px(f32::MAX),
5458 },
5459 )
5460 } else {
5461 (
5462 Range {
5463 start: Self::BORDER_WIDTH,
5464 end: self.hitbox.size.width,
5465 },
5466 MinMax {
5467 min: Self::LINE_MARKER_HEIGHT,
5468 max: Self::LINE_MARKER_HEIGHT,
5469 },
5470 )
5471 };
5472
5473 let row_to_y = |row: DisplayRow| row.as_f32() * self.row_height;
5474 let mut pixel_ranges = row_ranges
5475 .into_iter()
5476 .map(|range| {
5477 let start_y = row_to_y(range.start);
5478 let end_y = row_to_y(range.end)
5479 + self.row_height.max(height_limit.min).min(height_limit.max);
5480 ColoredRange {
5481 start: start_y,
5482 end: end_y,
5483 color: range.color,
5484 }
5485 })
5486 .peekable();
5487
5488 let mut quads = Vec::new();
5489 while let Some(mut pixel_range) = pixel_ranges.next() {
5490 while let Some(next_pixel_range) = pixel_ranges.peek() {
5491 if pixel_range.end >= next_pixel_range.start - px(1.0)
5492 && pixel_range.color == next_pixel_range.color
5493 {
5494 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
5495 pixel_ranges.next();
5496 } else {
5497 break;
5498 }
5499 }
5500
5501 let bounds = Bounds::from_corners(
5502 point(x_range.start, pixel_range.start),
5503 point(x_range.end, pixel_range.end),
5504 );
5505 quads.push(quad(
5506 bounds,
5507 Corners::default(),
5508 pixel_range.color,
5509 Edges::default(),
5510 Hsla::transparent_black(),
5511 ));
5512 }
5513
5514 quads
5515 }
5516}
5517
5518struct CreaseTrailerLayout {
5519 element: AnyElement,
5520 bounds: Bounds<Pixels>,
5521}
5522
5523struct PositionMap {
5524 size: Size<Pixels>,
5525 line_height: Pixels,
5526 scroll_pixel_position: gpui::Point<Pixels>,
5527 scroll_max: gpui::Point<f32>,
5528 em_width: Pixels,
5529 em_advance: Pixels,
5530 line_layouts: Vec<LineWithInvisibles>,
5531 snapshot: EditorSnapshot,
5532}
5533
5534#[derive(Debug, Copy, Clone)]
5535pub struct PointForPosition {
5536 pub previous_valid: DisplayPoint,
5537 pub next_valid: DisplayPoint,
5538 pub exact_unclipped: DisplayPoint,
5539 pub column_overshoot_after_line_end: u32,
5540}
5541
5542impl PointForPosition {
5543 pub fn as_valid(&self) -> Option<DisplayPoint> {
5544 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
5545 Some(self.previous_valid)
5546 } else {
5547 None
5548 }
5549 }
5550}
5551
5552impl PositionMap {
5553 fn point_for_position(
5554 &self,
5555 text_bounds: Bounds<Pixels>,
5556 position: gpui::Point<Pixels>,
5557 ) -> PointForPosition {
5558 let scroll_position = self.snapshot.scroll_position();
5559 let position = position - text_bounds.origin;
5560 let y = position.y.max(px(0.)).min(self.size.height);
5561 let x = position.x + (scroll_position.x * self.em_width);
5562 let row = ((y / self.line_height) + scroll_position.y) as u32;
5563
5564 let (column, x_overshoot_after_line_end) = if let Some(line) = self
5565 .line_layouts
5566 .get(row as usize - scroll_position.y as usize)
5567 {
5568 if let Some(ix) = line.index_for_x(x) {
5569 (ix as u32, px(0.))
5570 } else {
5571 (line.len as u32, px(0.).max(x - line.width))
5572 }
5573 } else {
5574 (0, x)
5575 };
5576
5577 let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
5578 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
5579 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
5580
5581 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
5582 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
5583 PointForPosition {
5584 previous_valid,
5585 next_valid,
5586 exact_unclipped,
5587 column_overshoot_after_line_end,
5588 }
5589 }
5590}
5591
5592struct BlockLayout {
5593 row: DisplayRow,
5594 element: AnyElement,
5595 available_space: Size<AvailableSpace>,
5596 style: BlockStyle,
5597}
5598
5599fn layout_line(
5600 row: DisplayRow,
5601 snapshot: &EditorSnapshot,
5602 style: &EditorStyle,
5603 cx: &mut WindowContext,
5604) -> LineWithInvisibles {
5605 let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
5606 LineWithInvisibles::from_chunks(chunks, &style.text, MAX_LINE_LEN, 1, &[], snapshot.mode, cx)
5607 .pop()
5608 .unwrap()
5609}
5610
5611#[derive(Debug)]
5612pub struct IndentGuideLayout {
5613 origin: gpui::Point<Pixels>,
5614 length: Pixels,
5615 single_indent_width: Pixels,
5616 depth: u32,
5617 active: bool,
5618 settings: IndentGuideSettings,
5619}
5620
5621pub struct CursorLayout {
5622 origin: gpui::Point<Pixels>,
5623 block_width: Pixels,
5624 line_height: Pixels,
5625 color: Hsla,
5626 shape: CursorShape,
5627 block_text: Option<ShapedLine>,
5628 cursor_name: Option<AnyElement>,
5629}
5630
5631#[derive(Debug)]
5632pub struct CursorName {
5633 string: SharedString,
5634 color: Hsla,
5635 is_top_row: bool,
5636}
5637
5638impl CursorLayout {
5639 pub fn new(
5640 origin: gpui::Point<Pixels>,
5641 block_width: Pixels,
5642 line_height: Pixels,
5643 color: Hsla,
5644 shape: CursorShape,
5645 block_text: Option<ShapedLine>,
5646 ) -> CursorLayout {
5647 CursorLayout {
5648 origin,
5649 block_width,
5650 line_height,
5651 color,
5652 shape,
5653 block_text,
5654 cursor_name: None,
5655 }
5656 }
5657
5658 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
5659 Bounds {
5660 origin: self.origin + origin,
5661 size: size(self.block_width, self.line_height),
5662 }
5663 }
5664
5665 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
5666 match self.shape {
5667 CursorShape::Bar => Bounds {
5668 origin: self.origin + origin,
5669 size: size(px(2.0), self.line_height),
5670 },
5671 CursorShape::Block | CursorShape::Hollow => Bounds {
5672 origin: self.origin + origin,
5673 size: size(self.block_width, self.line_height),
5674 },
5675 CursorShape::Underscore => Bounds {
5676 origin: self.origin
5677 + origin
5678 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
5679 size: size(self.block_width, px(2.0)),
5680 },
5681 }
5682 }
5683
5684 pub fn layout(
5685 &mut self,
5686 origin: gpui::Point<Pixels>,
5687 cursor_name: Option<CursorName>,
5688 cx: &mut WindowContext,
5689 ) {
5690 if let Some(cursor_name) = cursor_name {
5691 let bounds = self.bounds(origin);
5692 let text_size = self.line_height / 1.5;
5693
5694 let name_origin = if cursor_name.is_top_row {
5695 point(bounds.right() - px(1.), bounds.top())
5696 } else {
5697 point(bounds.left(), bounds.top() - text_size / 2. - px(1.))
5698 };
5699 let mut name_element = div()
5700 .bg(self.color)
5701 .text_size(text_size)
5702 .px_0p5()
5703 .line_height(text_size + px(2.))
5704 .text_color(cursor_name.color)
5705 .child(cursor_name.string.clone())
5706 .into_any_element();
5707
5708 name_element.prepaint_as_root(
5709 name_origin,
5710 size(AvailableSpace::MinContent, AvailableSpace::MinContent),
5711 cx,
5712 );
5713
5714 self.cursor_name = Some(name_element);
5715 }
5716 }
5717
5718 pub fn paint(&mut self, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
5719 let bounds = self.bounds(origin);
5720
5721 //Draw background or border quad
5722 let cursor = if matches!(self.shape, CursorShape::Hollow) {
5723 outline(bounds, self.color)
5724 } else {
5725 fill(bounds, self.color)
5726 };
5727
5728 if let Some(name) = &mut self.cursor_name {
5729 name.paint(cx);
5730 }
5731
5732 cx.paint_quad(cursor);
5733
5734 if let Some(block_text) = &self.block_text {
5735 block_text
5736 .paint(self.origin + origin, self.line_height, cx)
5737 .log_err();
5738 }
5739 }
5740
5741 pub fn shape(&self) -> CursorShape {
5742 self.shape
5743 }
5744}
5745
5746#[derive(Debug)]
5747pub struct HighlightedRange {
5748 pub start_y: Pixels,
5749 pub line_height: Pixels,
5750 pub lines: Vec<HighlightedRangeLine>,
5751 pub color: Hsla,
5752 pub corner_radius: Pixels,
5753}
5754
5755#[derive(Debug)]
5756pub struct HighlightedRangeLine {
5757 pub start_x: Pixels,
5758 pub end_x: Pixels,
5759}
5760
5761impl HighlightedRange {
5762 pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut WindowContext) {
5763 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
5764 self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
5765 self.paint_lines(
5766 self.start_y + self.line_height,
5767 &self.lines[1..],
5768 bounds,
5769 cx,
5770 );
5771 } else {
5772 self.paint_lines(self.start_y, &self.lines, bounds, cx);
5773 }
5774 }
5775
5776 fn paint_lines(
5777 &self,
5778 start_y: Pixels,
5779 lines: &[HighlightedRangeLine],
5780 _bounds: Bounds<Pixels>,
5781 cx: &mut WindowContext,
5782 ) {
5783 if lines.is_empty() {
5784 return;
5785 }
5786
5787 let first_line = lines.first().unwrap();
5788 let last_line = lines.last().unwrap();
5789
5790 let first_top_left = point(first_line.start_x, start_y);
5791 let first_top_right = point(first_line.end_x, start_y);
5792
5793 let curve_height = point(Pixels::ZERO, self.corner_radius);
5794 let curve_width = |start_x: Pixels, end_x: Pixels| {
5795 let max = (end_x - start_x) / 2.;
5796 let width = if max < self.corner_radius {
5797 max
5798 } else {
5799 self.corner_radius
5800 };
5801
5802 point(width, Pixels::ZERO)
5803 };
5804
5805 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
5806 let mut path = gpui::Path::new(first_top_right - top_curve_width);
5807 path.curve_to(first_top_right + curve_height, first_top_right);
5808
5809 let mut iter = lines.iter().enumerate().peekable();
5810 while let Some((ix, line)) = iter.next() {
5811 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
5812
5813 if let Some((_, next_line)) = iter.peek() {
5814 let next_top_right = point(next_line.end_x, bottom_right.y);
5815
5816 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
5817 Ordering::Equal => {
5818 path.line_to(bottom_right);
5819 }
5820 Ordering::Less => {
5821 let curve_width = curve_width(next_top_right.x, bottom_right.x);
5822 path.line_to(bottom_right - curve_height);
5823 if self.corner_radius > Pixels::ZERO {
5824 path.curve_to(bottom_right - curve_width, bottom_right);
5825 }
5826 path.line_to(next_top_right + curve_width);
5827 if self.corner_radius > Pixels::ZERO {
5828 path.curve_to(next_top_right + curve_height, next_top_right);
5829 }
5830 }
5831 Ordering::Greater => {
5832 let curve_width = curve_width(bottom_right.x, next_top_right.x);
5833 path.line_to(bottom_right - curve_height);
5834 if self.corner_radius > Pixels::ZERO {
5835 path.curve_to(bottom_right + curve_width, bottom_right);
5836 }
5837 path.line_to(next_top_right - curve_width);
5838 if self.corner_radius > Pixels::ZERO {
5839 path.curve_to(next_top_right + curve_height, next_top_right);
5840 }
5841 }
5842 }
5843 } else {
5844 let curve_width = curve_width(line.start_x, line.end_x);
5845 path.line_to(bottom_right - curve_height);
5846 if self.corner_radius > Pixels::ZERO {
5847 path.curve_to(bottom_right - curve_width, bottom_right);
5848 }
5849
5850 let bottom_left = point(line.start_x, bottom_right.y);
5851 path.line_to(bottom_left + curve_width);
5852 if self.corner_radius > Pixels::ZERO {
5853 path.curve_to(bottom_left - curve_height, bottom_left);
5854 }
5855 }
5856 }
5857
5858 if first_line.start_x > last_line.start_x {
5859 let curve_width = curve_width(last_line.start_x, first_line.start_x);
5860 let second_top_left = point(last_line.start_x, start_y + self.line_height);
5861 path.line_to(second_top_left + curve_height);
5862 if self.corner_radius > Pixels::ZERO {
5863 path.curve_to(second_top_left + curve_width, second_top_left);
5864 }
5865 let first_bottom_left = point(first_line.start_x, second_top_left.y);
5866 path.line_to(first_bottom_left - curve_width);
5867 if self.corner_radius > Pixels::ZERO {
5868 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
5869 }
5870 }
5871
5872 path.line_to(first_top_left + curve_height);
5873 if self.corner_radius > Pixels::ZERO {
5874 path.curve_to(first_top_left + top_curve_width, first_top_left);
5875 }
5876 path.line_to(first_top_right - top_curve_width);
5877
5878 cx.paint_path(path, self.color);
5879 }
5880}
5881
5882pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
5883 (delta.pow(1.5) / 100.0).into()
5884}
5885
5886fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
5887 (delta.pow(1.2) / 300.0).into()
5888}
5889
5890#[cfg(test)]
5891mod tests {
5892 use super::*;
5893 use crate::{
5894 display_map::{BlockDisposition, BlockProperties},
5895 editor_tests::{init_test, update_test_language_settings},
5896 Editor, MultiBuffer,
5897 };
5898 use gpui::{TestAppContext, VisualTestContext};
5899 use language::language_settings;
5900 use log::info;
5901 use std::num::NonZeroU32;
5902 use ui::Context;
5903 use util::test::sample_text;
5904
5905 #[gpui::test]
5906 fn test_shape_line_numbers(cx: &mut TestAppContext) {
5907 init_test(cx, |_| {});
5908 let window = cx.add_window(|cx| {
5909 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
5910 Editor::new(EditorMode::Full, buffer, None, true, cx)
5911 });
5912
5913 let editor = window.root(cx).unwrap();
5914 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5915 let element = EditorElement::new(&editor, style);
5916 let snapshot = window.update(cx, |editor, cx| editor.snapshot(cx)).unwrap();
5917
5918 let layouts = cx
5919 .update_window(*window, |_, cx| {
5920 element.layout_line_numbers(
5921 DisplayRow(0)..DisplayRow(6),
5922 (0..6).map(MultiBufferRow).map(Some),
5923 &Default::default(),
5924 Some(DisplayPoint::new(DisplayRow(0), 0)),
5925 &snapshot,
5926 cx,
5927 )
5928 })
5929 .unwrap();
5930 assert_eq!(layouts.len(), 6);
5931
5932 let relative_rows = window
5933 .update(cx, |editor, cx| {
5934 let snapshot = editor.snapshot(cx);
5935 element.calculate_relative_line_numbers(
5936 &snapshot,
5937 &(DisplayRow(0)..DisplayRow(6)),
5938 Some(DisplayRow(3)),
5939 )
5940 })
5941 .unwrap();
5942 assert_eq!(relative_rows[&DisplayRow(0)], 3);
5943 assert_eq!(relative_rows[&DisplayRow(1)], 2);
5944 assert_eq!(relative_rows[&DisplayRow(2)], 1);
5945 // current line has no relative number
5946 assert_eq!(relative_rows[&DisplayRow(4)], 1);
5947 assert_eq!(relative_rows[&DisplayRow(5)], 2);
5948
5949 // works if cursor is before screen
5950 let relative_rows = window
5951 .update(cx, |editor, cx| {
5952 let snapshot = editor.snapshot(cx);
5953 element.calculate_relative_line_numbers(
5954 &snapshot,
5955 &(DisplayRow(3)..DisplayRow(6)),
5956 Some(DisplayRow(1)),
5957 )
5958 })
5959 .unwrap();
5960 assert_eq!(relative_rows.len(), 3);
5961 assert_eq!(relative_rows[&DisplayRow(3)], 2);
5962 assert_eq!(relative_rows[&DisplayRow(4)], 3);
5963 assert_eq!(relative_rows[&DisplayRow(5)], 4);
5964
5965 // works if cursor is after screen
5966 let relative_rows = window
5967 .update(cx, |editor, cx| {
5968 let snapshot = editor.snapshot(cx);
5969 element.calculate_relative_line_numbers(
5970 &snapshot,
5971 &(DisplayRow(0)..DisplayRow(3)),
5972 Some(DisplayRow(6)),
5973 )
5974 })
5975 .unwrap();
5976 assert_eq!(relative_rows.len(), 3);
5977 assert_eq!(relative_rows[&DisplayRow(0)], 5);
5978 assert_eq!(relative_rows[&DisplayRow(1)], 4);
5979 assert_eq!(relative_rows[&DisplayRow(2)], 3);
5980 }
5981
5982 #[gpui::test]
5983 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
5984 init_test(cx, |_| {});
5985
5986 let window = cx.add_window(|cx| {
5987 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
5988 Editor::new(EditorMode::Full, buffer, None, true, cx)
5989 });
5990 let cx = &mut VisualTestContext::from_window(*window, cx);
5991 let editor = window.root(cx).unwrap();
5992 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5993
5994 window
5995 .update(cx, |editor, cx| {
5996 editor.cursor_shape = CursorShape::Block;
5997 editor.change_selections(None, cx, |s| {
5998 s.select_ranges([
5999 Point::new(0, 0)..Point::new(1, 0),
6000 Point::new(3, 2)..Point::new(3, 3),
6001 Point::new(5, 6)..Point::new(6, 0),
6002 ]);
6003 });
6004 })
6005 .unwrap();
6006
6007 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6008 EditorElement::new(&editor, style)
6009 });
6010
6011 assert_eq!(state.selections.len(), 1);
6012 let local_selections = &state.selections[0].1;
6013 assert_eq!(local_selections.len(), 3);
6014 // moves cursor back one line
6015 assert_eq!(
6016 local_selections[0].head,
6017 DisplayPoint::new(DisplayRow(0), 6)
6018 );
6019 assert_eq!(
6020 local_selections[0].range,
6021 DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
6022 );
6023
6024 // moves cursor back one column
6025 assert_eq!(
6026 local_selections[1].range,
6027 DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
6028 );
6029 assert_eq!(
6030 local_selections[1].head,
6031 DisplayPoint::new(DisplayRow(3), 2)
6032 );
6033
6034 // leaves cursor on the max point
6035 assert_eq!(
6036 local_selections[2].range,
6037 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
6038 );
6039 assert_eq!(
6040 local_selections[2].head,
6041 DisplayPoint::new(DisplayRow(6), 0)
6042 );
6043
6044 // active lines does not include 1 (even though the range of the selection does)
6045 assert_eq!(
6046 state.active_rows.keys().cloned().collect::<Vec<_>>(),
6047 vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
6048 );
6049
6050 // multi-buffer support
6051 // in DisplayPoint coordinates, this is what we're dealing with:
6052 // 0: [[file
6053 // 1: header
6054 // 2: section]]
6055 // 3: aaaaaa
6056 // 4: bbbbbb
6057 // 5: cccccc
6058 // 6:
6059 // 7: [[footer]]
6060 // 8: [[header]]
6061 // 9: ffffff
6062 // 10: gggggg
6063 // 11: hhhhhh
6064 // 12:
6065 // 13: [[footer]]
6066 // 14: [[file
6067 // 15: header
6068 // 16: section]]
6069 // 17: bbbbbb
6070 // 18: cccccc
6071 // 19: dddddd
6072 // 20: [[footer]]
6073 let window = cx.add_window(|cx| {
6074 let buffer = MultiBuffer::build_multi(
6075 [
6076 (
6077 &(sample_text(8, 6, 'a') + "\n"),
6078 vec![
6079 Point::new(0, 0)..Point::new(3, 0),
6080 Point::new(4, 0)..Point::new(7, 0),
6081 ],
6082 ),
6083 (
6084 &(sample_text(8, 6, 'a') + "\n"),
6085 vec![Point::new(1, 0)..Point::new(3, 0)],
6086 ),
6087 ],
6088 cx,
6089 );
6090 Editor::new(EditorMode::Full, buffer, None, true, cx)
6091 });
6092 let editor = window.root(cx).unwrap();
6093 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6094 let _state = window.update(cx, |editor, cx| {
6095 editor.cursor_shape = CursorShape::Block;
6096 editor.change_selections(None, cx, |s| {
6097 s.select_display_ranges([
6098 DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0),
6099 DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0),
6100 ]);
6101 });
6102 });
6103
6104 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6105 EditorElement::new(&editor, style)
6106 });
6107 assert_eq!(state.selections.len(), 1);
6108 let local_selections = &state.selections[0].1;
6109 assert_eq!(local_selections.len(), 2);
6110
6111 // moves cursor on excerpt boundary back a line
6112 // and doesn't allow selection to bleed through
6113 assert_eq!(
6114 local_selections[0].range,
6115 DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0)
6116 );
6117 assert_eq!(
6118 local_selections[0].head,
6119 DisplayPoint::new(DisplayRow(6), 0)
6120 );
6121 // moves cursor on buffer boundary back two lines
6122 // and doesn't allow selection to bleed through
6123 assert_eq!(
6124 local_selections[1].range,
6125 DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0)
6126 );
6127 assert_eq!(
6128 local_selections[1].head,
6129 DisplayPoint::new(DisplayRow(12), 0)
6130 );
6131 }
6132
6133 #[gpui::test]
6134 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
6135 init_test(cx, |_| {});
6136
6137 let window = cx.add_window(|cx| {
6138 let buffer = MultiBuffer::build_simple("", cx);
6139 Editor::new(EditorMode::Full, buffer, None, true, cx)
6140 });
6141 let cx = &mut VisualTestContext::from_window(*window, cx);
6142 let editor = window.root(cx).unwrap();
6143 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6144 window
6145 .update(cx, |editor, cx| {
6146 editor.set_placeholder_text("hello", cx);
6147 editor.insert_blocks(
6148 [BlockProperties {
6149 style: BlockStyle::Fixed,
6150 disposition: BlockDisposition::Above,
6151 height: 3,
6152 position: Anchor::min(),
6153 render: Box::new(|_| div().into_any()),
6154 }],
6155 None,
6156 cx,
6157 );
6158
6159 // Blur the editor so that it displays placeholder text.
6160 cx.blur();
6161 })
6162 .unwrap();
6163
6164 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6165 EditorElement::new(&editor, style)
6166 });
6167 assert_eq!(state.position_map.line_layouts.len(), 4);
6168 assert_eq!(
6169 state
6170 .line_numbers
6171 .iter()
6172 .map(Option::is_some)
6173 .collect::<Vec<_>>(),
6174 &[false, false, false, true]
6175 );
6176 }
6177
6178 #[gpui::test]
6179 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
6180 const TAB_SIZE: u32 = 4;
6181
6182 let input_text = "\t \t|\t| a b";
6183 let expected_invisibles = vec![
6184 Invisible::Tab {
6185 line_start_offset: 0,
6186 line_end_offset: TAB_SIZE as usize,
6187 },
6188 Invisible::Whitespace {
6189 line_offset: TAB_SIZE as usize,
6190 },
6191 Invisible::Tab {
6192 line_start_offset: TAB_SIZE as usize + 1,
6193 line_end_offset: TAB_SIZE as usize * 2,
6194 },
6195 Invisible::Tab {
6196 line_start_offset: TAB_SIZE as usize * 2 + 1,
6197 line_end_offset: TAB_SIZE as usize * 3,
6198 },
6199 Invisible::Whitespace {
6200 line_offset: TAB_SIZE as usize * 3 + 1,
6201 },
6202 Invisible::Whitespace {
6203 line_offset: TAB_SIZE as usize * 3 + 3,
6204 },
6205 ];
6206 assert_eq!(
6207 expected_invisibles.len(),
6208 input_text
6209 .chars()
6210 .filter(|initial_char| initial_char.is_whitespace())
6211 .count(),
6212 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
6213 );
6214
6215 init_test(cx, |s| {
6216 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6217 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
6218 });
6219
6220 let actual_invisibles =
6221 collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, px(500.0));
6222
6223 assert_eq!(expected_invisibles, actual_invisibles);
6224 }
6225
6226 #[gpui::test]
6227 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
6228 init_test(cx, |s| {
6229 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6230 s.defaults.tab_size = NonZeroU32::new(4);
6231 });
6232
6233 for editor_mode_without_invisibles in [
6234 EditorMode::SingleLine { auto_width: false },
6235 EditorMode::AutoHeight { max_lines: 100 },
6236 ] {
6237 let invisibles = collect_invisibles_from_new_editor(
6238 cx,
6239 editor_mode_without_invisibles,
6240 "\t\t\t| | a b",
6241 px(500.0),
6242 );
6243 assert!(invisibles.is_empty(),
6244 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
6245 }
6246 }
6247
6248 #[gpui::test]
6249 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
6250 let tab_size = 4;
6251 let input_text = "a\tbcd ".repeat(9);
6252 let repeated_invisibles = [
6253 Invisible::Tab {
6254 line_start_offset: 1,
6255 line_end_offset: tab_size as usize,
6256 },
6257 Invisible::Whitespace {
6258 line_offset: tab_size as usize + 3,
6259 },
6260 Invisible::Whitespace {
6261 line_offset: tab_size as usize + 4,
6262 },
6263 Invisible::Whitespace {
6264 line_offset: tab_size as usize + 5,
6265 },
6266 Invisible::Whitespace {
6267 line_offset: tab_size as usize + 6,
6268 },
6269 Invisible::Whitespace {
6270 line_offset: tab_size as usize + 7,
6271 },
6272 ];
6273 let expected_invisibles = std::iter::once(repeated_invisibles)
6274 .cycle()
6275 .take(9)
6276 .flatten()
6277 .collect::<Vec<_>>();
6278 assert_eq!(
6279 expected_invisibles.len(),
6280 input_text
6281 .chars()
6282 .filter(|initial_char| initial_char.is_whitespace())
6283 .count(),
6284 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
6285 );
6286 info!("Expected invisibles: {expected_invisibles:?}");
6287
6288 init_test(cx, |_| {});
6289
6290 // Put the same string with repeating whitespace pattern into editors of various size,
6291 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
6292 let resize_step = 10.0;
6293 let mut editor_width = 200.0;
6294 while editor_width <= 1000.0 {
6295 update_test_language_settings(cx, |s| {
6296 s.defaults.tab_size = NonZeroU32::new(tab_size);
6297 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6298 s.defaults.preferred_line_length = Some(editor_width as u32);
6299 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
6300 });
6301
6302 let actual_invisibles = collect_invisibles_from_new_editor(
6303 cx,
6304 EditorMode::Full,
6305 &input_text,
6306 px(editor_width),
6307 );
6308
6309 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
6310 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
6311 let mut i = 0;
6312 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
6313 i = actual_index;
6314 match expected_invisibles.get(i) {
6315 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
6316 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
6317 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
6318 _ => {
6319 panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
6320 }
6321 },
6322 None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
6323 }
6324 }
6325 let missing_expected_invisibles = &expected_invisibles[i + 1..];
6326 assert!(
6327 missing_expected_invisibles.is_empty(),
6328 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
6329 );
6330
6331 editor_width += resize_step;
6332 }
6333 }
6334
6335 fn collect_invisibles_from_new_editor(
6336 cx: &mut TestAppContext,
6337 editor_mode: EditorMode,
6338 input_text: &str,
6339 editor_width: Pixels,
6340 ) -> Vec<Invisible> {
6341 info!(
6342 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
6343 editor_width.0
6344 );
6345 let window = cx.add_window(|cx| {
6346 let buffer = MultiBuffer::build_simple(&input_text, cx);
6347 Editor::new(editor_mode, buffer, None, true, cx)
6348 });
6349 let cx = &mut VisualTestContext::from_window(*window, cx);
6350 let editor = window.root(cx).unwrap();
6351 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6352 window
6353 .update(cx, |editor, cx| {
6354 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
6355 editor.set_wrap_width(Some(editor_width), cx);
6356 })
6357 .unwrap();
6358 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6359 EditorElement::new(&editor, style)
6360 });
6361 state
6362 .position_map
6363 .line_layouts
6364 .iter()
6365 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
6366 .cloned()
6367 .collect()
6368 }
6369}
6370
6371pub fn register_action<T: Action>(
6372 view: &View<Editor>,
6373 cx: &mut WindowContext,
6374 listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
6375) {
6376 let view = view.clone();
6377 cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
6378 let action = action.downcast_ref().unwrap();
6379 if phase == DispatchPhase::Bubble {
6380 view.update(cx, |editor, cx| {
6381 listener(editor, action, cx);
6382 })
6383 }
6384 })
6385}
6386
6387fn compute_auto_height_layout(
6388 editor: &mut Editor,
6389 max_lines: usize,
6390 max_line_number_width: Pixels,
6391 known_dimensions: Size<Option<Pixels>>,
6392 available_width: AvailableSpace,
6393 cx: &mut ViewContext<Editor>,
6394) -> Option<Size<Pixels>> {
6395 let width = known_dimensions.width.or_else(|| {
6396 if let AvailableSpace::Definite(available_width) = available_width {
6397 Some(available_width)
6398 } else {
6399 None
6400 }
6401 })?;
6402 if let Some(height) = known_dimensions.height {
6403 return Some(size(width, height));
6404 }
6405
6406 let style = editor.style.as_ref().unwrap();
6407 let font_id = cx.text_system().resolve_font(&style.text.font());
6408 let font_size = style.text.font_size.to_pixels(cx.rem_size());
6409 let line_height = style.text.line_height_in_pixels(cx.rem_size());
6410 let em_width = cx
6411 .text_system()
6412 .typographic_bounds(font_id, font_size, 'm')
6413 .unwrap()
6414 .size
6415 .width;
6416
6417 let mut snapshot = editor.snapshot(cx);
6418 let gutter_dimensions =
6419 snapshot.gutter_dimensions(font_id, font_size, em_width, max_line_number_width, cx);
6420
6421 editor.gutter_dimensions = gutter_dimensions;
6422 let text_width = width - gutter_dimensions.width;
6423 let overscroll = size(em_width, px(0.));
6424
6425 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
6426 if editor.set_wrap_width(Some(editor_width), cx) {
6427 snapshot = editor.snapshot(cx);
6428 }
6429
6430 let scroll_height = Pixels::from(snapshot.max_point().row().next_row().0) * line_height;
6431 let height = scroll_height
6432 .max(line_height)
6433 .min(line_height * max_lines as f32);
6434
6435 Some(size(width, height))
6436}