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