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