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