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