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