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