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