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