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