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