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