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, 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 } => {
2156 let icon_offset = gutter_dimensions.width
2157 - (gutter_dimensions.left_padding + gutter_dimensions.margin);
2158
2159 let mut result = v_flex().id(block_id).w_full();
2160 if let Some(prev_excerpt) = prev_excerpt {
2161 if *show_excerpt_controls {
2162 result = result.child(
2163 h_flex()
2164 .w(icon_offset)
2165 .h(MULTI_BUFFER_EXCERPT_HEADER_HEIGHT as f32 * cx.line_height())
2166 .flex_none()
2167 .justify_end()
2168 .child(self.render_expand_excerpt_button(
2169 prev_excerpt.id,
2170 ExpandExcerptDirection::Down,
2171 IconName::ArrowDownFromLine,
2172 cx,
2173 )),
2174 );
2175 }
2176 }
2177
2178 let jump_data = jump_data(snapshot, block_row_start, *height, first_excerpt, cx);
2179 result
2180 .child(self.render_buffer_header(
2181 first_excerpt,
2182 header_padding,
2183 true,
2184 jump_data,
2185 cx,
2186 ))
2187 .into_any_element()
2188 }
2189 Block::ExcerptBoundary {
2190 prev_excerpt,
2191 next_excerpt,
2192 show_excerpt_controls,
2193 height,
2194 starts_new_buffer,
2195 ..
2196 } => {
2197 let icon_offset = gutter_dimensions.width
2198 - (gutter_dimensions.left_padding + gutter_dimensions.margin);
2199
2200 let mut result = v_flex().id(block_id).w_full();
2201 if let Some(prev_excerpt) = prev_excerpt {
2202 if *show_excerpt_controls {
2203 result = result.child(
2204 h_flex()
2205 .w(icon_offset)
2206 .h(MULTI_BUFFER_EXCERPT_HEADER_HEIGHT as f32 * cx.line_height())
2207 .flex_none()
2208 .justify_end()
2209 .child(self.render_expand_excerpt_button(
2210 prev_excerpt.id,
2211 ExpandExcerptDirection::Down,
2212 IconName::ArrowDownFromLine,
2213 cx,
2214 )),
2215 );
2216 }
2217 }
2218
2219 if let Some(next_excerpt) = next_excerpt {
2220 let jump_data = jump_data(snapshot, block_row_start, *height, next_excerpt, cx);
2221 if *starts_new_buffer {
2222 result = result.child(self.render_buffer_header(
2223 next_excerpt,
2224 header_padding,
2225 false,
2226 jump_data,
2227 cx,
2228 ));
2229 if *show_excerpt_controls {
2230 result = result.child(
2231 h_flex()
2232 .w(icon_offset)
2233 .h(MULTI_BUFFER_EXCERPT_HEADER_HEIGHT as f32 * cx.line_height())
2234 .flex_none()
2235 .justify_end()
2236 .child(self.render_expand_excerpt_button(
2237 next_excerpt.id,
2238 ExpandExcerptDirection::Up,
2239 IconName::ArrowUpFromLine,
2240 cx,
2241 )),
2242 );
2243 }
2244 } else {
2245 let editor = self.editor.clone();
2246 result = result.child(
2247 h_flex()
2248 .id("excerpt header block")
2249 .group("excerpt-jump-action")
2250 .justify_start()
2251 .w_full()
2252 .h(MULTI_BUFFER_EXCERPT_HEADER_HEIGHT as f32 * cx.line_height())
2253 .relative()
2254 .child(
2255 div()
2256 .top(px(0.))
2257 .absolute()
2258 .w_full()
2259 .h_px()
2260 .bg(cx.theme().colors().border_variant)
2261 .group_hover("excerpt-jump-action", |style| {
2262 style.bg(cx.theme().colors().border)
2263 }),
2264 )
2265 .cursor_pointer()
2266 .on_click({
2267 let jump_data = jump_data.clone();
2268 cx.listener_for(&self.editor, {
2269 let jump_data = jump_data.clone();
2270 move |editor, e: &ClickEvent, cx| {
2271 cx.stop_propagation();
2272 editor.open_excerpts_common(
2273 Some(jump_data.clone()),
2274 e.down.modifiers.secondary(),
2275 cx,
2276 );
2277 }
2278 })
2279 })
2280 .tooltip({
2281 let jump_data = jump_data.clone();
2282 move |cx| {
2283 let jump_message = format!(
2284 "Jump to {}:L{}",
2285 match &jump_data.path {
2286 Some(project_path) =>
2287 project_path.path.display().to_string(),
2288 None => {
2289 let editor = editor.read(cx);
2290 editor
2291 .file_at(jump_data.position, cx)
2292 .map(|file| {
2293 file.full_path(cx).display().to_string()
2294 })
2295 .or_else(|| {
2296 Some(
2297 editor
2298 .tab_description(0, cx)?
2299 .to_string(),
2300 )
2301 })
2302 .unwrap_or_else(|| {
2303 "Unknown buffer".to_string()
2304 })
2305 }
2306 },
2307 jump_data.position.row + 1
2308 );
2309 Tooltip::for_action(jump_message, &OpenExcerpts, cx)
2310 }
2311 })
2312 .child(
2313 h_flex()
2314 .w(icon_offset)
2315 .h(MULTI_BUFFER_EXCERPT_HEADER_HEIGHT as f32
2316 * cx.line_height())
2317 .flex_none()
2318 .justify_end()
2319 .child(if *show_excerpt_controls {
2320 self.render_expand_excerpt_button(
2321 next_excerpt.id,
2322 ExpandExcerptDirection::Up,
2323 IconName::ArrowUpFromLine,
2324 cx,
2325 )
2326 } else {
2327 ButtonLike::new("jump-icon")
2328 .style(ButtonStyle::Transparent)
2329 .child(
2330 svg()
2331 .path(IconName::ArrowUpRight.path())
2332 .size(IconSize::XSmall.rems())
2333 .text_color(
2334 cx.theme().colors().border_variant,
2335 )
2336 .group_hover(
2337 "excerpt-jump-action",
2338 |style| {
2339 style.text_color(
2340 cx.theme().colors().border,
2341 )
2342 },
2343 ),
2344 )
2345 }),
2346 ),
2347 );
2348 }
2349 }
2350
2351 result.into_any()
2352 }
2353 };
2354
2355 // Discover the element's content height, then round up to the nearest multiple of line height.
2356 let preliminary_size =
2357 element.layout_as_root(size(available_width, AvailableSpace::MinContent), cx);
2358 let quantized_height = (preliminary_size.height / line_height).ceil() * line_height;
2359 let final_size = if preliminary_size.height == quantized_height {
2360 preliminary_size
2361 } else {
2362 element.layout_as_root(size(available_width, quantized_height.into()), cx)
2363 };
2364
2365 if let BlockId::Custom(custom_block_id) = block_id {
2366 if block.height() > 0 {
2367 let element_height_in_lines =
2368 ((final_size.height / line_height).ceil() as u32).max(1);
2369 if element_height_in_lines != block.height() {
2370 resized_blocks.insert(custom_block_id, element_height_in_lines);
2371 }
2372 }
2373 }
2374
2375 (element, final_size)
2376 }
2377
2378 fn render_buffer_header(
2379 &self,
2380 for_excerpt: &ExcerptInfo,
2381 header_padding: Pixels,
2382 is_folded: bool,
2383 jump_data: JumpData,
2384 cx: &mut WindowContext,
2385 ) -> Div {
2386 let include_root = self
2387 .editor
2388 .read(cx)
2389 .project
2390 .as_ref()
2391 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
2392 .unwrap_or_default();
2393 let path = for_excerpt.buffer.resolve_file_path(cx, include_root);
2394 let filename = path
2395 .as_ref()
2396 .and_then(|path| Some(path.file_name()?.to_string_lossy().to_string()));
2397 let parent_path = path
2398 .as_ref()
2399 .and_then(|path| Some(path.parent()?.to_string_lossy().to_string() + "/"));
2400
2401 div()
2402 .px(header_padding)
2403 .pt(header_padding)
2404 .w_full()
2405 .h(FILE_HEADER_HEIGHT as f32 * cx.line_height())
2406 .child(
2407 h_flex()
2408 .id("path header block")
2409 .size_full()
2410 .flex_basis(Length::Definite(DefiniteLength::Fraction(0.667)))
2411 .px(gpui::px(12.))
2412 .rounded_md()
2413 .shadow_md()
2414 .border_1()
2415 .border_color(cx.theme().colors().border)
2416 .bg(cx.theme().colors().editor_subheader_background)
2417 .justify_between()
2418 .hover(|style| style.bg(cx.theme().colors().element_hover))
2419 .child(
2420 h_flex()
2421 .gap_3()
2422 .map(|header| {
2423 let editor = self.editor.clone();
2424 let buffer_id = for_excerpt.buffer_id;
2425 let toggle_chevron_icon =
2426 FileIcons::get_chevron_icon(!is_folded, cx)
2427 .map(Icon::from_path);
2428 header.child(
2429 ButtonLike::new("toggle-buffer-fold")
2430 .children(toggle_chevron_icon)
2431 .on_click(move |_, cx| {
2432 if is_folded {
2433 editor.update(cx, |editor, cx| {
2434 editor.unfold_buffer(buffer_id, cx);
2435 });
2436 } else {
2437 editor.update(cx, |editor, cx| {
2438 editor.fold_buffer(buffer_id, cx);
2439 });
2440 }
2441 }),
2442 )
2443 })
2444 .child(
2445 h_flex()
2446 .gap_2()
2447 .child(
2448 filename
2449 .map(SharedString::from)
2450 .unwrap_or_else(|| "untitled".into()),
2451 )
2452 .when_some(parent_path, |then, path| {
2453 then.child(
2454 div()
2455 .child(path)
2456 .text_color(cx.theme().colors().text_muted),
2457 )
2458 }),
2459 ),
2460 )
2461 .child(Icon::new(IconName::ArrowUpRight))
2462 .cursor_pointer()
2463 .tooltip(|cx| Tooltip::for_action("Jump to File", &OpenExcerpts, cx))
2464 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
2465 .on_click(cx.listener_for(&self.editor, {
2466 move |editor, e: &ClickEvent, cx| {
2467 editor.open_excerpts_common(
2468 Some(jump_data.clone()),
2469 e.down.modifiers.secondary(),
2470 cx,
2471 );
2472 }
2473 })),
2474 )
2475 }
2476
2477 fn render_expand_excerpt_button(
2478 &self,
2479 excerpt_id: ExcerptId,
2480 direction: ExpandExcerptDirection,
2481 icon: IconName,
2482 cx: &mut WindowContext,
2483 ) -> ButtonLike {
2484 ButtonLike::new("expand-icon")
2485 .style(ButtonStyle::Transparent)
2486 .child(
2487 svg()
2488 .path(icon.path())
2489 .size(IconSize::XSmall.rems())
2490 .text_color(cx.theme().colors().editor_line_number)
2491 .group("")
2492 .hover(|style| style.text_color(cx.theme().colors().editor_active_line_number)),
2493 )
2494 .on_click(cx.listener_for(&self.editor, {
2495 move |editor, _, cx| {
2496 editor.expand_excerpt(excerpt_id, direction, cx);
2497 }
2498 }))
2499 .tooltip({
2500 move |cx| Tooltip::for_action("Expand Excerpt", &ExpandExcerpts { lines: 0 }, cx)
2501 })
2502 }
2503
2504 #[allow(clippy::too_many_arguments)]
2505 fn render_blocks(
2506 &self,
2507 rows: Range<DisplayRow>,
2508 snapshot: &EditorSnapshot,
2509 hitbox: &Hitbox,
2510 text_hitbox: &Hitbox,
2511 editor_width: Pixels,
2512 scroll_width: &mut Pixels,
2513 gutter_dimensions: &GutterDimensions,
2514 em_width: Pixels,
2515 text_x: Pixels,
2516 line_height: Pixels,
2517 line_layouts: &[LineWithInvisibles],
2518 selections: &[Selection<Point>],
2519 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
2520 cx: &mut WindowContext,
2521 ) -> Result<Vec<BlockLayout>, HashMap<CustomBlockId, u32>> {
2522 let (fixed_blocks, non_fixed_blocks) = snapshot
2523 .blocks_in_range(rows.clone())
2524 .partition::<Vec<_>, _>(|(_, block)| block.style() == BlockStyle::Fixed);
2525
2526 let mut focused_block = self
2527 .editor
2528 .update(cx, |editor, _| editor.take_focused_block());
2529 let mut fixed_block_max_width = Pixels::ZERO;
2530 let mut blocks = Vec::new();
2531 let mut resized_blocks = HashMap::default();
2532
2533 for (row, block) in fixed_blocks {
2534 let block_id = block.id();
2535
2536 if focused_block.as_ref().map_or(false, |b| b.id == block_id) {
2537 focused_block = None;
2538 }
2539
2540 let (element, element_size) = self.render_block(
2541 block,
2542 AvailableSpace::MinContent,
2543 block_id,
2544 row,
2545 snapshot,
2546 text_x,
2547 &rows,
2548 line_layouts,
2549 gutter_dimensions,
2550 line_height,
2551 em_width,
2552 text_hitbox,
2553 editor_width,
2554 scroll_width,
2555 &mut resized_blocks,
2556 selections,
2557 is_row_soft_wrapped,
2558 cx,
2559 );
2560 fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
2561 blocks.push(BlockLayout {
2562 id: block_id,
2563 row: Some(row),
2564 element,
2565 available_space: size(AvailableSpace::MinContent, element_size.height.into()),
2566 style: BlockStyle::Fixed,
2567 });
2568 }
2569 for (row, block) in non_fixed_blocks {
2570 let style = block.style();
2571 let width = match style {
2572 BlockStyle::Sticky => hitbox.size.width,
2573 BlockStyle::Flex => hitbox
2574 .size
2575 .width
2576 .max(fixed_block_max_width)
2577 .max(gutter_dimensions.width + *scroll_width),
2578 BlockStyle::Fixed => unreachable!(),
2579 };
2580 let block_id = block.id();
2581
2582 if focused_block.as_ref().map_or(false, |b| b.id == block_id) {
2583 focused_block = None;
2584 }
2585
2586 let (element, element_size) = self.render_block(
2587 block,
2588 width.into(),
2589 block_id,
2590 row,
2591 snapshot,
2592 text_x,
2593 &rows,
2594 line_layouts,
2595 gutter_dimensions,
2596 line_height,
2597 em_width,
2598 text_hitbox,
2599 editor_width,
2600 scroll_width,
2601 &mut resized_blocks,
2602 selections,
2603 is_row_soft_wrapped,
2604 cx,
2605 );
2606
2607 blocks.push(BlockLayout {
2608 id: block_id,
2609 row: Some(row),
2610 element,
2611 available_space: size(width.into(), element_size.height.into()),
2612 style,
2613 });
2614 }
2615
2616 if let Some(focused_block) = focused_block {
2617 if let Some(focus_handle) = focused_block.focus_handle.upgrade() {
2618 if focus_handle.is_focused(cx) {
2619 if let Some(block) = snapshot.block_for_id(focused_block.id) {
2620 let style = block.style();
2621 let width = match style {
2622 BlockStyle::Fixed => AvailableSpace::MinContent,
2623 BlockStyle::Flex => AvailableSpace::Definite(
2624 hitbox
2625 .size
2626 .width
2627 .max(fixed_block_max_width)
2628 .max(gutter_dimensions.width + *scroll_width),
2629 ),
2630 BlockStyle::Sticky => AvailableSpace::Definite(hitbox.size.width),
2631 };
2632
2633 let (element, element_size) = self.render_block(
2634 &block,
2635 width,
2636 focused_block.id,
2637 rows.end,
2638 snapshot,
2639 text_x,
2640 &rows,
2641 line_layouts,
2642 gutter_dimensions,
2643 line_height,
2644 em_width,
2645 text_hitbox,
2646 editor_width,
2647 scroll_width,
2648 &mut resized_blocks,
2649 selections,
2650 is_row_soft_wrapped,
2651 cx,
2652 );
2653
2654 blocks.push(BlockLayout {
2655 id: block.id(),
2656 row: None,
2657 element,
2658 available_space: size(width, element_size.height.into()),
2659 style,
2660 });
2661 }
2662 }
2663 }
2664 }
2665
2666 if resized_blocks.is_empty() {
2667 *scroll_width = (*scroll_width).max(fixed_block_max_width - gutter_dimensions.width);
2668 Ok(blocks)
2669 } else {
2670 Err(resized_blocks)
2671 }
2672 }
2673
2674 /// Returns true if any of the blocks changed size since the previous frame. This will trigger
2675 /// a restart of rendering for the editor based on the new sizes.
2676 fn layout_blocks(
2677 &self,
2678 blocks: &mut Vec<BlockLayout>,
2679 block_starts: &mut HashSet<DisplayRow>,
2680 hitbox: &Hitbox,
2681 line_height: Pixels,
2682 scroll_pixel_position: gpui::Point<Pixels>,
2683 cx: &mut WindowContext,
2684 ) {
2685 for block in blocks {
2686 let mut origin = if let Some(row) = block.row {
2687 block_starts.insert(row);
2688 hitbox.origin
2689 + point(
2690 Pixels::ZERO,
2691 row.as_f32() * line_height - scroll_pixel_position.y,
2692 )
2693 } else {
2694 // Position the block outside the visible area
2695 hitbox.origin + point(Pixels::ZERO, hitbox.size.height)
2696 };
2697
2698 if !matches!(block.style, BlockStyle::Sticky) {
2699 origin += point(-scroll_pixel_position.x, Pixels::ZERO);
2700 }
2701
2702 let focus_handle = block
2703 .element
2704 .prepaint_as_root(origin, block.available_space, cx);
2705
2706 if let Some(focus_handle) = focus_handle {
2707 self.editor.update(cx, |editor, _cx| {
2708 editor.set_focused_block(FocusedBlock {
2709 id: block.id,
2710 focus_handle: focus_handle.downgrade(),
2711 });
2712 });
2713 }
2714 }
2715 }
2716
2717 #[allow(clippy::too_many_arguments)]
2718 fn layout_context_menu(
2719 &self,
2720 line_height: Pixels,
2721 hitbox: &Hitbox,
2722 text_hitbox: &Hitbox,
2723 content_origin: gpui::Point<Pixels>,
2724 start_row: DisplayRow,
2725 scroll_pixel_position: gpui::Point<Pixels>,
2726 line_layouts: &[LineWithInvisibles],
2727 newest_selection_head: DisplayPoint,
2728 gutter_overshoot: Pixels,
2729 cx: &mut WindowContext,
2730 ) -> bool {
2731 let max_height = cmp::min(
2732 12. * line_height,
2733 cmp::max(3. * line_height, (hitbox.size.height - line_height) / 2.),
2734 );
2735 let Some((position, mut context_menu)) = self.editor.update(cx, |editor, cx| {
2736 if editor.context_menu_visible() {
2737 editor.render_context_menu(newest_selection_head, &self.style, max_height, cx)
2738 } else {
2739 None
2740 }
2741 }) else {
2742 return false;
2743 };
2744
2745 let context_menu_size = context_menu.layout_as_root(AvailableSpace::min_size(), cx);
2746
2747 let (x, y) = match position {
2748 crate::ContextMenuOrigin::EditorPoint(point) => {
2749 let cursor_row_layout = &line_layouts[point.row().minus(start_row) as usize];
2750 let x = cursor_row_layout.x_for_index(point.column() as usize)
2751 - scroll_pixel_position.x;
2752 let y = point.row().next_row().as_f32() * line_height - scroll_pixel_position.y;
2753 (x, y)
2754 }
2755 crate::ContextMenuOrigin::GutterIndicator(row) => {
2756 // 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
2757 // text field.
2758 let x = -gutter_overshoot;
2759 let y = row.next_row().as_f32() * line_height - scroll_pixel_position.y;
2760 (x, y)
2761 }
2762 };
2763
2764 let mut list_origin = content_origin + point(x, y);
2765 let list_width = context_menu_size.width;
2766 let list_height = context_menu_size.height;
2767
2768 // Snap the right edge of the list to the right edge of the window if
2769 // its horizontal bounds overflow.
2770 if list_origin.x + list_width > cx.viewport_size().width {
2771 list_origin.x = (cx.viewport_size().width - list_width).max(Pixels::ZERO);
2772 }
2773
2774 if list_origin.y + list_height > text_hitbox.lower_right().y {
2775 list_origin.y -= line_height + list_height;
2776 }
2777
2778 cx.defer_draw(context_menu, list_origin, 1);
2779 true
2780 }
2781
2782 #[allow(clippy::too_many_arguments)]
2783 fn layout_inline_completion_popover(
2784 &self,
2785 text_bounds: &Bounds<Pixels>,
2786 editor_snapshot: &EditorSnapshot,
2787 visible_row_range: Range<DisplayRow>,
2788 scroll_top: f32,
2789 scroll_bottom: f32,
2790 line_layouts: &[LineWithInvisibles],
2791 line_height: Pixels,
2792 scroll_pixel_position: gpui::Point<Pixels>,
2793 editor_width: Pixels,
2794 style: &EditorStyle,
2795 cx: &mut WindowContext,
2796 ) -> Option<AnyElement> {
2797 const PADDING_X: Pixels = Pixels(24.);
2798 const PADDING_Y: Pixels = Pixels(2.);
2799
2800 let active_inline_completion = self.editor.read(cx).active_inline_completion.as_ref()?;
2801
2802 match &active_inline_completion.completion {
2803 InlineCompletion::Move(target_position) => {
2804 let tab_kbd = h_flex()
2805 .px_0p5()
2806 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
2807 .text_size(TextSize::XSmall.rems(cx))
2808 .text_color(cx.theme().colors().text.opacity(0.8))
2809 .child("tab");
2810
2811 let icon_container = div().mt(px(2.5)); // For optical alignment
2812
2813 let container_element = h_flex()
2814 .items_center()
2815 .py_0p5()
2816 .px_1()
2817 .gap_1()
2818 .bg(cx.theme().colors().editor_subheader_background)
2819 .border_1()
2820 .border_color(cx.theme().colors().text_accent.opacity(0.2))
2821 .rounded_md()
2822 .shadow_sm();
2823
2824 let target_display_point = target_position.to_display_point(editor_snapshot);
2825 if target_display_point.row().as_f32() < scroll_top {
2826 let mut element = container_element
2827 .child(tab_kbd)
2828 .child(Label::new("Jump to Edit").size(LabelSize::Small))
2829 .child(
2830 icon_container
2831 .child(Icon::new(IconName::ArrowUp).size(IconSize::Small)),
2832 )
2833 .into_any();
2834 let size = element.layout_as_root(AvailableSpace::min_size(), cx);
2835 let offset = point((text_bounds.size.width - size.width) / 2., PADDING_Y);
2836 element.prepaint_at(text_bounds.origin + offset, cx);
2837 Some(element)
2838 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
2839 let mut element = container_element
2840 .child(tab_kbd)
2841 .child(Label::new("Jump to Edit").size(LabelSize::Small))
2842 .child(
2843 icon_container
2844 .child(Icon::new(IconName::ArrowDown).size(IconSize::Small)),
2845 )
2846 .into_any();
2847 let size = element.layout_as_root(AvailableSpace::min_size(), cx);
2848 let offset = point(
2849 (text_bounds.size.width - size.width) / 2.,
2850 text_bounds.size.height - size.height - PADDING_Y,
2851 );
2852 element.prepaint_at(text_bounds.origin + offset, cx);
2853 Some(element)
2854 } else {
2855 let mut element = container_element
2856 .child(tab_kbd)
2857 .child(Label::new("Jump to Edit").size(LabelSize::Small))
2858 .into_any();
2859
2860 let target_line_end = DisplayPoint::new(
2861 target_display_point.row(),
2862 editor_snapshot.line_len(target_display_point.row()),
2863 );
2864 let origin = self.editor.update(cx, |editor, cx| {
2865 editor.display_to_pixel_point(target_line_end, editor_snapshot, cx)
2866 })?;
2867 element.prepaint_as_root(
2868 text_bounds.origin + origin + point(PADDING_X, px(0.)),
2869 AvailableSpace::min_size(),
2870 cx,
2871 );
2872 Some(element)
2873 }
2874 }
2875 InlineCompletion::Edit(edits) => {
2876 let edit_start = edits
2877 .first()
2878 .unwrap()
2879 .0
2880 .start
2881 .to_display_point(editor_snapshot);
2882 let edit_end = edits
2883 .last()
2884 .unwrap()
2885 .0
2886 .end
2887 .to_display_point(editor_snapshot);
2888
2889 let is_visible = visible_row_range.contains(&edit_start.row())
2890 || visible_row_range.contains(&edit_end.row());
2891 if !is_visible {
2892 return None;
2893 }
2894
2895 if all_edits_insertions_or_deletions(edits, &editor_snapshot.buffer_snapshot) {
2896 return None;
2897 }
2898
2899 let (text, highlights) = inline_completion_popover_text(editor_snapshot, edits, cx);
2900 let line_count = text.lines().count() + 1;
2901
2902 let longest_row =
2903 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
2904 let longest_line_width = if visible_row_range.contains(&longest_row) {
2905 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
2906 } else {
2907 layout_line(
2908 longest_row,
2909 editor_snapshot,
2910 style,
2911 editor_width,
2912 |_| false,
2913 cx,
2914 )
2915 .width
2916 };
2917
2918 let styled_text =
2919 gpui::StyledText::new(text).with_highlights(&style.text, highlights);
2920
2921 let mut element = div()
2922 .bg(cx.theme().colors().editor_background)
2923 .border_1()
2924 .border_color(cx.theme().colors().border)
2925 .rounded_md()
2926 .px_1()
2927 .child(styled_text)
2928 .into_any();
2929
2930 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), cx);
2931 let is_fully_visible =
2932 editor_width >= longest_line_width + PADDING_X + element_bounds.width;
2933
2934 let origin = if is_fully_visible {
2935 text_bounds.origin
2936 + point(
2937 longest_line_width + PADDING_X - scroll_pixel_position.x,
2938 edit_start.row().as_f32() * line_height - scroll_pixel_position.y,
2939 )
2940 } else {
2941 let target_above =
2942 DisplayRow(edit_start.row().0.saturating_sub(line_count as u32));
2943 let row_target = if visible_row_range
2944 .contains(&DisplayRow(target_above.0.saturating_sub(1)))
2945 {
2946 target_above
2947 } else {
2948 DisplayRow(edit_end.row().0 + 1)
2949 };
2950
2951 text_bounds.origin
2952 + point(
2953 -scroll_pixel_position.x,
2954 row_target.as_f32() * line_height - scroll_pixel_position.y,
2955 )
2956 };
2957
2958 element.prepaint_as_root(origin, element_bounds.into(), cx);
2959 Some(element)
2960 }
2961 }
2962 }
2963
2964 fn layout_mouse_context_menu(
2965 &self,
2966 editor_snapshot: &EditorSnapshot,
2967 visible_range: Range<DisplayRow>,
2968 content_origin: gpui::Point<Pixels>,
2969 cx: &mut WindowContext,
2970 ) -> Option<AnyElement> {
2971 let position = self.editor.update(cx, |editor, cx| {
2972 let visible_start_point = editor.display_to_pixel_point(
2973 DisplayPoint::new(visible_range.start, 0),
2974 editor_snapshot,
2975 cx,
2976 )?;
2977 let visible_end_point = editor.display_to_pixel_point(
2978 DisplayPoint::new(visible_range.end, 0),
2979 editor_snapshot,
2980 cx,
2981 )?;
2982
2983 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
2984 let (source_display_point, position) = match mouse_context_menu.position {
2985 MenuPosition::PinnedToScreen(point) => (None, point),
2986 MenuPosition::PinnedToEditor { source, offset } => {
2987 let source_display_point = source.to_display_point(editor_snapshot);
2988 let source_point = editor.to_pixel_point(source, editor_snapshot, cx)?;
2989 let position = content_origin + source_point + offset;
2990 (Some(source_display_point), position)
2991 }
2992 };
2993
2994 let source_included = source_display_point.map_or(true, |source_display_point| {
2995 visible_range
2996 .to_inclusive()
2997 .contains(&source_display_point.row())
2998 });
2999 let position_included =
3000 visible_start_point.y <= position.y && position.y <= visible_end_point.y;
3001 if !source_included && !position_included {
3002 None
3003 } else {
3004 Some(position)
3005 }
3006 })?;
3007
3008 let mut element = self.editor.update(cx, |editor, _| {
3009 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
3010 let context_menu = mouse_context_menu.context_menu.clone();
3011
3012 Some(
3013 deferred(
3014 anchored()
3015 .position(position)
3016 .child(context_menu)
3017 .anchor(AnchorCorner::TopLeft)
3018 .snap_to_window_with_margin(px(8.)),
3019 )
3020 .with_priority(1)
3021 .into_any(),
3022 )
3023 })?;
3024
3025 element.prepaint_as_root(position, AvailableSpace::min_size(), cx);
3026 Some(element)
3027 }
3028
3029 #[allow(clippy::too_many_arguments)]
3030 fn layout_hover_popovers(
3031 &self,
3032 snapshot: &EditorSnapshot,
3033 hitbox: &Hitbox,
3034 text_hitbox: &Hitbox,
3035 visible_display_row_range: Range<DisplayRow>,
3036 content_origin: gpui::Point<Pixels>,
3037 scroll_pixel_position: gpui::Point<Pixels>,
3038 line_layouts: &[LineWithInvisibles],
3039 line_height: Pixels,
3040 em_width: Pixels,
3041 cx: &mut WindowContext,
3042 ) {
3043 struct MeasuredHoverPopover {
3044 element: AnyElement,
3045 size: Size<Pixels>,
3046 horizontal_offset: Pixels,
3047 }
3048
3049 let max_size = size(
3050 (120. * em_width) // Default size
3051 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
3052 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
3053 (16. * line_height) // Default size
3054 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
3055 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
3056 );
3057
3058 let hover_popovers = self.editor.update(cx, |editor, cx| {
3059 editor
3060 .hover_state
3061 .render(snapshot, visible_display_row_range.clone(), max_size, cx)
3062 });
3063 let Some((position, hover_popovers)) = hover_popovers else {
3064 return;
3065 };
3066
3067 // This is safe because we check on layout whether the required row is available
3068 let hovered_row_layout =
3069 &line_layouts[position.row().minus(visible_display_row_range.start) as usize];
3070
3071 // Compute Hovered Point
3072 let x =
3073 hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
3074 let y = position.row().as_f32() * line_height - scroll_pixel_position.y;
3075 let hovered_point = content_origin + point(x, y);
3076
3077 let mut overall_height = Pixels::ZERO;
3078 let mut measured_hover_popovers = Vec::new();
3079 for mut hover_popover in hover_popovers {
3080 let size = hover_popover.layout_as_root(AvailableSpace::min_size(), cx);
3081 let horizontal_offset =
3082 (text_hitbox.upper_right().x - (hovered_point.x + size.width)).min(Pixels::ZERO);
3083
3084 overall_height += HOVER_POPOVER_GAP + size.height;
3085
3086 measured_hover_popovers.push(MeasuredHoverPopover {
3087 element: hover_popover,
3088 size,
3089 horizontal_offset,
3090 });
3091 }
3092 overall_height += HOVER_POPOVER_GAP;
3093
3094 fn draw_occluder(width: Pixels, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
3095 let mut occlusion = div()
3096 .size_full()
3097 .occlude()
3098 .on_mouse_move(|_, cx| cx.stop_propagation())
3099 .into_any_element();
3100 occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), cx);
3101 cx.defer_draw(occlusion, origin, 2);
3102 }
3103
3104 if hovered_point.y > overall_height {
3105 // There is enough space above. Render popovers above the hovered point
3106 let mut current_y = hovered_point.y;
3107 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
3108 let size = popover.size;
3109 let popover_origin = point(
3110 hovered_point.x + popover.horizontal_offset,
3111 current_y - size.height,
3112 );
3113
3114 cx.defer_draw(popover.element, popover_origin, 2);
3115 if position != itertools::Position::Last {
3116 let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
3117 draw_occluder(size.width, origin, cx);
3118 }
3119
3120 current_y = popover_origin.y - HOVER_POPOVER_GAP;
3121 }
3122 } else {
3123 // There is not enough space above. Render popovers below the hovered point
3124 let mut current_y = hovered_point.y + line_height;
3125 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
3126 let size = popover.size;
3127 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
3128
3129 cx.defer_draw(popover.element, popover_origin, 2);
3130 if position != itertools::Position::Last {
3131 let origin = point(popover_origin.x, popover_origin.y + size.height);
3132 draw_occluder(size.width, origin, cx);
3133 }
3134
3135 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
3136 }
3137 }
3138 }
3139
3140 #[allow(clippy::too_many_arguments)]
3141 fn layout_signature_help(
3142 &self,
3143 hitbox: &Hitbox,
3144 content_origin: gpui::Point<Pixels>,
3145 scroll_pixel_position: gpui::Point<Pixels>,
3146 newest_selection_head: Option<DisplayPoint>,
3147 start_row: DisplayRow,
3148 line_layouts: &[LineWithInvisibles],
3149 line_height: Pixels,
3150 em_width: Pixels,
3151 cx: &mut WindowContext,
3152 ) {
3153 if !self.editor.focus_handle(cx).is_focused(cx) {
3154 return;
3155 }
3156 let Some(newest_selection_head) = newest_selection_head else {
3157 return;
3158 };
3159 let selection_row = newest_selection_head.row();
3160 if selection_row < start_row {
3161 return;
3162 }
3163 let Some(cursor_row_layout) = line_layouts.get(selection_row.minus(start_row) as usize)
3164 else {
3165 return;
3166 };
3167
3168 let start_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
3169 - scroll_pixel_position.x
3170 + content_origin.x;
3171 let start_y =
3172 selection_row.as_f32() * line_height + content_origin.y - scroll_pixel_position.y;
3173
3174 let max_size = size(
3175 (120. * em_width) // Default size
3176 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
3177 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
3178 (16. * line_height) // Default size
3179 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
3180 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
3181 );
3182
3183 let maybe_element = self.editor.update(cx, |editor, cx| {
3184 if let Some(popover) = editor.signature_help_state.popover_mut() {
3185 let element = popover.render(
3186 &self.style,
3187 max_size,
3188 editor.workspace.as_ref().map(|(w, _)| w.clone()),
3189 cx,
3190 );
3191 Some(element)
3192 } else {
3193 None
3194 }
3195 });
3196 if let Some(mut element) = maybe_element {
3197 let window_size = cx.viewport_size();
3198 let size = element.layout_as_root(Size::<AvailableSpace>::default(), cx);
3199 let mut point = point(start_x, start_y - size.height);
3200
3201 // Adjusting to ensure the popover does not overflow in the X-axis direction.
3202 if point.x + size.width >= window_size.width {
3203 point.x = window_size.width - size.width;
3204 }
3205
3206 cx.defer_draw(element, point, 1)
3207 }
3208 }
3209
3210 fn paint_background(&self, layout: &EditorLayout, cx: &mut WindowContext) {
3211 cx.paint_layer(layout.hitbox.bounds, |cx| {
3212 let scroll_top = layout.position_map.snapshot.scroll_position().y;
3213 let gutter_bg = cx.theme().colors().editor_gutter_background;
3214 cx.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
3215 cx.paint_quad(fill(layout.text_hitbox.bounds, self.style.background));
3216
3217 if let EditorMode::Full = layout.mode {
3218 let mut active_rows = layout.active_rows.iter().peekable();
3219 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
3220 let mut end_row = start_row.0;
3221 while active_rows
3222 .peek()
3223 .map_or(false, |(active_row, has_selection)| {
3224 active_row.0 == end_row + 1
3225 && *has_selection == contains_non_empty_selection
3226 })
3227 {
3228 active_rows.next().unwrap();
3229 end_row += 1;
3230 }
3231
3232 if !contains_non_empty_selection {
3233 let highlight_h_range =
3234 match layout.position_map.snapshot.current_line_highlight {
3235 CurrentLineHighlight::Gutter => Some(Range {
3236 start: layout.hitbox.left(),
3237 end: layout.gutter_hitbox.right(),
3238 }),
3239 CurrentLineHighlight::Line => Some(Range {
3240 start: layout.text_hitbox.bounds.left(),
3241 end: layout.text_hitbox.bounds.right(),
3242 }),
3243 CurrentLineHighlight::All => Some(Range {
3244 start: layout.hitbox.left(),
3245 end: layout.hitbox.right(),
3246 }),
3247 CurrentLineHighlight::None => None,
3248 };
3249 if let Some(range) = highlight_h_range {
3250 let active_line_bg = cx.theme().colors().editor_active_line_background;
3251 let bounds = Bounds {
3252 origin: point(
3253 range.start,
3254 layout.hitbox.origin.y
3255 + (start_row.as_f32() - scroll_top)
3256 * layout.position_map.line_height,
3257 ),
3258 size: size(
3259 range.end - range.start,
3260 layout.position_map.line_height
3261 * (end_row - start_row.0 + 1) as f32,
3262 ),
3263 };
3264 cx.paint_quad(fill(bounds, active_line_bg));
3265 }
3266 }
3267 }
3268
3269 let mut paint_highlight =
3270 |highlight_row_start: DisplayRow, highlight_row_end: DisplayRow, color| {
3271 let origin = point(
3272 layout.hitbox.origin.x,
3273 layout.hitbox.origin.y
3274 + (highlight_row_start.as_f32() - scroll_top)
3275 * layout.position_map.line_height,
3276 );
3277 let size = size(
3278 layout.hitbox.size.width,
3279 layout.position_map.line_height
3280 * highlight_row_end.next_row().minus(highlight_row_start) as f32,
3281 );
3282 cx.paint_quad(fill(Bounds { origin, size }, color));
3283 };
3284
3285 let mut current_paint: Option<(Hsla, Range<DisplayRow>)> = None;
3286 for (&new_row, &new_color) in &layout.highlighted_rows {
3287 match &mut current_paint {
3288 Some((current_color, current_range)) => {
3289 let current_color = *current_color;
3290 let new_range_started = current_color != new_color
3291 || current_range.end.next_row() != new_row;
3292 if new_range_started {
3293 paint_highlight(
3294 current_range.start,
3295 current_range.end,
3296 current_color,
3297 );
3298 current_paint = Some((new_color, new_row..new_row));
3299 continue;
3300 } else {
3301 current_range.end = current_range.end.next_row();
3302 }
3303 }
3304 None => current_paint = Some((new_color, new_row..new_row)),
3305 };
3306 }
3307 if let Some((color, range)) = current_paint {
3308 paint_highlight(range.start, range.end, color);
3309 }
3310
3311 let scroll_left =
3312 layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
3313
3314 for (wrap_position, active) in layout.wrap_guides.iter() {
3315 let x = (layout.text_hitbox.origin.x
3316 + *wrap_position
3317 + layout.position_map.em_width / 2.)
3318 - scroll_left;
3319
3320 let show_scrollbars = layout
3321 .scrollbar_layout
3322 .as_ref()
3323 .map_or(false, |scrollbar| scrollbar.visible);
3324 if x < layout.text_hitbox.origin.x
3325 || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
3326 {
3327 continue;
3328 }
3329
3330 let color = if *active {
3331 cx.theme().colors().editor_active_wrap_guide
3332 } else {
3333 cx.theme().colors().editor_wrap_guide
3334 };
3335 cx.paint_quad(fill(
3336 Bounds {
3337 origin: point(x, layout.text_hitbox.origin.y),
3338 size: size(px(1.), layout.text_hitbox.size.height),
3339 },
3340 color,
3341 ));
3342 }
3343 }
3344 })
3345 }
3346
3347 fn paint_indent_guides(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3348 let Some(indent_guides) = &layout.indent_guides else {
3349 return;
3350 };
3351
3352 let faded_color = |color: Hsla, alpha: f32| {
3353 let mut faded = color;
3354 faded.a = alpha;
3355 faded
3356 };
3357
3358 for indent_guide in indent_guides {
3359 let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
3360 let settings = indent_guide.settings;
3361
3362 // TODO fixed for now, expose them through themes later
3363 const INDENT_AWARE_ALPHA: f32 = 0.2;
3364 const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
3365 const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
3366 const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
3367
3368 let line_color = match (settings.coloring, indent_guide.active) {
3369 (IndentGuideColoring::Disabled, _) => None,
3370 (IndentGuideColoring::Fixed, false) => {
3371 Some(cx.theme().colors().editor_indent_guide)
3372 }
3373 (IndentGuideColoring::Fixed, true) => {
3374 Some(cx.theme().colors().editor_indent_guide_active)
3375 }
3376 (IndentGuideColoring::IndentAware, false) => {
3377 Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
3378 }
3379 (IndentGuideColoring::IndentAware, true) => {
3380 Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
3381 }
3382 };
3383
3384 let background_color = match (settings.background_coloring, indent_guide.active) {
3385 (IndentGuideBackgroundColoring::Disabled, _) => None,
3386 (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
3387 indent_accent_colors,
3388 INDENT_AWARE_BACKGROUND_ALPHA,
3389 )),
3390 (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
3391 indent_accent_colors,
3392 INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
3393 )),
3394 };
3395
3396 let requested_line_width = if indent_guide.active {
3397 settings.active_line_width
3398 } else {
3399 settings.line_width
3400 }
3401 .clamp(1, 10);
3402 let mut line_indicator_width = 0.;
3403 if let Some(color) = line_color {
3404 cx.paint_quad(fill(
3405 Bounds {
3406 origin: indent_guide.origin,
3407 size: size(px(requested_line_width as f32), indent_guide.length),
3408 },
3409 color,
3410 ));
3411 line_indicator_width = requested_line_width as f32;
3412 }
3413
3414 if let Some(color) = background_color {
3415 let width = indent_guide.single_indent_width - px(line_indicator_width);
3416 cx.paint_quad(fill(
3417 Bounds {
3418 origin: point(
3419 indent_guide.origin.x + px(line_indicator_width),
3420 indent_guide.origin.y,
3421 ),
3422 size: size(width, indent_guide.length),
3423 },
3424 color,
3425 ));
3426 }
3427 }
3428 }
3429
3430 fn paint_line_numbers(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3431 let line_height = layout.position_map.line_height;
3432 let scroll_position = layout.position_map.snapshot.scroll_position();
3433 let scroll_top = scroll_position.y * line_height;
3434
3435 cx.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
3436
3437 for (ix, line) in layout.line_numbers.iter().enumerate() {
3438 if let Some(line) = line {
3439 let line_origin = layout.gutter_hitbox.origin
3440 + point(
3441 layout.gutter_hitbox.size.width
3442 - line.width
3443 - layout.gutter_dimensions.right_padding,
3444 ix as f32 * line_height - (scroll_top % line_height),
3445 );
3446
3447 line.paint(line_origin, line_height, cx).log_err();
3448 }
3449 }
3450 }
3451
3452 fn paint_diff_hunks(layout: &mut EditorLayout, cx: &mut WindowContext) {
3453 if layout.display_hunks.is_empty() {
3454 return;
3455 }
3456
3457 let line_height = layout.position_map.line_height;
3458 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3459 for (hunk, hitbox) in &layout.display_hunks {
3460 let hunk_to_paint = match hunk {
3461 DisplayDiffHunk::Folded { .. } => {
3462 let hunk_bounds = Self::diff_hunk_bounds(
3463 &layout.position_map.snapshot,
3464 line_height,
3465 layout.gutter_hitbox.bounds,
3466 hunk,
3467 );
3468 Some((
3469 hunk_bounds,
3470 cx.theme().status().modified,
3471 Corners::all(px(0.)),
3472 ))
3473 }
3474 DisplayDiffHunk::Unfolded { status, .. } => {
3475 hitbox.as_ref().map(|hunk_hitbox| match status {
3476 DiffHunkStatus::Added => (
3477 hunk_hitbox.bounds,
3478 cx.theme().status().created,
3479 Corners::all(px(0.)),
3480 ),
3481 DiffHunkStatus::Modified => (
3482 hunk_hitbox.bounds,
3483 cx.theme().status().modified,
3484 Corners::all(px(0.)),
3485 ),
3486 DiffHunkStatus::Removed => (
3487 Bounds::new(
3488 point(
3489 hunk_hitbox.origin.x - hunk_hitbox.size.width,
3490 hunk_hitbox.origin.y,
3491 ),
3492 size(hunk_hitbox.size.width * px(2.), hunk_hitbox.size.height),
3493 ),
3494 cx.theme().status().deleted,
3495 Corners::all(1. * line_height),
3496 ),
3497 })
3498 }
3499 };
3500
3501 if let Some((hunk_bounds, background_color, corner_radii)) = hunk_to_paint {
3502 cx.paint_quad(quad(
3503 hunk_bounds,
3504 corner_radii,
3505 background_color,
3506 Edges::default(),
3507 transparent_black(),
3508 ));
3509 }
3510 }
3511 });
3512 }
3513
3514 pub(super) fn diff_hunk_bounds(
3515 snapshot: &EditorSnapshot,
3516 line_height: Pixels,
3517 gutter_bounds: Bounds<Pixels>,
3518 hunk: &DisplayDiffHunk,
3519 ) -> Bounds<Pixels> {
3520 let scroll_position = snapshot.scroll_position();
3521 let scroll_top = scroll_position.y * line_height;
3522
3523 match hunk {
3524 DisplayDiffHunk::Folded { display_row, .. } => {
3525 let start_y = display_row.as_f32() * line_height - scroll_top;
3526 let end_y = start_y + line_height;
3527
3528 let width = Self::diff_hunk_strip_width(line_height);
3529 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
3530 let highlight_size = size(width, end_y - start_y);
3531 Bounds::new(highlight_origin, highlight_size)
3532 }
3533 DisplayDiffHunk::Unfolded {
3534 display_row_range,
3535 status,
3536 ..
3537 } => match status {
3538 DiffHunkStatus::Added | DiffHunkStatus::Modified => {
3539 let start_row = display_row_range.start;
3540 let end_row = display_row_range.end;
3541 // If we're in a multibuffer, row range span might include an
3542 // excerpt header, so if we were to draw the marker straight away,
3543 // the hunk might include the rows of that header.
3544 // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
3545 // Instead, we simply check whether the range we're dealing with includes
3546 // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
3547 let end_row_in_current_excerpt = snapshot
3548 .blocks_in_range(start_row..end_row)
3549 .find_map(|(start_row, block)| {
3550 if matches!(block, Block::ExcerptBoundary { .. }) {
3551 Some(start_row)
3552 } else {
3553 None
3554 }
3555 })
3556 .unwrap_or(end_row);
3557
3558 let start_y = start_row.as_f32() * line_height - scroll_top;
3559 let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
3560
3561 let width = Self::diff_hunk_strip_width(line_height);
3562 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
3563 let highlight_size = size(width, end_y - start_y);
3564 Bounds::new(highlight_origin, highlight_size)
3565 }
3566 DiffHunkStatus::Removed => {
3567 let row = display_row_range.start;
3568
3569 let offset = line_height / 2.;
3570 let start_y = row.as_f32() * line_height - offset - scroll_top;
3571 let end_y = start_y + line_height;
3572
3573 let width = (0.35 * line_height).floor();
3574 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
3575 let highlight_size = size(width, end_y - start_y);
3576 Bounds::new(highlight_origin, highlight_size)
3577 }
3578 },
3579 }
3580 }
3581
3582 /// Returns the width of the diff strip that will be displayed in the gutter.
3583 pub(super) fn diff_hunk_strip_width(line_height: Pixels) -> Pixels {
3584 // We floor the value to prevent pixel rounding.
3585 (0.275 * line_height).floor()
3586 }
3587
3588 fn paint_gutter_indicators(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3589 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3590 cx.with_element_namespace("crease_toggles", |cx| {
3591 for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
3592 crease_toggle.paint(cx);
3593 }
3594 });
3595
3596 for test_indicator in layout.test_indicators.iter_mut() {
3597 test_indicator.paint(cx);
3598 }
3599
3600 if let Some(indicator) = layout.code_actions_indicator.as_mut() {
3601 indicator.paint(cx);
3602 }
3603 });
3604 }
3605
3606 fn paint_gutter_highlights(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3607 for (_, hunk_hitbox) in &layout.display_hunks {
3608 if let Some(hunk_hitbox) = hunk_hitbox {
3609 cx.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
3610 }
3611 }
3612
3613 let show_git_gutter = layout
3614 .position_map
3615 .snapshot
3616 .show_git_diff_gutter
3617 .unwrap_or_else(|| {
3618 matches!(
3619 ProjectSettings::get_global(cx).git.git_gutter,
3620 Some(GitGutterSetting::TrackedFiles)
3621 )
3622 });
3623 if show_git_gutter {
3624 Self::paint_diff_hunks(layout, cx)
3625 }
3626
3627 let highlight_width = 0.275 * layout.position_map.line_height;
3628 let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
3629 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3630 for (range, color) in &layout.highlighted_gutter_ranges {
3631 let start_row = if range.start.row() < layout.visible_display_row_range.start {
3632 layout.visible_display_row_range.start - DisplayRow(1)
3633 } else {
3634 range.start.row()
3635 };
3636 let end_row = if range.end.row() > layout.visible_display_row_range.end {
3637 layout.visible_display_row_range.end + DisplayRow(1)
3638 } else {
3639 range.end.row()
3640 };
3641
3642 let start_y = layout.gutter_hitbox.top()
3643 + start_row.0 as f32 * layout.position_map.line_height
3644 - layout.position_map.scroll_pixel_position.y;
3645 let end_y = layout.gutter_hitbox.top()
3646 + (end_row.0 + 1) as f32 * layout.position_map.line_height
3647 - layout.position_map.scroll_pixel_position.y;
3648 let bounds = Bounds::from_corners(
3649 point(layout.gutter_hitbox.left(), start_y),
3650 point(layout.gutter_hitbox.left() + highlight_width, end_y),
3651 );
3652 cx.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
3653 }
3654 });
3655 }
3656
3657 fn paint_blamed_display_rows(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3658 let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
3659 return;
3660 };
3661
3662 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3663 for mut blame_element in blamed_display_rows.into_iter() {
3664 blame_element.paint(cx);
3665 }
3666 })
3667 }
3668
3669 fn paint_text(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3670 cx.with_content_mask(
3671 Some(ContentMask {
3672 bounds: layout.text_hitbox.bounds,
3673 }),
3674 |cx| {
3675 let cursor_style = if self
3676 .editor
3677 .read(cx)
3678 .hovered_link_state
3679 .as_ref()
3680 .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
3681 {
3682 CursorStyle::PointingHand
3683 } else {
3684 CursorStyle::IBeam
3685 };
3686 cx.set_cursor_style(cursor_style, &layout.text_hitbox);
3687
3688 let invisible_display_ranges = self.paint_highlights(layout, cx);
3689 self.paint_lines(&invisible_display_ranges, layout, cx);
3690 self.paint_redactions(layout, cx);
3691 self.paint_cursors(layout, cx);
3692 self.paint_inline_blame(layout, cx);
3693 cx.with_element_namespace("crease_trailers", |cx| {
3694 for trailer in layout.crease_trailers.iter_mut().flatten() {
3695 trailer.element.paint(cx);
3696 }
3697 });
3698 },
3699 )
3700 }
3701
3702 fn paint_highlights(
3703 &mut self,
3704 layout: &mut EditorLayout,
3705 cx: &mut WindowContext,
3706 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
3707 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3708 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
3709 let line_end_overshoot = 0.15 * layout.position_map.line_height;
3710 for (range, color) in &layout.highlighted_ranges {
3711 self.paint_highlighted_range(
3712 range.clone(),
3713 *color,
3714 Pixels::ZERO,
3715 line_end_overshoot,
3716 layout,
3717 cx,
3718 );
3719 }
3720
3721 let corner_radius = 0.15 * layout.position_map.line_height;
3722
3723 for (player_color, selections) in &layout.selections {
3724 for selection in selections.iter() {
3725 self.paint_highlighted_range(
3726 selection.range.clone(),
3727 player_color.selection,
3728 corner_radius,
3729 corner_radius * 2.,
3730 layout,
3731 cx,
3732 );
3733
3734 if selection.is_local && !selection.range.is_empty() {
3735 invisible_display_ranges.push(selection.range.clone());
3736 }
3737 }
3738 }
3739 invisible_display_ranges
3740 })
3741 }
3742
3743 fn paint_lines(
3744 &mut self,
3745 invisible_display_ranges: &[Range<DisplayPoint>],
3746 layout: &mut EditorLayout,
3747 cx: &mut WindowContext,
3748 ) {
3749 let whitespace_setting = self
3750 .editor
3751 .read(cx)
3752 .buffer
3753 .read(cx)
3754 .settings_at(0, cx)
3755 .show_whitespaces;
3756
3757 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
3758 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
3759 line_with_invisibles.draw(
3760 layout,
3761 row,
3762 layout.content_origin,
3763 whitespace_setting,
3764 invisible_display_ranges,
3765 cx,
3766 )
3767 }
3768
3769 for line_element in &mut layout.line_elements {
3770 line_element.paint(cx);
3771 }
3772 }
3773
3774 fn paint_redactions(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
3775 if layout.redacted_ranges.is_empty() {
3776 return;
3777 }
3778
3779 let line_end_overshoot = layout.line_end_overshoot();
3780
3781 // A softer than perfect black
3782 let redaction_color = gpui::rgb(0x0e1111);
3783
3784 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3785 for range in layout.redacted_ranges.iter() {
3786 self.paint_highlighted_range(
3787 range.clone(),
3788 redaction_color.into(),
3789 Pixels::ZERO,
3790 line_end_overshoot,
3791 layout,
3792 cx,
3793 );
3794 }
3795 });
3796 }
3797
3798 fn paint_cursors(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3799 for cursor in &mut layout.visible_cursors {
3800 cursor.paint(layout.content_origin, cx);
3801 }
3802 }
3803
3804 fn paint_scrollbar(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3805 let Some(scrollbar_layout) = layout.scrollbar_layout.as_ref() else {
3806 return;
3807 };
3808
3809 let thumb_bounds = scrollbar_layout.thumb_bounds();
3810 if scrollbar_layout.visible {
3811 cx.paint_layer(scrollbar_layout.hitbox.bounds, |cx| {
3812 cx.paint_quad(quad(
3813 scrollbar_layout.hitbox.bounds,
3814 Corners::default(),
3815 cx.theme().colors().scrollbar_track_background,
3816 Edges {
3817 top: Pixels::ZERO,
3818 right: Pixels::ZERO,
3819 bottom: Pixels::ZERO,
3820 left: ScrollbarLayout::BORDER_WIDTH,
3821 },
3822 cx.theme().colors().scrollbar_track_border,
3823 ));
3824
3825 let fast_markers =
3826 self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
3827 // Refresh slow scrollbar markers in the background. Below, we paint whatever markers have already been computed.
3828 self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, cx);
3829
3830 let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
3831 for marker in markers.iter().chain(&fast_markers) {
3832 let mut marker = marker.clone();
3833 marker.bounds.origin += scrollbar_layout.hitbox.origin;
3834 cx.paint_quad(marker);
3835 }
3836
3837 cx.paint_quad(quad(
3838 thumb_bounds,
3839 Corners::default(),
3840 cx.theme().colors().scrollbar_thumb_background,
3841 Edges {
3842 top: Pixels::ZERO,
3843 right: Pixels::ZERO,
3844 bottom: Pixels::ZERO,
3845 left: ScrollbarLayout::BORDER_WIDTH,
3846 },
3847 cx.theme().colors().scrollbar_thumb_border,
3848 ));
3849 });
3850 }
3851
3852 cx.set_cursor_style(CursorStyle::Arrow, &scrollbar_layout.hitbox);
3853
3854 let row_height = scrollbar_layout.row_height;
3855 let row_range = scrollbar_layout.visible_row_range.clone();
3856
3857 cx.on_mouse_event({
3858 let editor = self.editor.clone();
3859 let hitbox = scrollbar_layout.hitbox.clone();
3860 let mut mouse_position = cx.mouse_position();
3861 move |event: &MouseMoveEvent, phase, cx| {
3862 if phase == DispatchPhase::Capture {
3863 return;
3864 }
3865
3866 editor.update(cx, |editor, cx| {
3867 if event.pressed_button == Some(MouseButton::Left)
3868 && editor.scroll_manager.is_dragging_scrollbar()
3869 {
3870 let y = mouse_position.y;
3871 let new_y = event.position.y;
3872 if (hitbox.top()..hitbox.bottom()).contains(&y) {
3873 let mut position = editor.scroll_position(cx);
3874 position.y += (new_y - y) / row_height;
3875 if position.y < 0.0 {
3876 position.y = 0.0;
3877 }
3878 editor.set_scroll_position(position, cx);
3879 }
3880
3881 cx.stop_propagation();
3882 } else {
3883 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
3884 if hitbox.is_hovered(cx) {
3885 editor.scroll_manager.show_scrollbar(cx);
3886 }
3887 }
3888 mouse_position = event.position;
3889 })
3890 }
3891 });
3892
3893 if self.editor.read(cx).scroll_manager.is_dragging_scrollbar() {
3894 cx.on_mouse_event({
3895 let editor = self.editor.clone();
3896 move |_: &MouseUpEvent, phase, cx| {
3897 if phase == DispatchPhase::Capture {
3898 return;
3899 }
3900
3901 editor.update(cx, |editor, cx| {
3902 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
3903 cx.stop_propagation();
3904 });
3905 }
3906 });
3907 } else {
3908 cx.on_mouse_event({
3909 let editor = self.editor.clone();
3910 let hitbox = scrollbar_layout.hitbox.clone();
3911 move |event: &MouseDownEvent, phase, cx| {
3912 if phase == DispatchPhase::Capture || !hitbox.is_hovered(cx) {
3913 return;
3914 }
3915
3916 editor.update(cx, |editor, cx| {
3917 editor.scroll_manager.set_is_dragging_scrollbar(true, cx);
3918
3919 let y = event.position.y;
3920 if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
3921 let center_row = ((y - hitbox.top()) / row_height).round() as u32;
3922 let top_row = center_row
3923 .saturating_sub((row_range.end - row_range.start) as u32 / 2);
3924 let mut position = editor.scroll_position(cx);
3925 position.y = top_row as f32;
3926 editor.set_scroll_position(position, cx);
3927 } else {
3928 editor.scroll_manager.show_scrollbar(cx);
3929 }
3930
3931 cx.stop_propagation();
3932 });
3933 }
3934 });
3935 }
3936 }
3937
3938 fn collect_fast_scrollbar_markers(
3939 &self,
3940 layout: &EditorLayout,
3941 scrollbar_layout: &ScrollbarLayout,
3942 cx: &mut WindowContext,
3943 ) -> Vec<PaintQuad> {
3944 const LIMIT: usize = 100;
3945 if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
3946 return vec![];
3947 }
3948 let cursor_ranges = layout
3949 .cursors
3950 .iter()
3951 .map(|(point, color)| ColoredRange {
3952 start: point.row(),
3953 end: point.row(),
3954 color: *color,
3955 })
3956 .collect_vec();
3957 scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
3958 }
3959
3960 fn refresh_slow_scrollbar_markers(
3961 &self,
3962 layout: &EditorLayout,
3963 scrollbar_layout: &ScrollbarLayout,
3964 cx: &mut WindowContext,
3965 ) {
3966 self.editor.update(cx, |editor, cx| {
3967 if !editor.is_singleton(cx)
3968 || !editor
3969 .scrollbar_marker_state
3970 .should_refresh(scrollbar_layout.hitbox.size)
3971 {
3972 return;
3973 }
3974
3975 let scrollbar_layout = scrollbar_layout.clone();
3976 let background_highlights = editor.background_highlights.clone();
3977 let snapshot = layout.position_map.snapshot.clone();
3978 let theme = cx.theme().clone();
3979 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
3980
3981 editor.scrollbar_marker_state.dirty = false;
3982 editor.scrollbar_marker_state.pending_refresh =
3983 Some(cx.spawn(|editor, mut cx| async move {
3984 let scrollbar_size = scrollbar_layout.hitbox.size;
3985 let scrollbar_markers = cx
3986 .background_executor()
3987 .spawn(async move {
3988 let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
3989 let mut marker_quads = Vec::new();
3990 if scrollbar_settings.git_diff {
3991 let marker_row_ranges = snapshot
3992 .diff_map
3993 .diff_hunks(&snapshot.buffer_snapshot)
3994 .map(|hunk| {
3995 let start_display_row =
3996 MultiBufferPoint::new(hunk.row_range.start.0, 0)
3997 .to_display_point(&snapshot.display_snapshot)
3998 .row();
3999 let mut end_display_row =
4000 MultiBufferPoint::new(hunk.row_range.end.0, 0)
4001 .to_display_point(&snapshot.display_snapshot)
4002 .row();
4003 if end_display_row != start_display_row {
4004 end_display_row.0 -= 1;
4005 }
4006 let color = match hunk_status(&hunk) {
4007 DiffHunkStatus::Added => theme.status().created,
4008 DiffHunkStatus::Modified => theme.status().modified,
4009 DiffHunkStatus::Removed => theme.status().deleted,
4010 };
4011 ColoredRange {
4012 start: start_display_row,
4013 end: end_display_row,
4014 color,
4015 }
4016 });
4017
4018 marker_quads.extend(
4019 scrollbar_layout
4020 .marker_quads_for_ranges(marker_row_ranges, Some(0)),
4021 );
4022 }
4023
4024 for (background_highlight_id, (_, background_ranges)) in
4025 background_highlights.iter()
4026 {
4027 let is_search_highlights = *background_highlight_id
4028 == TypeId::of::<BufferSearchHighlights>();
4029 let is_symbol_occurrences = *background_highlight_id
4030 == TypeId::of::<DocumentHighlightRead>()
4031 || *background_highlight_id
4032 == TypeId::of::<DocumentHighlightWrite>();
4033 if (is_search_highlights && scrollbar_settings.search_results)
4034 || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
4035 {
4036 let mut color = theme.status().info;
4037 if is_symbol_occurrences {
4038 color.fade_out(0.5);
4039 }
4040 let marker_row_ranges = background_ranges.iter().map(|range| {
4041 let display_start = range
4042 .start
4043 .to_display_point(&snapshot.display_snapshot);
4044 let display_end =
4045 range.end.to_display_point(&snapshot.display_snapshot);
4046 ColoredRange {
4047 start: display_start.row(),
4048 end: display_end.row(),
4049 color,
4050 }
4051 });
4052 marker_quads.extend(
4053 scrollbar_layout
4054 .marker_quads_for_ranges(marker_row_ranges, Some(1)),
4055 );
4056 }
4057 }
4058
4059 if scrollbar_settings.diagnostics {
4060 let diagnostics = snapshot
4061 .buffer_snapshot
4062 .diagnostics_in_range::<_, Point>(
4063 Point::zero()..max_point,
4064 false,
4065 )
4066 // We want to sort by severity, in order to paint the most severe diagnostics last.
4067 .sorted_by_key(|diagnostic| {
4068 std::cmp::Reverse(diagnostic.diagnostic.severity)
4069 });
4070
4071 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
4072 let start_display = diagnostic
4073 .range
4074 .start
4075 .to_display_point(&snapshot.display_snapshot);
4076 let end_display = diagnostic
4077 .range
4078 .end
4079 .to_display_point(&snapshot.display_snapshot);
4080 let color = match diagnostic.diagnostic.severity {
4081 DiagnosticSeverity::ERROR => theme.status().error,
4082 DiagnosticSeverity::WARNING => theme.status().warning,
4083 DiagnosticSeverity::INFORMATION => theme.status().info,
4084 _ => theme.status().hint,
4085 };
4086 ColoredRange {
4087 start: start_display.row(),
4088 end: end_display.row(),
4089 color,
4090 }
4091 });
4092 marker_quads.extend(
4093 scrollbar_layout
4094 .marker_quads_for_ranges(marker_row_ranges, Some(2)),
4095 );
4096 }
4097
4098 Arc::from(marker_quads)
4099 })
4100 .await;
4101
4102 editor.update(&mut cx, |editor, cx| {
4103 editor.scrollbar_marker_state.markers = scrollbar_markers;
4104 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
4105 editor.scrollbar_marker_state.pending_refresh = None;
4106 cx.notify();
4107 })?;
4108
4109 Ok(())
4110 }));
4111 });
4112 }
4113
4114 #[allow(clippy::too_many_arguments)]
4115 fn paint_highlighted_range(
4116 &self,
4117 range: Range<DisplayPoint>,
4118 color: Hsla,
4119 corner_radius: Pixels,
4120 line_end_overshoot: Pixels,
4121 layout: &EditorLayout,
4122 cx: &mut WindowContext,
4123 ) {
4124 let start_row = layout.visible_display_row_range.start;
4125 let end_row = layout.visible_display_row_range.end;
4126 if range.start != range.end {
4127 let row_range = if range.end.column() == 0 {
4128 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
4129 } else {
4130 cmp::max(range.start.row(), start_row)
4131 ..cmp::min(range.end.row().next_row(), end_row)
4132 };
4133
4134 let highlighted_range = HighlightedRange {
4135 color,
4136 line_height: layout.position_map.line_height,
4137 corner_radius,
4138 start_y: layout.content_origin.y
4139 + row_range.start.as_f32() * layout.position_map.line_height
4140 - layout.position_map.scroll_pixel_position.y,
4141 lines: row_range
4142 .iter_rows()
4143 .map(|row| {
4144 let line_layout =
4145 &layout.position_map.line_layouts[row.minus(start_row) as usize];
4146 HighlightedRangeLine {
4147 start_x: if row == range.start.row() {
4148 layout.content_origin.x
4149 + line_layout.x_for_index(range.start.column() as usize)
4150 - layout.position_map.scroll_pixel_position.x
4151 } else {
4152 layout.content_origin.x
4153 - layout.position_map.scroll_pixel_position.x
4154 },
4155 end_x: if row == range.end.row() {
4156 layout.content_origin.x
4157 + line_layout.x_for_index(range.end.column() as usize)
4158 - layout.position_map.scroll_pixel_position.x
4159 } else {
4160 layout.content_origin.x + line_layout.width + line_end_overshoot
4161 - layout.position_map.scroll_pixel_position.x
4162 },
4163 }
4164 })
4165 .collect(),
4166 };
4167
4168 highlighted_range.paint(layout.text_hitbox.bounds, cx);
4169 }
4170 }
4171
4172 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
4173 if let Some(mut inline_blame) = layout.inline_blame.take() {
4174 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
4175 inline_blame.paint(cx);
4176 })
4177 }
4178 }
4179
4180 fn paint_blocks(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
4181 for mut block in layout.blocks.drain(..) {
4182 block.element.paint(cx);
4183 }
4184 }
4185
4186 fn paint_inline_completion_popover(
4187 &mut self,
4188 layout: &mut EditorLayout,
4189 cx: &mut WindowContext,
4190 ) {
4191 if let Some(inline_completion_popover) = layout.inline_completion_popover.as_mut() {
4192 inline_completion_popover.paint(cx);
4193 }
4194 }
4195
4196 fn paint_mouse_context_menu(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
4197 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
4198 mouse_context_menu.paint(cx);
4199 }
4200 }
4201
4202 fn paint_scroll_wheel_listener(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
4203 cx.on_mouse_event({
4204 let position_map = layout.position_map.clone();
4205 let editor = self.editor.clone();
4206 let hitbox = layout.hitbox.clone();
4207 let mut delta = ScrollDelta::default();
4208
4209 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
4210 // accidentally turn off their scrolling.
4211 let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
4212
4213 move |event: &ScrollWheelEvent, phase, cx| {
4214 if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
4215 delta = delta.coalesce(event.delta);
4216 editor.update(cx, |editor, cx| {
4217 let position_map: &PositionMap = &position_map;
4218
4219 let line_height = position_map.line_height;
4220 let max_glyph_width = position_map.em_width;
4221 let (delta, axis) = match delta {
4222 gpui::ScrollDelta::Pixels(mut pixels) => {
4223 //Trackpad
4224 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
4225 (pixels, axis)
4226 }
4227
4228 gpui::ScrollDelta::Lines(lines) => {
4229 //Not trackpad
4230 let pixels =
4231 point(lines.x * max_glyph_width, lines.y * line_height);
4232 (pixels, None)
4233 }
4234 };
4235
4236 let current_scroll_position = position_map.snapshot.scroll_position();
4237 let x = (current_scroll_position.x * max_glyph_width
4238 - (delta.x * scroll_sensitivity))
4239 / max_glyph_width;
4240 let y = (current_scroll_position.y * line_height
4241 - (delta.y * scroll_sensitivity))
4242 / line_height;
4243 let mut scroll_position =
4244 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
4245 let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
4246 if forbid_vertical_scroll {
4247 scroll_position.y = current_scroll_position.y;
4248 }
4249
4250 if scroll_position != current_scroll_position {
4251 editor.scroll(scroll_position, axis, cx);
4252 cx.stop_propagation();
4253 } else if y < 0. {
4254 // Due to clamping, we may fail to detect cases of overscroll to the top;
4255 // We want the scroll manager to get an update in such cases and detect the change of direction
4256 // on the next frame.
4257 cx.notify();
4258 }
4259 });
4260 }
4261 }
4262 });
4263 }
4264
4265 fn paint_mouse_listeners(
4266 &mut self,
4267 layout: &EditorLayout,
4268 hovered_hunk: Option<HoveredHunk>,
4269 cx: &mut WindowContext,
4270 ) {
4271 self.paint_scroll_wheel_listener(layout, cx);
4272
4273 cx.on_mouse_event({
4274 let position_map = layout.position_map.clone();
4275 let editor = self.editor.clone();
4276 let text_hitbox = layout.text_hitbox.clone();
4277 let gutter_hitbox = layout.gutter_hitbox.clone();
4278
4279 move |event: &MouseDownEvent, phase, cx| {
4280 if phase == DispatchPhase::Bubble {
4281 match event.button {
4282 MouseButton::Left => editor.update(cx, |editor, cx| {
4283 Self::mouse_left_down(
4284 editor,
4285 event,
4286 hovered_hunk.clone(),
4287 &position_map,
4288 &text_hitbox,
4289 &gutter_hitbox,
4290 cx,
4291 );
4292 }),
4293 MouseButton::Right => editor.update(cx, |editor, cx| {
4294 Self::mouse_right_down(editor, event, &position_map, &text_hitbox, cx);
4295 }),
4296 MouseButton::Middle => editor.update(cx, |editor, cx| {
4297 Self::mouse_middle_down(editor, event, &position_map, &text_hitbox, cx);
4298 }),
4299 _ => {}
4300 };
4301 }
4302 }
4303 });
4304
4305 cx.on_mouse_event({
4306 let editor = self.editor.clone();
4307 let position_map = layout.position_map.clone();
4308 let text_hitbox = layout.text_hitbox.clone();
4309
4310 move |event: &MouseUpEvent, phase, cx| {
4311 if phase == DispatchPhase::Bubble {
4312 editor.update(cx, |editor, cx| {
4313 Self::mouse_up(editor, event, &position_map, &text_hitbox, cx)
4314 });
4315 }
4316 }
4317 });
4318 cx.on_mouse_event({
4319 let position_map = layout.position_map.clone();
4320 let editor = self.editor.clone();
4321 let text_hitbox = layout.text_hitbox.clone();
4322 let gutter_hitbox = layout.gutter_hitbox.clone();
4323
4324 move |event: &MouseMoveEvent, phase, cx| {
4325 if phase == DispatchPhase::Bubble {
4326 editor.update(cx, |editor, cx| {
4327 if editor.hover_state.focused(cx) {
4328 return;
4329 }
4330 if event.pressed_button == Some(MouseButton::Left)
4331 || event.pressed_button == Some(MouseButton::Middle)
4332 {
4333 Self::mouse_dragged(
4334 editor,
4335 event,
4336 &position_map,
4337 text_hitbox.bounds,
4338 cx,
4339 )
4340 }
4341
4342 Self::mouse_moved(
4343 editor,
4344 event,
4345 &position_map,
4346 &text_hitbox,
4347 &gutter_hitbox,
4348 cx,
4349 )
4350 });
4351 }
4352 }
4353 });
4354 }
4355
4356 fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
4357 bounds.upper_right().x - self.style.scrollbar_width
4358 }
4359
4360 fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
4361 let style = &self.style;
4362 let font_size = style.text.font_size.to_pixels(cx.rem_size());
4363 let layout = cx
4364 .text_system()
4365 .shape_line(
4366 SharedString::from(" ".repeat(column)),
4367 font_size,
4368 &[TextRun {
4369 len: column,
4370 font: style.text.font(),
4371 color: Hsla::default(),
4372 background_color: None,
4373 underline: None,
4374 strikethrough: None,
4375 }],
4376 )
4377 .unwrap();
4378
4379 layout.width
4380 }
4381
4382 fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
4383 let digit_count = (snapshot.widest_line_number() as f32).log10().floor() as usize + 1;
4384 self.column_pixels(digit_count, cx)
4385 }
4386}
4387
4388fn jump_data(
4389 snapshot: &EditorSnapshot,
4390 block_row_start: DisplayRow,
4391 height: u32,
4392 for_excerpt: &ExcerptInfo,
4393 cx: &mut WindowContext<'_>,
4394) -> JumpData {
4395 let range = &for_excerpt.range;
4396 let buffer = &for_excerpt.buffer;
4397 let jump_path = project::File::from_dyn(buffer.file()).map(|file| ProjectPath {
4398 worktree_id: file.worktree_id(cx),
4399 path: file.path.clone(),
4400 });
4401 let jump_anchor = range
4402 .primary
4403 .as_ref()
4404 .map_or(range.context.start, |primary| primary.start);
4405
4406 let excerpt_start = range.context.start;
4407 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
4408 let offset_from_excerpt_start = if jump_anchor == excerpt_start {
4409 0
4410 } else {
4411 let excerpt_start_row = language::ToPoint::to_point(&jump_anchor, buffer).row;
4412 jump_position.row - excerpt_start_row
4413 };
4414 let line_offset_from_top = block_row_start.0 + height + offset_from_excerpt_start
4415 - snapshot
4416 .scroll_anchor
4417 .scroll_position(&snapshot.display_snapshot)
4418 .y as u32;
4419 JumpData {
4420 excerpt_id: for_excerpt.id,
4421 anchor: jump_anchor,
4422 position: language::ToPoint::to_point(&jump_anchor, buffer),
4423 path: jump_path,
4424 line_offset_from_top,
4425 }
4426}
4427
4428fn inline_completion_popover_text(
4429 editor_snapshot: &EditorSnapshot,
4430 edits: &Vec<(Range<Anchor>, String)>,
4431 cx: &WindowContext,
4432) -> (String, Vec<(Range<usize>, HighlightStyle)>) {
4433 let edit_start = edits
4434 .first()
4435 .unwrap()
4436 .0
4437 .start
4438 .to_display_point(editor_snapshot);
4439
4440 let mut text = String::new();
4441 let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
4442 let mut highlights = Vec::new();
4443 for (old_range, new_text) in edits {
4444 let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
4445 text.extend(
4446 editor_snapshot
4447 .buffer_snapshot
4448 .chunks(offset..old_offset_range.start, false)
4449 .map(|chunk| chunk.text),
4450 );
4451 offset = old_offset_range.end;
4452
4453 let start = text.len();
4454 text.push_str(new_text);
4455 let end = text.len();
4456 highlights.push((
4457 start..end,
4458 HighlightStyle {
4459 background_color: Some(cx.theme().status().created_background),
4460 ..Default::default()
4461 },
4462 ));
4463 }
4464
4465 let edit_end = edits
4466 .last()
4467 .unwrap()
4468 .0
4469 .end
4470 .to_display_point(editor_snapshot);
4471 let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
4472 .to_offset(editor_snapshot, Bias::Right);
4473 text.extend(
4474 editor_snapshot
4475 .buffer_snapshot
4476 .chunks(offset..end_of_line, false)
4477 .map(|chunk| chunk.text),
4478 );
4479
4480 (text, highlights)
4481}
4482
4483fn all_edits_insertions_or_deletions(
4484 edits: &Vec<(Range<Anchor>, String)>,
4485 snapshot: &MultiBufferSnapshot,
4486) -> bool {
4487 let mut all_insertions = true;
4488 let mut all_deletions = true;
4489
4490 for (range, new_text) in edits.iter() {
4491 let range_is_empty = range.to_offset(&snapshot).is_empty();
4492 let text_is_empty = new_text.is_empty();
4493
4494 if range_is_empty != text_is_empty {
4495 if range_is_empty {
4496 all_deletions = false;
4497 } else {
4498 all_insertions = false;
4499 }
4500 } else {
4501 return false;
4502 }
4503
4504 if !all_insertions && !all_deletions {
4505 return false;
4506 }
4507 }
4508 all_insertions || all_deletions
4509}
4510
4511#[allow(clippy::too_many_arguments)]
4512fn prepaint_gutter_button(
4513 button: IconButton,
4514 row: DisplayRow,
4515 line_height: Pixels,
4516 gutter_dimensions: &GutterDimensions,
4517 scroll_pixel_position: gpui::Point<Pixels>,
4518 gutter_hitbox: &Hitbox,
4519 rows_with_hunk_bounds: &HashMap<DisplayRow, Bounds<Pixels>>,
4520 cx: &mut WindowContext<'_>,
4521) -> AnyElement {
4522 let mut button = button.into_any_element();
4523 let available_space = size(
4524 AvailableSpace::MinContent,
4525 AvailableSpace::Definite(line_height),
4526 );
4527 let indicator_size = button.layout_as_root(available_space, cx);
4528
4529 let blame_width = gutter_dimensions.git_blame_entries_width;
4530 let gutter_width = rows_with_hunk_bounds
4531 .get(&row)
4532 .map(|bounds| bounds.size.width);
4533 let left_offset = blame_width.max(gutter_width).unwrap_or_default();
4534
4535 let mut x = left_offset;
4536 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
4537 - indicator_size.width
4538 - left_offset;
4539 x += available_width / 2.;
4540
4541 let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
4542 y += (line_height - indicator_size.height) / 2.;
4543
4544 button.prepaint_as_root(gutter_hitbox.origin + point(x, y), available_space, cx);
4545 button
4546}
4547
4548fn render_inline_blame_entry(
4549 blame: &gpui::Model<GitBlame>,
4550 blame_entry: BlameEntry,
4551 style: &EditorStyle,
4552 workspace: Option<WeakView<Workspace>>,
4553 cx: &mut WindowContext<'_>,
4554) -> AnyElement {
4555 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
4556
4557 let author = blame_entry.author.as_deref().unwrap_or_default();
4558 let summary_enabled = ProjectSettings::get_global(cx)
4559 .git
4560 .show_inline_commit_summary();
4561
4562 let text = match blame_entry.summary.as_ref() {
4563 Some(summary) if summary_enabled => {
4564 format!("{}, {} - {}", author, relative_timestamp, summary)
4565 }
4566 _ => format!("{}, {}", author, relative_timestamp),
4567 };
4568
4569 let details = blame.read(cx).details_for_entry(&blame_entry);
4570
4571 let tooltip = cx.new_view(|_| BlameEntryTooltip::new(blame_entry, details, style, workspace));
4572
4573 h_flex()
4574 .id("inline-blame")
4575 .w_full()
4576 .font_family(style.text.font().family)
4577 .text_color(cx.theme().status().hint)
4578 .line_height(style.text.line_height)
4579 .child(Icon::new(IconName::FileGit).color(Color::Hint))
4580 .child(text)
4581 .gap_2()
4582 .hoverable_tooltip(move |_| tooltip.clone().into())
4583 .into_any()
4584}
4585
4586fn render_blame_entry(
4587 ix: usize,
4588 blame: &gpui::Model<GitBlame>,
4589 blame_entry: BlameEntry,
4590 style: &EditorStyle,
4591 last_used_color: &mut Option<(PlayerColor, Oid)>,
4592 editor: View<Editor>,
4593 cx: &mut WindowContext<'_>,
4594) -> AnyElement {
4595 let mut sha_color = cx
4596 .theme()
4597 .players()
4598 .color_for_participant(blame_entry.sha.into());
4599 // If the last color we used is the same as the one we get for this line, but
4600 // the commit SHAs are different, then we try again to get a different color.
4601 match *last_used_color {
4602 Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
4603 let index: u32 = blame_entry.sha.into();
4604 sha_color = cx.theme().players().color_for_participant(index + 1);
4605 }
4606 _ => {}
4607 };
4608 last_used_color.replace((sha_color, blame_entry.sha));
4609
4610 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
4611
4612 let short_commit_id = blame_entry.sha.display_short();
4613
4614 let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
4615 let name = util::truncate_and_trailoff(author_name, GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED);
4616
4617 let details = blame.read(cx).details_for_entry(&blame_entry);
4618
4619 let workspace = editor.read(cx).workspace.as_ref().map(|(w, _)| w.clone());
4620
4621 let tooltip = cx.new_view(|_| {
4622 BlameEntryTooltip::new(blame_entry.clone(), details.clone(), style, workspace)
4623 });
4624
4625 h_flex()
4626 .w_full()
4627 .justify_between()
4628 .font_family(style.text.font().family)
4629 .line_height(style.text.line_height)
4630 .id(("blame", ix))
4631 .text_color(cx.theme().status().hint)
4632 .pr_2()
4633 .gap_2()
4634 .child(
4635 h_flex()
4636 .items_center()
4637 .gap_2()
4638 .child(div().text_color(sha_color.cursor).child(short_commit_id))
4639 .child(name),
4640 )
4641 .child(relative_timestamp)
4642 .on_mouse_down(MouseButton::Right, {
4643 let blame_entry = blame_entry.clone();
4644 let details = details.clone();
4645 move |event, cx| {
4646 deploy_blame_entry_context_menu(
4647 &blame_entry,
4648 details.as_ref(),
4649 editor.clone(),
4650 event.position,
4651 cx,
4652 );
4653 }
4654 })
4655 .hover(|style| style.bg(cx.theme().colors().element_hover))
4656 .when_some(
4657 details.and_then(|details| details.permalink),
4658 |this, url| {
4659 let url = url.clone();
4660 this.cursor_pointer().on_click(move |_, cx| {
4661 cx.stop_propagation();
4662 cx.open_url(url.as_str())
4663 })
4664 },
4665 )
4666 .hoverable_tooltip(move |_| tooltip.clone().into())
4667 .into_any()
4668}
4669
4670fn deploy_blame_entry_context_menu(
4671 blame_entry: &BlameEntry,
4672 details: Option<&CommitDetails>,
4673 editor: View<Editor>,
4674 position: gpui::Point<Pixels>,
4675 cx: &mut WindowContext<'_>,
4676) {
4677 let context_menu = ContextMenu::build(cx, move |menu, _| {
4678 let sha = format!("{}", blame_entry.sha);
4679 menu.on_blur_subscription(Subscription::new(|| {}))
4680 .entry("Copy commit SHA", None, move |cx| {
4681 cx.write_to_clipboard(ClipboardItem::new_string(sha.clone()));
4682 })
4683 .when_some(
4684 details.and_then(|details| details.permalink.clone()),
4685 |this, url| this.entry("Open permalink", None, move |cx| cx.open_url(url.as_str())),
4686 )
4687 });
4688
4689 editor.update(cx, move |editor, cx| {
4690 editor.mouse_context_menu = Some(MouseContextMenu::new(
4691 MenuPosition::PinnedToScreen(position),
4692 context_menu,
4693 cx,
4694 ));
4695 cx.notify();
4696 });
4697}
4698
4699#[derive(Debug)]
4700pub(crate) struct LineWithInvisibles {
4701 fragments: SmallVec<[LineFragment; 1]>,
4702 invisibles: Vec<Invisible>,
4703 len: usize,
4704 width: Pixels,
4705 font_size: Pixels,
4706}
4707
4708#[allow(clippy::large_enum_variant)]
4709enum LineFragment {
4710 Text(ShapedLine),
4711 Element {
4712 element: Option<AnyElement>,
4713 size: Size<Pixels>,
4714 len: usize,
4715 },
4716}
4717
4718impl fmt::Debug for LineFragment {
4719 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4720 match self {
4721 LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
4722 LineFragment::Element { size, len, .. } => f
4723 .debug_struct("Element")
4724 .field("size", size)
4725 .field("len", len)
4726 .finish(),
4727 }
4728 }
4729}
4730
4731impl LineWithInvisibles {
4732 #[allow(clippy::too_many_arguments)]
4733 fn from_chunks<'a>(
4734 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
4735 editor_style: &EditorStyle,
4736 max_line_len: usize,
4737 max_line_count: usize,
4738 editor_mode: EditorMode,
4739 text_width: Pixels,
4740 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
4741 cx: &mut WindowContext,
4742 ) -> Vec<Self> {
4743 let text_style = &editor_style.text;
4744 let mut layouts = Vec::with_capacity(max_line_count);
4745 let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
4746 let mut line = String::new();
4747 let mut invisibles = Vec::new();
4748 let mut width = Pixels::ZERO;
4749 let mut len = 0;
4750 let mut styles = Vec::new();
4751 let mut non_whitespace_added = false;
4752 let mut row = 0;
4753 let mut line_exceeded_max_len = false;
4754 let font_size = text_style.font_size.to_pixels(cx.rem_size());
4755
4756 let ellipsis = SharedString::from("⋯");
4757
4758 for highlighted_chunk in chunks.chain([HighlightedChunk {
4759 text: "\n",
4760 style: None,
4761 is_tab: false,
4762 replacement: None,
4763 }]) {
4764 if let Some(replacement) = highlighted_chunk.replacement {
4765 if !line.is_empty() {
4766 let shaped_line = cx
4767 .text_system()
4768 .shape_line(line.clone().into(), font_size, &styles)
4769 .unwrap();
4770 width += shaped_line.width;
4771 len += shaped_line.len;
4772 fragments.push(LineFragment::Text(shaped_line));
4773 line.clear();
4774 styles.clear();
4775 }
4776
4777 match replacement {
4778 ChunkReplacement::Renderer(renderer) => {
4779 let available_width = if renderer.constrain_width {
4780 let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
4781 ellipsis.clone()
4782 } else {
4783 SharedString::from(Arc::from(highlighted_chunk.text))
4784 };
4785 let shaped_line = cx
4786 .text_system()
4787 .shape_line(
4788 chunk,
4789 font_size,
4790 &[text_style.to_run(highlighted_chunk.text.len())],
4791 )
4792 .unwrap();
4793 AvailableSpace::Definite(shaped_line.width)
4794 } else {
4795 AvailableSpace::MinContent
4796 };
4797
4798 let mut element = (renderer.render)(&mut ChunkRendererContext {
4799 context: cx,
4800 max_width: text_width,
4801 });
4802 let line_height = text_style.line_height_in_pixels(cx.rem_size());
4803 let size = element.layout_as_root(
4804 size(available_width, AvailableSpace::Definite(line_height)),
4805 cx,
4806 );
4807
4808 width += size.width;
4809 len += highlighted_chunk.text.len();
4810 fragments.push(LineFragment::Element {
4811 element: Some(element),
4812 size,
4813 len: highlighted_chunk.text.len(),
4814 });
4815 }
4816 ChunkReplacement::Str(x) => {
4817 let text_style = if let Some(style) = highlighted_chunk.style {
4818 Cow::Owned(text_style.clone().highlight(style))
4819 } else {
4820 Cow::Borrowed(text_style)
4821 };
4822
4823 let run = TextRun {
4824 len: x.len(),
4825 font: text_style.font(),
4826 color: text_style.color,
4827 background_color: text_style.background_color,
4828 underline: text_style.underline,
4829 strikethrough: text_style.strikethrough,
4830 };
4831 let line_layout = cx
4832 .text_system()
4833 .shape_line(x, font_size, &[run])
4834 .unwrap()
4835 .with_len(highlighted_chunk.text.len());
4836
4837 width += line_layout.width;
4838 len += highlighted_chunk.text.len();
4839 fragments.push(LineFragment::Text(line_layout))
4840 }
4841 }
4842 } else {
4843 for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
4844 if ix > 0 {
4845 let shaped_line = cx
4846 .text_system()
4847 .shape_line(line.clone().into(), font_size, &styles)
4848 .unwrap();
4849 width += shaped_line.width;
4850 len += shaped_line.len;
4851 fragments.push(LineFragment::Text(shaped_line));
4852 layouts.push(Self {
4853 width: mem::take(&mut width),
4854 len: mem::take(&mut len),
4855 fragments: mem::take(&mut fragments),
4856 invisibles: std::mem::take(&mut invisibles),
4857 font_size,
4858 });
4859
4860 line.clear();
4861 styles.clear();
4862 row += 1;
4863 line_exceeded_max_len = false;
4864 non_whitespace_added = false;
4865 if row == max_line_count {
4866 return layouts;
4867 }
4868 }
4869
4870 if !line_chunk.is_empty() && !line_exceeded_max_len {
4871 let text_style = if let Some(style) = highlighted_chunk.style {
4872 Cow::Owned(text_style.clone().highlight(style))
4873 } else {
4874 Cow::Borrowed(text_style)
4875 };
4876
4877 if line.len() + line_chunk.len() > max_line_len {
4878 let mut chunk_len = max_line_len - line.len();
4879 while !line_chunk.is_char_boundary(chunk_len) {
4880 chunk_len -= 1;
4881 }
4882 line_chunk = &line_chunk[..chunk_len];
4883 line_exceeded_max_len = true;
4884 }
4885
4886 styles.push(TextRun {
4887 len: line_chunk.len(),
4888 font: text_style.font(),
4889 color: text_style.color,
4890 background_color: text_style.background_color,
4891 underline: text_style.underline,
4892 strikethrough: text_style.strikethrough,
4893 });
4894
4895 if editor_mode == EditorMode::Full {
4896 // Line wrap pads its contents with fake whitespaces,
4897 // avoid printing them
4898 let is_soft_wrapped = is_row_soft_wrapped(row);
4899 if highlighted_chunk.is_tab {
4900 if non_whitespace_added || !is_soft_wrapped {
4901 invisibles.push(Invisible::Tab {
4902 line_start_offset: line.len(),
4903 line_end_offset: line.len() + line_chunk.len(),
4904 });
4905 }
4906 } else {
4907 invisibles.extend(
4908 line_chunk
4909 .bytes()
4910 .enumerate()
4911 .filter(|(_, line_byte)| {
4912 let is_whitespace =
4913 (*line_byte as char).is_whitespace();
4914 non_whitespace_added |= !is_whitespace;
4915 is_whitespace
4916 && (non_whitespace_added || !is_soft_wrapped)
4917 })
4918 .map(|(whitespace_index, _)| Invisible::Whitespace {
4919 line_offset: line.len() + whitespace_index,
4920 }),
4921 )
4922 }
4923 }
4924
4925 line.push_str(line_chunk);
4926 }
4927 }
4928 }
4929 }
4930
4931 layouts
4932 }
4933
4934 fn prepaint(
4935 &mut self,
4936 line_height: Pixels,
4937 scroll_pixel_position: gpui::Point<Pixels>,
4938 row: DisplayRow,
4939 content_origin: gpui::Point<Pixels>,
4940 line_elements: &mut SmallVec<[AnyElement; 1]>,
4941 cx: &mut WindowContext,
4942 ) {
4943 let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
4944 let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
4945 for fragment in &mut self.fragments {
4946 match fragment {
4947 LineFragment::Text(line) => {
4948 fragment_origin.x += line.width;
4949 }
4950 LineFragment::Element { element, size, .. } => {
4951 let mut element = element
4952 .take()
4953 .expect("you can't prepaint LineWithInvisibles twice");
4954
4955 // Center the element vertically within the line.
4956 let mut element_origin = fragment_origin;
4957 element_origin.y += (line_height - size.height) / 2.;
4958 element.prepaint_at(element_origin, cx);
4959 line_elements.push(element);
4960
4961 fragment_origin.x += size.width;
4962 }
4963 }
4964 }
4965 }
4966
4967 fn draw(
4968 &self,
4969 layout: &EditorLayout,
4970 row: DisplayRow,
4971 content_origin: gpui::Point<Pixels>,
4972 whitespace_setting: ShowWhitespaceSetting,
4973 selection_ranges: &[Range<DisplayPoint>],
4974 cx: &mut WindowContext,
4975 ) {
4976 let line_height = layout.position_map.line_height;
4977 let line_y = line_height
4978 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
4979
4980 let mut fragment_origin =
4981 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
4982
4983 for fragment in &self.fragments {
4984 match fragment {
4985 LineFragment::Text(line) => {
4986 line.paint(fragment_origin, line_height, cx).log_err();
4987 fragment_origin.x += line.width;
4988 }
4989 LineFragment::Element { size, .. } => {
4990 fragment_origin.x += size.width;
4991 }
4992 }
4993 }
4994
4995 self.draw_invisibles(
4996 selection_ranges,
4997 layout,
4998 content_origin,
4999 line_y,
5000 row,
5001 line_height,
5002 whitespace_setting,
5003 cx,
5004 );
5005 }
5006
5007 #[allow(clippy::too_many_arguments)]
5008 fn draw_invisibles(
5009 &self,
5010 selection_ranges: &[Range<DisplayPoint>],
5011 layout: &EditorLayout,
5012 content_origin: gpui::Point<Pixels>,
5013 line_y: Pixels,
5014 row: DisplayRow,
5015 line_height: Pixels,
5016 whitespace_setting: ShowWhitespaceSetting,
5017 cx: &mut WindowContext,
5018 ) {
5019 let extract_whitespace_info = |invisible: &Invisible| {
5020 let (token_offset, token_end_offset, invisible_symbol) = match invisible {
5021 Invisible::Tab {
5022 line_start_offset,
5023 line_end_offset,
5024 } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
5025 Invisible::Whitespace { line_offset } => {
5026 (*line_offset, line_offset + 1, &layout.space_invisible)
5027 }
5028 };
5029
5030 let x_offset = self.x_for_index(token_offset);
5031 let invisible_offset =
5032 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
5033 let origin = content_origin
5034 + gpui::point(
5035 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
5036 line_y,
5037 );
5038
5039 (
5040 [token_offset, token_end_offset],
5041 Box::new(move |cx: &mut WindowContext| {
5042 invisible_symbol.paint(origin, line_height, cx).log_err();
5043 }),
5044 )
5045 };
5046
5047 let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
5048 match whitespace_setting {
5049 ShowWhitespaceSetting::None => (),
5050 ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(cx)),
5051 ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
5052 let invisible_point = DisplayPoint::new(row, start as u32);
5053 if !selection_ranges
5054 .iter()
5055 .any(|region| region.start <= invisible_point && invisible_point < region.end)
5056 {
5057 return;
5058 }
5059
5060 paint(cx);
5061 }),
5062
5063 // For a whitespace to be on a boundary, any of the following conditions need to be met:
5064 // - It is a tab
5065 // - It is adjacent to an edge (start or end)
5066 // - It is adjacent to a whitespace (left or right)
5067 ShowWhitespaceSetting::Boundary => {
5068 // 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
5069 // the above cases.
5070 // Note: We zip in the original `invisibles` to check for tab equality
5071 let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut WindowContext)>)> = None;
5072 for (([start, end], paint), invisible) in
5073 invisible_iter.zip_eq(self.invisibles.iter())
5074 {
5075 let should_render = match (&last_seen, invisible) {
5076 (_, Invisible::Tab { .. }) => true,
5077 (Some((_, last_end, _)), _) => *last_end == start,
5078 _ => false,
5079 };
5080
5081 if should_render || start == 0 || end == self.len {
5082 paint(cx);
5083
5084 // Since we are scanning from the left, we will skip over the first available whitespace that is part
5085 // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
5086 if let Some((should_render_last, last_end, paint_last)) = last_seen {
5087 // Note that we need to make sure that the last one is actually adjacent
5088 if !should_render_last && last_end == start {
5089 paint_last(cx);
5090 }
5091 }
5092 }
5093
5094 // Manually render anything within a selection
5095 let invisible_point = DisplayPoint::new(row, start as u32);
5096 if selection_ranges.iter().any(|region| {
5097 region.start <= invisible_point && invisible_point < region.end
5098 }) {
5099 paint(cx);
5100 }
5101
5102 last_seen = Some((should_render, end, paint));
5103 }
5104 }
5105 }
5106 }
5107
5108 pub fn x_for_index(&self, index: usize) -> Pixels {
5109 let mut fragment_start_x = Pixels::ZERO;
5110 let mut fragment_start_index = 0;
5111
5112 for fragment in &self.fragments {
5113 match fragment {
5114 LineFragment::Text(shaped_line) => {
5115 let fragment_end_index = fragment_start_index + shaped_line.len;
5116 if index < fragment_end_index {
5117 return fragment_start_x
5118 + shaped_line.x_for_index(index - fragment_start_index);
5119 }
5120 fragment_start_x += shaped_line.width;
5121 fragment_start_index = fragment_end_index;
5122 }
5123 LineFragment::Element { len, size, .. } => {
5124 let fragment_end_index = fragment_start_index + len;
5125 if index < fragment_end_index {
5126 return fragment_start_x;
5127 }
5128 fragment_start_x += size.width;
5129 fragment_start_index = fragment_end_index;
5130 }
5131 }
5132 }
5133
5134 fragment_start_x
5135 }
5136
5137 pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
5138 let mut fragment_start_x = Pixels::ZERO;
5139 let mut fragment_start_index = 0;
5140
5141 for fragment in &self.fragments {
5142 match fragment {
5143 LineFragment::Text(shaped_line) => {
5144 let fragment_end_x = fragment_start_x + shaped_line.width;
5145 if x < fragment_end_x {
5146 return Some(
5147 fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
5148 );
5149 }
5150 fragment_start_x = fragment_end_x;
5151 fragment_start_index += shaped_line.len;
5152 }
5153 LineFragment::Element { len, size, .. } => {
5154 let fragment_end_x = fragment_start_x + size.width;
5155 if x < fragment_end_x {
5156 return Some(fragment_start_index);
5157 }
5158 fragment_start_index += len;
5159 fragment_start_x = fragment_end_x;
5160 }
5161 }
5162 }
5163
5164 None
5165 }
5166
5167 pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
5168 let mut fragment_start_index = 0;
5169
5170 for fragment in &self.fragments {
5171 match fragment {
5172 LineFragment::Text(shaped_line) => {
5173 let fragment_end_index = fragment_start_index + shaped_line.len;
5174 if index < fragment_end_index {
5175 return shaped_line.font_id_for_index(index - fragment_start_index);
5176 }
5177 fragment_start_index = fragment_end_index;
5178 }
5179 LineFragment::Element { len, .. } => {
5180 let fragment_end_index = fragment_start_index + len;
5181 if index < fragment_end_index {
5182 return None;
5183 }
5184 fragment_start_index = fragment_end_index;
5185 }
5186 }
5187 }
5188
5189 None
5190 }
5191}
5192
5193#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5194enum Invisible {
5195 /// A tab character
5196 ///
5197 /// A tab character is internally represented by spaces (configured by the user's tab width)
5198 /// aligned to the nearest column, so it's necessary to store the start and end offset for
5199 /// adjacency checks.
5200 Tab {
5201 line_start_offset: usize,
5202 line_end_offset: usize,
5203 },
5204 Whitespace {
5205 line_offset: usize,
5206 },
5207}
5208
5209impl EditorElement {
5210 /// Returns the rem size to use when rendering the [`EditorElement`].
5211 ///
5212 /// This allows UI elements to scale based on the `buffer_font_size`.
5213 fn rem_size(&self, cx: &WindowContext) -> Option<Pixels> {
5214 match self.editor.read(cx).mode {
5215 EditorMode::Full => {
5216 let buffer_font_size = self.style.text.font_size;
5217 match buffer_font_size {
5218 AbsoluteLength::Pixels(pixels) => {
5219 let rem_size_scale = {
5220 // Our default UI font size is 14px on a 16px base scale.
5221 // This means the default UI font size is 0.875rems.
5222 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
5223
5224 // We then determine the delta between a single rem and the default font
5225 // size scale.
5226 let default_font_size_delta = 1. - default_font_size_scale;
5227
5228 // Finally, we add this delta to 1rem to get the scale factor that
5229 // should be used to scale up the UI.
5230 1. + default_font_size_delta
5231 };
5232
5233 Some(pixels * rem_size_scale)
5234 }
5235 AbsoluteLength::Rems(rems) => {
5236 Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
5237 }
5238 }
5239 }
5240 // We currently use single-line and auto-height editors in UI contexts,
5241 // so we don't want to scale everything with the buffer font size, as it
5242 // ends up looking off.
5243 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => None,
5244 }
5245 }
5246}
5247
5248impl Element for EditorElement {
5249 type RequestLayoutState = ();
5250 type PrepaintState = EditorLayout;
5251
5252 fn id(&self) -> Option<ElementId> {
5253 None
5254 }
5255
5256 fn request_layout(
5257 &mut self,
5258 _: Option<&GlobalElementId>,
5259 cx: &mut WindowContext,
5260 ) -> (gpui::LayoutId, ()) {
5261 let rem_size = self.rem_size(cx);
5262 cx.with_rem_size(rem_size, |cx| {
5263 self.editor.update(cx, |editor, cx| {
5264 editor.set_style(self.style.clone(), cx);
5265
5266 let layout_id = match editor.mode {
5267 EditorMode::SingleLine { auto_width } => {
5268 let rem_size = cx.rem_size();
5269
5270 let height = self.style.text.line_height_in_pixels(rem_size);
5271 if auto_width {
5272 let editor_handle = cx.view().clone();
5273 let style = self.style.clone();
5274 cx.request_measured_layout(Style::default(), move |_, _, cx| {
5275 let editor_snapshot =
5276 editor_handle.update(cx, |editor, cx| editor.snapshot(cx));
5277 let line = Self::layout_lines(
5278 DisplayRow(0)..DisplayRow(1),
5279 &editor_snapshot,
5280 &style,
5281 px(f32::MAX),
5282 |_| false, // Single lines never soft wrap
5283 cx,
5284 )
5285 .pop()
5286 .unwrap();
5287
5288 let font_id = cx.text_system().resolve_font(&style.text.font());
5289 let font_size = style.text.font_size.to_pixels(cx.rem_size());
5290 let em_width = cx
5291 .text_system()
5292 .typographic_bounds(font_id, font_size, 'm')
5293 .unwrap()
5294 .size
5295 .width;
5296
5297 size(line.width + em_width, height)
5298 })
5299 } else {
5300 let mut style = Style::default();
5301 style.size.height = height.into();
5302 style.size.width = relative(1.).into();
5303 cx.request_layout(style, None)
5304 }
5305 }
5306 EditorMode::AutoHeight { max_lines } => {
5307 let editor_handle = cx.view().clone();
5308 let max_line_number_width =
5309 self.max_line_number_width(&editor.snapshot(cx), cx);
5310 cx.request_measured_layout(
5311 Style::default(),
5312 move |known_dimensions, available_space, cx| {
5313 editor_handle
5314 .update(cx, |editor, cx| {
5315 compute_auto_height_layout(
5316 editor,
5317 max_lines,
5318 max_line_number_width,
5319 known_dimensions,
5320 available_space.width,
5321 cx,
5322 )
5323 })
5324 .unwrap_or_default()
5325 },
5326 )
5327 }
5328 EditorMode::Full => {
5329 let mut style = Style::default();
5330 style.size.width = relative(1.).into();
5331 style.size.height = relative(1.).into();
5332 cx.request_layout(style, None)
5333 }
5334 };
5335
5336 (layout_id, ())
5337 })
5338 })
5339 }
5340
5341 fn prepaint(
5342 &mut self,
5343 _: Option<&GlobalElementId>,
5344 bounds: Bounds<Pixels>,
5345 _: &mut Self::RequestLayoutState,
5346 cx: &mut WindowContext,
5347 ) -> Self::PrepaintState {
5348 let text_style = TextStyleRefinement {
5349 font_size: Some(self.style.text.font_size),
5350 line_height: Some(self.style.text.line_height),
5351 ..Default::default()
5352 };
5353 let focus_handle = self.editor.focus_handle(cx);
5354 cx.set_view_id(self.editor.entity_id());
5355 cx.set_focus_handle(&focus_handle);
5356
5357 let rem_size = self.rem_size(cx);
5358 cx.with_rem_size(rem_size, |cx| {
5359 cx.with_text_style(Some(text_style), |cx| {
5360 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
5361 let mut snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
5362 let style = self.style.clone();
5363
5364 let font_id = cx.text_system().resolve_font(&style.text.font());
5365 let font_size = style.text.font_size.to_pixels(cx.rem_size());
5366 let line_height = style.text.line_height_in_pixels(cx.rem_size());
5367 let em_width = cx
5368 .text_system()
5369 .typographic_bounds(font_id, font_size, 'm')
5370 .unwrap()
5371 .size
5372 .width;
5373 let em_advance = cx
5374 .text_system()
5375 .advance(font_id, font_size, 'm')
5376 .unwrap()
5377 .width;
5378
5379 let gutter_dimensions = snapshot.gutter_dimensions(
5380 font_id,
5381 font_size,
5382 em_width,
5383 em_advance,
5384 self.max_line_number_width(&snapshot, cx),
5385 cx,
5386 );
5387 let text_width = bounds.size.width - gutter_dimensions.width;
5388
5389 let right_margin = if snapshot.mode == EditorMode::Full {
5390 EditorElement::SCROLLBAR_WIDTH
5391 } else {
5392 px(0.)
5393 };
5394 let overscroll = size(em_width + right_margin, px(0.));
5395
5396 let editor_width =
5397 text_width - gutter_dimensions.margin - overscroll.width - em_width;
5398
5399 snapshot = self.editor.update(cx, |editor, cx| {
5400 editor.last_bounds = Some(bounds);
5401 editor.gutter_dimensions = gutter_dimensions;
5402 editor.set_visible_line_count(bounds.size.height / line_height, cx);
5403
5404 if matches!(editor.mode, EditorMode::AutoHeight { .. }) {
5405 snapshot
5406 } else {
5407 let wrap_width = match editor.soft_wrap_mode(cx) {
5408 SoftWrap::GitDiff => None,
5409 SoftWrap::None => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
5410 SoftWrap::EditorWidth => Some(editor_width),
5411 SoftWrap::Column(column) => Some(column as f32 * em_advance),
5412 SoftWrap::Bounded(column) => {
5413 Some(editor_width.min(column as f32 * em_advance))
5414 }
5415 };
5416
5417 if editor.set_wrap_width(wrap_width, cx) {
5418 editor.snapshot(cx)
5419 } else {
5420 snapshot
5421 }
5422 }
5423 });
5424
5425 let wrap_guides = self
5426 .editor
5427 .read(cx)
5428 .wrap_guides(cx)
5429 .iter()
5430 .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
5431 .collect::<SmallVec<[_; 2]>>();
5432
5433 let hitbox = cx.insert_hitbox(bounds, false);
5434 let gutter_hitbox =
5435 cx.insert_hitbox(gutter_bounds(bounds, gutter_dimensions), false);
5436 let text_hitbox = cx.insert_hitbox(
5437 Bounds {
5438 origin: gutter_hitbox.upper_right(),
5439 size: size(text_width, bounds.size.height),
5440 },
5441 false,
5442 );
5443 // Offset the content_bounds from the text_bounds by the gutter margin (which
5444 // is roughly half a character wide) to make hit testing work more like how we want.
5445 let content_origin =
5446 text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
5447
5448 let height_in_lines = bounds.size.height / line_height;
5449 let max_row = snapshot.max_point().row().as_f32();
5450 let max_scroll_top = if matches!(snapshot.mode, EditorMode::AutoHeight { .. }) {
5451 (max_row - height_in_lines + 1.).max(0.)
5452 } else {
5453 let settings = EditorSettings::get_global(cx);
5454 match settings.scroll_beyond_last_line {
5455 ScrollBeyondLastLine::OnePage => max_row,
5456 ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
5457 ScrollBeyondLastLine::VerticalScrollMargin => {
5458 (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
5459 .max(0.)
5460 }
5461 }
5462 };
5463
5464 let mut autoscroll_request = None;
5465 let mut autoscroll_containing_element = false;
5466 let mut autoscroll_horizontally = false;
5467 self.editor.update(cx, |editor, cx| {
5468 autoscroll_request = editor.autoscroll_request();
5469 autoscroll_containing_element =
5470 autoscroll_request.is_some() || editor.has_pending_selection();
5471 autoscroll_horizontally =
5472 editor.autoscroll_vertically(bounds, line_height, max_scroll_top, cx);
5473 snapshot = editor.snapshot(cx);
5474 });
5475
5476 let mut scroll_position = snapshot.scroll_position();
5477 // The scroll position is a fractional point, the whole number of which represents
5478 // the top of the window in terms of display rows.
5479 let start_row = DisplayRow(scroll_position.y as u32);
5480 let max_row = snapshot.max_point().row();
5481 let end_row = cmp::min(
5482 (scroll_position.y + height_in_lines).ceil() as u32,
5483 max_row.next_row().0,
5484 );
5485 let end_row = DisplayRow(end_row);
5486
5487 let buffer_rows = snapshot
5488 .buffer_rows(start_row)
5489 .take((start_row..end_row).len())
5490 .collect::<Vec<_>>();
5491 let is_row_soft_wrapped =
5492 |row| buffer_rows.get(row).copied().flatten().is_none();
5493
5494 let start_anchor = if start_row == Default::default() {
5495 Anchor::min()
5496 } else {
5497 snapshot.buffer_snapshot.anchor_before(
5498 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
5499 )
5500 };
5501 let end_anchor = if end_row > max_row {
5502 Anchor::max()
5503 } else {
5504 snapshot.buffer_snapshot.anchor_before(
5505 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
5506 )
5507 };
5508
5509 let highlighted_rows = self
5510 .editor
5511 .update(cx, |editor, cx| editor.highlighted_display_rows(cx));
5512 let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
5513 start_anchor..end_anchor,
5514 &snapshot.display_snapshot,
5515 cx.theme().colors(),
5516 );
5517 let highlighted_gutter_ranges =
5518 self.editor.read(cx).gutter_highlights_in_range(
5519 start_anchor..end_anchor,
5520 &snapshot.display_snapshot,
5521 cx,
5522 );
5523
5524 let redacted_ranges = self.editor.read(cx).redacted_ranges(
5525 start_anchor..end_anchor,
5526 &snapshot.display_snapshot,
5527 cx,
5528 );
5529
5530 let local_selections: Vec<Selection<Point>> =
5531 self.editor.update(cx, |editor, cx| {
5532 let mut selections = editor
5533 .selections
5534 .disjoint_in_range(start_anchor..end_anchor, cx);
5535 selections.extend(editor.selections.pending(cx));
5536 selections
5537 });
5538
5539 let (selections, active_rows, newest_selection_head) = self.layout_selections(
5540 start_anchor,
5541 end_anchor,
5542 &local_selections,
5543 &snapshot,
5544 start_row,
5545 end_row,
5546 cx,
5547 );
5548
5549 let line_numbers = self.layout_line_numbers(
5550 start_row..end_row,
5551 buffer_rows.iter().copied(),
5552 &active_rows,
5553 newest_selection_head,
5554 &snapshot,
5555 cx,
5556 );
5557
5558 let mut crease_toggles = cx.with_element_namespace("crease_toggles", |cx| {
5559 self.layout_crease_toggles(
5560 start_row..end_row,
5561 buffer_rows.iter().copied(),
5562 &active_rows,
5563 &snapshot,
5564 cx,
5565 )
5566 });
5567 let crease_trailers = cx.with_element_namespace("crease_trailers", |cx| {
5568 self.layout_crease_trailers(buffer_rows.iter().copied(), &snapshot, cx)
5569 });
5570
5571 let display_hunks = self.layout_gutter_git_hunks(
5572 line_height,
5573 &gutter_hitbox,
5574 start_row..end_row,
5575 start_anchor..end_anchor,
5576 &snapshot,
5577 cx,
5578 );
5579
5580 let mut max_visible_line_width = Pixels::ZERO;
5581 let mut line_layouts = Self::layout_lines(
5582 start_row..end_row,
5583 &snapshot,
5584 &self.style,
5585 editor_width,
5586 is_row_soft_wrapped,
5587 cx,
5588 );
5589 for line_with_invisibles in &line_layouts {
5590 if line_with_invisibles.width > max_visible_line_width {
5591 max_visible_line_width = line_with_invisibles.width;
5592 }
5593 }
5594
5595 let longest_line_width = layout_line(
5596 snapshot.longest_row(),
5597 &snapshot,
5598 &style,
5599 editor_width,
5600 is_row_soft_wrapped,
5601 cx,
5602 )
5603 .width;
5604 let mut scroll_width =
5605 longest_line_width.max(max_visible_line_width) + overscroll.width;
5606
5607 let blocks = cx.with_element_namespace("blocks", |cx| {
5608 self.render_blocks(
5609 start_row..end_row,
5610 &snapshot,
5611 &hitbox,
5612 &text_hitbox,
5613 editor_width,
5614 &mut scroll_width,
5615 &gutter_dimensions,
5616 em_width,
5617 gutter_dimensions.full_width(),
5618 line_height,
5619 &line_layouts,
5620 &local_selections,
5621 is_row_soft_wrapped,
5622 cx,
5623 )
5624 });
5625 let mut blocks = match blocks {
5626 Ok(blocks) => blocks,
5627 Err(resized_blocks) => {
5628 self.editor.update(cx, |editor, cx| {
5629 editor.resize_blocks(resized_blocks, autoscroll_request, cx)
5630 });
5631 return self.prepaint(None, bounds, &mut (), cx);
5632 }
5633 };
5634
5635 let start_buffer_row =
5636 MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
5637 let end_buffer_row =
5638 MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
5639
5640 let scroll_max = point(
5641 ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
5642 max_row.as_f32(),
5643 );
5644
5645 self.editor.update(cx, |editor, cx| {
5646 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
5647
5648 let autoscrolled = if autoscroll_horizontally {
5649 editor.autoscroll_horizontally(
5650 start_row,
5651 text_hitbox.size.width,
5652 scroll_width,
5653 em_width,
5654 &line_layouts,
5655 cx,
5656 )
5657 } else {
5658 false
5659 };
5660
5661 if clamped || autoscrolled {
5662 snapshot = editor.snapshot(cx);
5663 scroll_position = snapshot.scroll_position();
5664 }
5665 });
5666
5667 let scroll_pixel_position = point(
5668 scroll_position.x * em_width,
5669 scroll_position.y * line_height,
5670 );
5671
5672 let indent_guides = self.layout_indent_guides(
5673 content_origin,
5674 text_hitbox.origin,
5675 start_buffer_row..end_buffer_row,
5676 scroll_pixel_position,
5677 line_height,
5678 &snapshot,
5679 cx,
5680 );
5681
5682 let crease_trailers = cx.with_element_namespace("crease_trailers", |cx| {
5683 self.prepaint_crease_trailers(
5684 crease_trailers,
5685 &line_layouts,
5686 line_height,
5687 content_origin,
5688 scroll_pixel_position,
5689 em_width,
5690 cx,
5691 )
5692 });
5693
5694 let mut inline_blame = None;
5695 if let Some(newest_selection_head) = newest_selection_head {
5696 let display_row = newest_selection_head.row();
5697 if (start_row..end_row).contains(&display_row) {
5698 let line_ix = display_row.minus(start_row) as usize;
5699 let line_layout = &line_layouts[line_ix];
5700 let crease_trailer_layout = crease_trailers[line_ix].as_ref();
5701 inline_blame = self.layout_inline_blame(
5702 display_row,
5703 &snapshot.display_snapshot,
5704 line_layout,
5705 crease_trailer_layout,
5706 em_width,
5707 content_origin,
5708 scroll_pixel_position,
5709 line_height,
5710 cx,
5711 );
5712 }
5713 }
5714
5715 let blamed_display_rows = self.layout_blame_entries(
5716 buffer_rows.into_iter(),
5717 em_width,
5718 scroll_position,
5719 line_height,
5720 &gutter_hitbox,
5721 gutter_dimensions.git_blame_entries_width,
5722 cx,
5723 );
5724
5725 let scroll_max = point(
5726 ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
5727 max_scroll_top,
5728 );
5729
5730 self.editor.update(cx, |editor, cx| {
5731 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
5732
5733 let autoscrolled = if autoscroll_horizontally {
5734 editor.autoscroll_horizontally(
5735 start_row,
5736 text_hitbox.size.width,
5737 scroll_width,
5738 em_width,
5739 &line_layouts,
5740 cx,
5741 )
5742 } else {
5743 false
5744 };
5745
5746 if clamped || autoscrolled {
5747 snapshot = editor.snapshot(cx);
5748 scroll_position = snapshot.scroll_position();
5749 }
5750 });
5751
5752 let line_elements = self.prepaint_lines(
5753 start_row,
5754 &mut line_layouts,
5755 line_height,
5756 scroll_pixel_position,
5757 content_origin,
5758 cx,
5759 );
5760
5761 let mut block_start_rows = HashSet::default();
5762 cx.with_element_namespace("blocks", |cx| {
5763 self.layout_blocks(
5764 &mut blocks,
5765 &mut block_start_rows,
5766 &hitbox,
5767 line_height,
5768 scroll_pixel_position,
5769 cx,
5770 );
5771 });
5772
5773 let cursors = self.collect_cursors(&snapshot, cx);
5774 let visible_row_range = start_row..end_row;
5775 let non_visible_cursors = cursors
5776 .iter()
5777 .any(move |c| !visible_row_range.contains(&c.0.row()));
5778
5779 let visible_cursors = self.layout_visible_cursors(
5780 &snapshot,
5781 &selections,
5782 &block_start_rows,
5783 start_row..end_row,
5784 &line_layouts,
5785 &text_hitbox,
5786 content_origin,
5787 scroll_position,
5788 scroll_pixel_position,
5789 line_height,
5790 em_width,
5791 autoscroll_containing_element,
5792 cx,
5793 );
5794
5795 let scrollbar_layout = self.layout_scrollbar(
5796 &snapshot,
5797 bounds,
5798 scroll_position,
5799 height_in_lines,
5800 non_visible_cursors,
5801 cx,
5802 );
5803
5804 let gutter_settings = EditorSettings::get_global(cx).gutter;
5805
5806 let expanded_add_hunks_by_rows = self.editor.update(cx, |editor, _| {
5807 editor
5808 .diff_map
5809 .hunks(false)
5810 .filter(|hunk| hunk.status == DiffHunkStatus::Added)
5811 .map(|expanded_hunk| {
5812 let start_row = expanded_hunk
5813 .hunk_range
5814 .start
5815 .to_display_point(&snapshot)
5816 .row();
5817 (start_row, expanded_hunk.clone())
5818 })
5819 .collect::<HashMap<_, _>>()
5820 });
5821
5822 let rows_with_hunk_bounds = display_hunks
5823 .iter()
5824 .filter_map(|(hunk, hitbox)| Some((hunk, hitbox.as_ref()?.bounds)))
5825 .fold(
5826 HashMap::default(),
5827 |mut rows_with_hunk_bounds, (hunk, bounds)| {
5828 match hunk {
5829 DisplayDiffHunk::Folded { display_row } => {
5830 rows_with_hunk_bounds.insert(*display_row, bounds);
5831 }
5832 DisplayDiffHunk::Unfolded {
5833 display_row_range, ..
5834 } => {
5835 for display_row in display_row_range.iter_rows() {
5836 rows_with_hunk_bounds.insert(display_row, bounds);
5837 }
5838 }
5839 }
5840 rows_with_hunk_bounds
5841 },
5842 );
5843 let mut _context_menu_visible = false;
5844 let mut code_actions_indicator = None;
5845 if let Some(newest_selection_head) = newest_selection_head {
5846 if (start_row..end_row).contains(&newest_selection_head.row()) {
5847 _context_menu_visible = self.layout_context_menu(
5848 line_height,
5849 &hitbox,
5850 &text_hitbox,
5851 content_origin,
5852 start_row,
5853 scroll_pixel_position,
5854 &line_layouts,
5855 newest_selection_head,
5856 gutter_dimensions.width - gutter_dimensions.left_padding,
5857 cx,
5858 );
5859
5860 let show_code_actions = snapshot
5861 .show_code_actions
5862 .unwrap_or(gutter_settings.code_actions);
5863 if show_code_actions {
5864 let newest_selection_point =
5865 newest_selection_head.to_point(&snapshot.display_snapshot);
5866 let newest_selection_display_row =
5867 newest_selection_point.to_display_point(&snapshot).row();
5868 if !expanded_add_hunks_by_rows
5869 .contains_key(&newest_selection_display_row)
5870 {
5871 if !snapshot
5872 .is_line_folded(MultiBufferRow(newest_selection_point.row))
5873 {
5874 let buffer = snapshot.buffer_snapshot.buffer_line_for_row(
5875 MultiBufferRow(newest_selection_point.row),
5876 );
5877 if let Some((buffer, range)) = buffer {
5878 let buffer_id = buffer.remote_id();
5879 let row = range.start.row;
5880 let has_test_indicator = self
5881 .editor
5882 .read(cx)
5883 .tasks
5884 .contains_key(&(buffer_id, row));
5885
5886 if !has_test_indicator {
5887 code_actions_indicator = self
5888 .layout_code_actions_indicator(
5889 line_height,
5890 newest_selection_head,
5891 scroll_pixel_position,
5892 &gutter_dimensions,
5893 &gutter_hitbox,
5894 &rows_with_hunk_bounds,
5895 cx,
5896 );
5897 }
5898 }
5899 }
5900 }
5901 }
5902 }
5903 }
5904
5905 let test_indicators = if gutter_settings.runnables {
5906 self.layout_run_indicators(
5907 line_height,
5908 start_row..end_row,
5909 scroll_pixel_position,
5910 &gutter_dimensions,
5911 &gutter_hitbox,
5912 &rows_with_hunk_bounds,
5913 &snapshot,
5914 cx,
5915 )
5916 } else {
5917 Vec::new()
5918 };
5919
5920 self.layout_signature_help(
5921 &hitbox,
5922 content_origin,
5923 scroll_pixel_position,
5924 newest_selection_head,
5925 start_row,
5926 &line_layouts,
5927 line_height,
5928 em_width,
5929 cx,
5930 );
5931
5932 if !cx.has_active_drag() {
5933 self.layout_hover_popovers(
5934 &snapshot,
5935 &hitbox,
5936 &text_hitbox,
5937 start_row..end_row,
5938 content_origin,
5939 scroll_pixel_position,
5940 &line_layouts,
5941 line_height,
5942 em_width,
5943 cx,
5944 );
5945 }
5946
5947 let inline_completion_popover = self.layout_inline_completion_popover(
5948 &text_hitbox.bounds,
5949 &snapshot,
5950 start_row..end_row,
5951 scroll_position.y,
5952 scroll_position.y + height_in_lines,
5953 &line_layouts,
5954 line_height,
5955 scroll_pixel_position,
5956 editor_width,
5957 &style,
5958 cx,
5959 );
5960
5961 let mouse_context_menu = self.layout_mouse_context_menu(
5962 &snapshot,
5963 start_row..end_row,
5964 content_origin,
5965 cx,
5966 );
5967
5968 cx.with_element_namespace("crease_toggles", |cx| {
5969 self.prepaint_crease_toggles(
5970 &mut crease_toggles,
5971 line_height,
5972 &gutter_dimensions,
5973 gutter_settings,
5974 scroll_pixel_position,
5975 &gutter_hitbox,
5976 cx,
5977 )
5978 });
5979
5980 let invisible_symbol_font_size = font_size / 2.;
5981 let tab_invisible = cx
5982 .text_system()
5983 .shape_line(
5984 "→".into(),
5985 invisible_symbol_font_size,
5986 &[TextRun {
5987 len: "→".len(),
5988 font: self.style.text.font(),
5989 color: cx.theme().colors().editor_invisible,
5990 background_color: None,
5991 underline: None,
5992 strikethrough: None,
5993 }],
5994 )
5995 .unwrap();
5996 let space_invisible = cx
5997 .text_system()
5998 .shape_line(
5999 "•".into(),
6000 invisible_symbol_font_size,
6001 &[TextRun {
6002 len: "•".len(),
6003 font: self.style.text.font(),
6004 color: cx.theme().colors().editor_invisible,
6005 background_color: None,
6006 underline: None,
6007 strikethrough: None,
6008 }],
6009 )
6010 .unwrap();
6011
6012 EditorLayout {
6013 mode: snapshot.mode,
6014 position_map: Rc::new(PositionMap {
6015 size: bounds.size,
6016 scroll_pixel_position,
6017 scroll_max,
6018 line_layouts,
6019 line_height,
6020 em_width,
6021 em_advance,
6022 snapshot,
6023 }),
6024 visible_display_row_range: start_row..end_row,
6025 wrap_guides,
6026 indent_guides,
6027 hitbox,
6028 text_hitbox,
6029 gutter_hitbox,
6030 gutter_dimensions,
6031 display_hunks,
6032 content_origin,
6033 scrollbar_layout,
6034 active_rows,
6035 highlighted_rows,
6036 highlighted_ranges,
6037 highlighted_gutter_ranges,
6038 redacted_ranges,
6039 line_elements,
6040 line_numbers,
6041 blamed_display_rows,
6042 inline_blame,
6043 blocks,
6044 cursors,
6045 visible_cursors,
6046 selections,
6047 inline_completion_popover,
6048 mouse_context_menu,
6049 test_indicators,
6050 code_actions_indicator,
6051 crease_toggles,
6052 crease_trailers,
6053 tab_invisible,
6054 space_invisible,
6055 }
6056 })
6057 })
6058 })
6059 }
6060
6061 fn paint(
6062 &mut self,
6063 _: Option<&GlobalElementId>,
6064 bounds: Bounds<gpui::Pixels>,
6065 _: &mut Self::RequestLayoutState,
6066 layout: &mut Self::PrepaintState,
6067 cx: &mut WindowContext,
6068 ) {
6069 let focus_handle = self.editor.focus_handle(cx);
6070 let key_context = self.editor.update(cx, |editor, cx| editor.key_context(cx));
6071 cx.set_key_context(key_context);
6072 cx.handle_input(
6073 &focus_handle,
6074 ElementInputHandler::new(bounds, self.editor.clone()),
6075 );
6076 self.register_actions(cx);
6077 self.register_key_listeners(cx, layout);
6078
6079 let text_style = TextStyleRefinement {
6080 font_size: Some(self.style.text.font_size),
6081 line_height: Some(self.style.text.line_height),
6082 ..Default::default()
6083 };
6084 let hovered_hunk = layout
6085 .display_hunks
6086 .iter()
6087 .find_map(|(hunk, hunk_hitbox)| match hunk {
6088 DisplayDiffHunk::Folded { .. } => None,
6089 DisplayDiffHunk::Unfolded {
6090 diff_base_byte_range,
6091 multi_buffer_range,
6092 status,
6093 ..
6094 } => {
6095 if hunk_hitbox
6096 .as_ref()
6097 .map(|hitbox| hitbox.is_hovered(cx))
6098 .unwrap_or(false)
6099 {
6100 Some(HoveredHunk {
6101 status: *status,
6102 multi_buffer_range: multi_buffer_range.clone(),
6103 diff_base_byte_range: diff_base_byte_range.clone(),
6104 })
6105 } else {
6106 None
6107 }
6108 }
6109 });
6110 let rem_size = self.rem_size(cx);
6111 cx.with_rem_size(rem_size, |cx| {
6112 cx.with_text_style(Some(text_style), |cx| {
6113 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
6114 self.paint_mouse_listeners(layout, hovered_hunk, cx);
6115 self.paint_background(layout, cx);
6116 self.paint_indent_guides(layout, cx);
6117
6118 if layout.gutter_hitbox.size.width > Pixels::ZERO {
6119 self.paint_blamed_display_rows(layout, cx);
6120 self.paint_line_numbers(layout, cx);
6121 }
6122
6123 self.paint_text(layout, cx);
6124
6125 if layout.gutter_hitbox.size.width > Pixels::ZERO {
6126 self.paint_gutter_highlights(layout, cx);
6127 self.paint_gutter_indicators(layout, cx);
6128 }
6129
6130 if !layout.blocks.is_empty() {
6131 cx.with_element_namespace("blocks", |cx| {
6132 self.paint_blocks(layout, cx);
6133 });
6134 }
6135
6136 self.paint_scrollbar(layout, cx);
6137 self.paint_inline_completion_popover(layout, cx);
6138 self.paint_mouse_context_menu(layout, cx);
6139 });
6140 })
6141 })
6142 }
6143}
6144
6145pub(super) fn gutter_bounds(
6146 editor_bounds: Bounds<Pixels>,
6147 gutter_dimensions: GutterDimensions,
6148) -> Bounds<Pixels> {
6149 Bounds {
6150 origin: editor_bounds.origin,
6151 size: size(gutter_dimensions.width, editor_bounds.size.height),
6152 }
6153}
6154
6155impl IntoElement for EditorElement {
6156 type Element = Self;
6157
6158 fn into_element(self) -> Self::Element {
6159 self
6160 }
6161}
6162
6163pub struct EditorLayout {
6164 position_map: Rc<PositionMap>,
6165 hitbox: Hitbox,
6166 text_hitbox: Hitbox,
6167 gutter_hitbox: Hitbox,
6168 gutter_dimensions: GutterDimensions,
6169 content_origin: gpui::Point<Pixels>,
6170 scrollbar_layout: Option<ScrollbarLayout>,
6171 mode: EditorMode,
6172 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
6173 indent_guides: Option<Vec<IndentGuideLayout>>,
6174 visible_display_row_range: Range<DisplayRow>,
6175 active_rows: BTreeMap<DisplayRow, bool>,
6176 highlighted_rows: BTreeMap<DisplayRow, Hsla>,
6177 line_elements: SmallVec<[AnyElement; 1]>,
6178 line_numbers: Vec<Option<ShapedLine>>,
6179 display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
6180 blamed_display_rows: Option<Vec<AnyElement>>,
6181 inline_blame: Option<AnyElement>,
6182 blocks: Vec<BlockLayout>,
6183 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
6184 highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
6185 redacted_ranges: Vec<Range<DisplayPoint>>,
6186 cursors: Vec<(DisplayPoint, Hsla)>,
6187 visible_cursors: Vec<CursorLayout>,
6188 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
6189 code_actions_indicator: Option<AnyElement>,
6190 test_indicators: Vec<AnyElement>,
6191 crease_toggles: Vec<Option<AnyElement>>,
6192 crease_trailers: Vec<Option<CreaseTrailerLayout>>,
6193 inline_completion_popover: Option<AnyElement>,
6194 mouse_context_menu: Option<AnyElement>,
6195 tab_invisible: ShapedLine,
6196 space_invisible: ShapedLine,
6197}
6198
6199impl EditorLayout {
6200 fn line_end_overshoot(&self) -> Pixels {
6201 0.15 * self.position_map.line_height
6202 }
6203}
6204
6205struct ColoredRange<T> {
6206 start: T,
6207 end: T,
6208 color: Hsla,
6209}
6210
6211#[derive(Clone)]
6212struct ScrollbarLayout {
6213 hitbox: Hitbox,
6214 visible_row_range: Range<f32>,
6215 visible: bool,
6216 row_height: Pixels,
6217 thumb_height: Pixels,
6218}
6219
6220impl ScrollbarLayout {
6221 const BORDER_WIDTH: Pixels = px(1.0);
6222 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
6223 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
6224 const MIN_THUMB_HEIGHT: Pixels = px(20.0);
6225
6226 fn thumb_bounds(&self) -> Bounds<Pixels> {
6227 let thumb_top = self.y_for_row(self.visible_row_range.start);
6228 let thumb_bottom = thumb_top + self.thumb_height;
6229 Bounds::from_corners(
6230 point(self.hitbox.left(), thumb_top),
6231 point(self.hitbox.right(), thumb_bottom),
6232 )
6233 }
6234
6235 fn y_for_row(&self, row: f32) -> Pixels {
6236 self.hitbox.top() + row * self.row_height
6237 }
6238
6239 fn marker_quads_for_ranges(
6240 &self,
6241 row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
6242 column: Option<usize>,
6243 ) -> Vec<PaintQuad> {
6244 struct MinMax {
6245 min: Pixels,
6246 max: Pixels,
6247 }
6248 let (x_range, height_limit) = if let Some(column) = column {
6249 let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
6250 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
6251 let end = start + column_width;
6252 (
6253 Range { start, end },
6254 MinMax {
6255 min: Self::MIN_MARKER_HEIGHT,
6256 max: px(f32::MAX),
6257 },
6258 )
6259 } else {
6260 (
6261 Range {
6262 start: Self::BORDER_WIDTH,
6263 end: self.hitbox.size.width,
6264 },
6265 MinMax {
6266 min: Self::LINE_MARKER_HEIGHT,
6267 max: Self::LINE_MARKER_HEIGHT,
6268 },
6269 )
6270 };
6271
6272 let row_to_y = |row: DisplayRow| row.as_f32() * self.row_height;
6273 let mut pixel_ranges = row_ranges
6274 .into_iter()
6275 .map(|range| {
6276 let start_y = row_to_y(range.start);
6277 let end_y = row_to_y(range.end)
6278 + self.row_height.max(height_limit.min).min(height_limit.max);
6279 ColoredRange {
6280 start: start_y,
6281 end: end_y,
6282 color: range.color,
6283 }
6284 })
6285 .peekable();
6286
6287 let mut quads = Vec::new();
6288 while let Some(mut pixel_range) = pixel_ranges.next() {
6289 while let Some(next_pixel_range) = pixel_ranges.peek() {
6290 if pixel_range.end >= next_pixel_range.start - px(1.0)
6291 && pixel_range.color == next_pixel_range.color
6292 {
6293 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
6294 pixel_ranges.next();
6295 } else {
6296 break;
6297 }
6298 }
6299
6300 let bounds = Bounds::from_corners(
6301 point(x_range.start, pixel_range.start),
6302 point(x_range.end, pixel_range.end),
6303 );
6304 quads.push(quad(
6305 bounds,
6306 Corners::default(),
6307 pixel_range.color,
6308 Edges::default(),
6309 Hsla::transparent_black(),
6310 ));
6311 }
6312
6313 quads
6314 }
6315}
6316
6317struct CreaseTrailerLayout {
6318 element: AnyElement,
6319 bounds: Bounds<Pixels>,
6320}
6321
6322struct PositionMap {
6323 size: Size<Pixels>,
6324 line_height: Pixels,
6325 scroll_pixel_position: gpui::Point<Pixels>,
6326 scroll_max: gpui::Point<f32>,
6327 em_width: Pixels,
6328 em_advance: Pixels,
6329 line_layouts: Vec<LineWithInvisibles>,
6330 snapshot: EditorSnapshot,
6331}
6332
6333#[derive(Debug, Copy, Clone)]
6334pub struct PointForPosition {
6335 pub previous_valid: DisplayPoint,
6336 pub next_valid: DisplayPoint,
6337 pub exact_unclipped: DisplayPoint,
6338 pub column_overshoot_after_line_end: u32,
6339}
6340
6341impl PointForPosition {
6342 pub fn as_valid(&self) -> Option<DisplayPoint> {
6343 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
6344 Some(self.previous_valid)
6345 } else {
6346 None
6347 }
6348 }
6349}
6350
6351impl PositionMap {
6352 fn point_for_position(
6353 &self,
6354 text_bounds: Bounds<Pixels>,
6355 position: gpui::Point<Pixels>,
6356 ) -> PointForPosition {
6357 let scroll_position = self.snapshot.scroll_position();
6358 let position = position - text_bounds.origin;
6359 let y = position.y.max(px(0.)).min(self.size.height);
6360 let x = position.x + (scroll_position.x * self.em_width);
6361 let row = ((y / self.line_height) + scroll_position.y) as u32;
6362
6363 let (column, x_overshoot_after_line_end) = if let Some(line) = self
6364 .line_layouts
6365 .get(row as usize - scroll_position.y as usize)
6366 {
6367 if let Some(ix) = line.index_for_x(x) {
6368 (ix as u32, px(0.))
6369 } else {
6370 (line.len as u32, px(0.).max(x - line.width))
6371 }
6372 } else {
6373 (0, x)
6374 };
6375
6376 let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
6377 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
6378 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
6379
6380 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
6381 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
6382 PointForPosition {
6383 previous_valid,
6384 next_valid,
6385 exact_unclipped,
6386 column_overshoot_after_line_end,
6387 }
6388 }
6389}
6390
6391struct BlockLayout {
6392 id: BlockId,
6393 row: Option<DisplayRow>,
6394 element: AnyElement,
6395 available_space: Size<AvailableSpace>,
6396 style: BlockStyle,
6397}
6398
6399fn layout_line(
6400 row: DisplayRow,
6401 snapshot: &EditorSnapshot,
6402 style: &EditorStyle,
6403 text_width: Pixels,
6404 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
6405 cx: &mut WindowContext,
6406) -> LineWithInvisibles {
6407 let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
6408 LineWithInvisibles::from_chunks(
6409 chunks,
6410 &style,
6411 MAX_LINE_LEN,
6412 1,
6413 snapshot.mode,
6414 text_width,
6415 is_row_soft_wrapped,
6416 cx,
6417 )
6418 .pop()
6419 .unwrap()
6420}
6421
6422#[derive(Debug)]
6423pub struct IndentGuideLayout {
6424 origin: gpui::Point<Pixels>,
6425 length: Pixels,
6426 single_indent_width: Pixels,
6427 depth: u32,
6428 active: bool,
6429 settings: IndentGuideSettings,
6430}
6431
6432pub struct CursorLayout {
6433 origin: gpui::Point<Pixels>,
6434 block_width: Pixels,
6435 line_height: Pixels,
6436 color: Hsla,
6437 shape: CursorShape,
6438 block_text: Option<ShapedLine>,
6439 cursor_name: Option<AnyElement>,
6440}
6441
6442#[derive(Debug)]
6443pub struct CursorName {
6444 string: SharedString,
6445 color: Hsla,
6446 is_top_row: bool,
6447}
6448
6449impl CursorLayout {
6450 pub fn new(
6451 origin: gpui::Point<Pixels>,
6452 block_width: Pixels,
6453 line_height: Pixels,
6454 color: Hsla,
6455 shape: CursorShape,
6456 block_text: Option<ShapedLine>,
6457 ) -> CursorLayout {
6458 CursorLayout {
6459 origin,
6460 block_width,
6461 line_height,
6462 color,
6463 shape,
6464 block_text,
6465 cursor_name: None,
6466 }
6467 }
6468
6469 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
6470 Bounds {
6471 origin: self.origin + origin,
6472 size: size(self.block_width, self.line_height),
6473 }
6474 }
6475
6476 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
6477 match self.shape {
6478 CursorShape::Bar => Bounds {
6479 origin: self.origin + origin,
6480 size: size(px(2.0), self.line_height),
6481 },
6482 CursorShape::Block | CursorShape::Hollow => Bounds {
6483 origin: self.origin + origin,
6484 size: size(self.block_width, self.line_height),
6485 },
6486 CursorShape::Underline => Bounds {
6487 origin: self.origin
6488 + origin
6489 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
6490 size: size(self.block_width, px(2.0)),
6491 },
6492 }
6493 }
6494
6495 pub fn layout(
6496 &mut self,
6497 origin: gpui::Point<Pixels>,
6498 cursor_name: Option<CursorName>,
6499 cx: &mut WindowContext,
6500 ) {
6501 if let Some(cursor_name) = cursor_name {
6502 let bounds = self.bounds(origin);
6503 let text_size = self.line_height / 1.5;
6504
6505 let name_origin = if cursor_name.is_top_row {
6506 point(bounds.right() - px(1.), bounds.top())
6507 } else {
6508 point(bounds.left(), bounds.top() - text_size / 2. - px(1.))
6509 };
6510 let mut name_element = div()
6511 .bg(self.color)
6512 .text_size(text_size)
6513 .px_0p5()
6514 .line_height(text_size + px(2.))
6515 .text_color(cursor_name.color)
6516 .child(cursor_name.string.clone())
6517 .into_any_element();
6518
6519 name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), cx);
6520
6521 self.cursor_name = Some(name_element);
6522 }
6523 }
6524
6525 pub fn paint(&mut self, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
6526 let bounds = self.bounds(origin);
6527
6528 //Draw background or border quad
6529 let cursor = if matches!(self.shape, CursorShape::Hollow) {
6530 outline(bounds, self.color)
6531 } else {
6532 fill(bounds, self.color)
6533 };
6534
6535 if let Some(name) = &mut self.cursor_name {
6536 name.paint(cx);
6537 }
6538
6539 cx.paint_quad(cursor);
6540
6541 if let Some(block_text) = &self.block_text {
6542 block_text
6543 .paint(self.origin + origin, self.line_height, cx)
6544 .log_err();
6545 }
6546 }
6547
6548 pub fn shape(&self) -> CursorShape {
6549 self.shape
6550 }
6551}
6552
6553#[derive(Debug)]
6554pub struct HighlightedRange {
6555 pub start_y: Pixels,
6556 pub line_height: Pixels,
6557 pub lines: Vec<HighlightedRangeLine>,
6558 pub color: Hsla,
6559 pub corner_radius: Pixels,
6560}
6561
6562#[derive(Debug)]
6563pub struct HighlightedRangeLine {
6564 pub start_x: Pixels,
6565 pub end_x: Pixels,
6566}
6567
6568impl HighlightedRange {
6569 pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut WindowContext) {
6570 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
6571 self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
6572 self.paint_lines(
6573 self.start_y + self.line_height,
6574 &self.lines[1..],
6575 bounds,
6576 cx,
6577 );
6578 } else {
6579 self.paint_lines(self.start_y, &self.lines, bounds, cx);
6580 }
6581 }
6582
6583 fn paint_lines(
6584 &self,
6585 start_y: Pixels,
6586 lines: &[HighlightedRangeLine],
6587 _bounds: Bounds<Pixels>,
6588 cx: &mut WindowContext,
6589 ) {
6590 if lines.is_empty() {
6591 return;
6592 }
6593
6594 let first_line = lines.first().unwrap();
6595 let last_line = lines.last().unwrap();
6596
6597 let first_top_left = point(first_line.start_x, start_y);
6598 let first_top_right = point(first_line.end_x, start_y);
6599
6600 let curve_height = point(Pixels::ZERO, self.corner_radius);
6601 let curve_width = |start_x: Pixels, end_x: Pixels| {
6602 let max = (end_x - start_x) / 2.;
6603 let width = if max < self.corner_radius {
6604 max
6605 } else {
6606 self.corner_radius
6607 };
6608
6609 point(width, Pixels::ZERO)
6610 };
6611
6612 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
6613 let mut path = gpui::Path::new(first_top_right - top_curve_width);
6614 path.curve_to(first_top_right + curve_height, first_top_right);
6615
6616 let mut iter = lines.iter().enumerate().peekable();
6617 while let Some((ix, line)) = iter.next() {
6618 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
6619
6620 if let Some((_, next_line)) = iter.peek() {
6621 let next_top_right = point(next_line.end_x, bottom_right.y);
6622
6623 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
6624 Ordering::Equal => {
6625 path.line_to(bottom_right);
6626 }
6627 Ordering::Less => {
6628 let curve_width = curve_width(next_top_right.x, bottom_right.x);
6629 path.line_to(bottom_right - curve_height);
6630 if self.corner_radius > Pixels::ZERO {
6631 path.curve_to(bottom_right - curve_width, bottom_right);
6632 }
6633 path.line_to(next_top_right + curve_width);
6634 if self.corner_radius > Pixels::ZERO {
6635 path.curve_to(next_top_right + curve_height, next_top_right);
6636 }
6637 }
6638 Ordering::Greater => {
6639 let curve_width = curve_width(bottom_right.x, next_top_right.x);
6640 path.line_to(bottom_right - curve_height);
6641 if self.corner_radius > Pixels::ZERO {
6642 path.curve_to(bottom_right + curve_width, bottom_right);
6643 }
6644 path.line_to(next_top_right - curve_width);
6645 if self.corner_radius > Pixels::ZERO {
6646 path.curve_to(next_top_right + curve_height, next_top_right);
6647 }
6648 }
6649 }
6650 } else {
6651 let curve_width = curve_width(line.start_x, line.end_x);
6652 path.line_to(bottom_right - curve_height);
6653 if self.corner_radius > Pixels::ZERO {
6654 path.curve_to(bottom_right - curve_width, bottom_right);
6655 }
6656
6657 let bottom_left = point(line.start_x, bottom_right.y);
6658 path.line_to(bottom_left + curve_width);
6659 if self.corner_radius > Pixels::ZERO {
6660 path.curve_to(bottom_left - curve_height, bottom_left);
6661 }
6662 }
6663 }
6664
6665 if first_line.start_x > last_line.start_x {
6666 let curve_width = curve_width(last_line.start_x, first_line.start_x);
6667 let second_top_left = point(last_line.start_x, start_y + self.line_height);
6668 path.line_to(second_top_left + curve_height);
6669 if self.corner_radius > Pixels::ZERO {
6670 path.curve_to(second_top_left + curve_width, second_top_left);
6671 }
6672 let first_bottom_left = point(first_line.start_x, second_top_left.y);
6673 path.line_to(first_bottom_left - curve_width);
6674 if self.corner_radius > Pixels::ZERO {
6675 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
6676 }
6677 }
6678
6679 path.line_to(first_top_left + curve_height);
6680 if self.corner_radius > Pixels::ZERO {
6681 path.curve_to(first_top_left + top_curve_width, first_top_left);
6682 }
6683 path.line_to(first_top_right - top_curve_width);
6684
6685 cx.paint_path(path, self.color);
6686 }
6687}
6688
6689pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
6690 (delta.pow(1.5) / 100.0).into()
6691}
6692
6693fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
6694 (delta.pow(1.2) / 300.0).into()
6695}
6696
6697pub fn register_action<T: Action>(
6698 view: &View<Editor>,
6699 cx: &mut WindowContext,
6700 listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
6701) {
6702 let view = view.clone();
6703 cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
6704 let action = action.downcast_ref().unwrap();
6705 if phase == DispatchPhase::Bubble {
6706 view.update(cx, |editor, cx| {
6707 listener(editor, action, cx);
6708 })
6709 }
6710 })
6711}
6712
6713fn compute_auto_height_layout(
6714 editor: &mut Editor,
6715 max_lines: usize,
6716 max_line_number_width: Pixels,
6717 known_dimensions: Size<Option<Pixels>>,
6718 available_width: AvailableSpace,
6719 cx: &mut ViewContext<Editor>,
6720) -> Option<Size<Pixels>> {
6721 let width = known_dimensions.width.or({
6722 if let AvailableSpace::Definite(available_width) = available_width {
6723 Some(available_width)
6724 } else {
6725 None
6726 }
6727 })?;
6728 if let Some(height) = known_dimensions.height {
6729 return Some(size(width, height));
6730 }
6731
6732 let style = editor.style.as_ref().unwrap();
6733 let font_id = cx.text_system().resolve_font(&style.text.font());
6734 let font_size = style.text.font_size.to_pixels(cx.rem_size());
6735 let line_height = style.text.line_height_in_pixels(cx.rem_size());
6736 let em_width = cx
6737 .text_system()
6738 .typographic_bounds(font_id, font_size, 'm')
6739 .unwrap()
6740 .size
6741 .width;
6742 let em_advance = cx
6743 .text_system()
6744 .advance(font_id, font_size, 'm')
6745 .unwrap()
6746 .width;
6747
6748 let mut snapshot = editor.snapshot(cx);
6749 let gutter_dimensions = snapshot.gutter_dimensions(
6750 font_id,
6751 font_size,
6752 em_width,
6753 em_advance,
6754 max_line_number_width,
6755 cx,
6756 );
6757
6758 editor.gutter_dimensions = gutter_dimensions;
6759 let text_width = width - gutter_dimensions.width;
6760 let overscroll = size(em_width, px(0.));
6761
6762 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
6763 if editor.set_wrap_width(Some(editor_width), cx) {
6764 snapshot = editor.snapshot(cx);
6765 }
6766
6767 let scroll_height = Pixels::from(snapshot.max_point().row().next_row().0) * line_height;
6768 let height = scroll_height
6769 .max(line_height)
6770 .min(line_height * max_lines as f32);
6771
6772 Some(size(width, height))
6773}
6774
6775#[cfg(test)]
6776mod tests {
6777 use super::*;
6778 use crate::{
6779 display_map::{BlockPlacement, BlockProperties},
6780 editor_tests::{init_test, update_test_language_settings},
6781 Editor, MultiBuffer,
6782 };
6783 use gpui::{TestAppContext, VisualTestContext};
6784 use language::language_settings;
6785 use log::info;
6786 use std::num::NonZeroU32;
6787 use util::test::sample_text;
6788
6789 #[gpui::test]
6790 fn test_shape_line_numbers(cx: &mut TestAppContext) {
6791 init_test(cx, |_| {});
6792 let window = cx.add_window(|cx| {
6793 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
6794 Editor::new(EditorMode::Full, buffer, None, true, cx)
6795 });
6796
6797 let editor = window.root(cx).unwrap();
6798 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6799 let element = EditorElement::new(&editor, style);
6800 let snapshot = window.update(cx, |editor, cx| editor.snapshot(cx)).unwrap();
6801
6802 let layouts = cx
6803 .update_window(*window, |_, cx| {
6804 element.layout_line_numbers(
6805 DisplayRow(0)..DisplayRow(6),
6806 (0..6).map(MultiBufferRow).map(Some),
6807 &Default::default(),
6808 Some(DisplayPoint::new(DisplayRow(0), 0)),
6809 &snapshot,
6810 cx,
6811 )
6812 })
6813 .unwrap();
6814 assert_eq!(layouts.len(), 6);
6815
6816 let relative_rows = window
6817 .update(cx, |editor, cx| {
6818 let snapshot = editor.snapshot(cx);
6819 element.calculate_relative_line_numbers(
6820 &snapshot,
6821 &(DisplayRow(0)..DisplayRow(6)),
6822 Some(DisplayRow(3)),
6823 )
6824 })
6825 .unwrap();
6826 assert_eq!(relative_rows[&DisplayRow(0)], 3);
6827 assert_eq!(relative_rows[&DisplayRow(1)], 2);
6828 assert_eq!(relative_rows[&DisplayRow(2)], 1);
6829 // current line has no relative number
6830 assert_eq!(relative_rows[&DisplayRow(4)], 1);
6831 assert_eq!(relative_rows[&DisplayRow(5)], 2);
6832
6833 // works if cursor is before screen
6834 let relative_rows = window
6835 .update(cx, |editor, cx| {
6836 let snapshot = editor.snapshot(cx);
6837 element.calculate_relative_line_numbers(
6838 &snapshot,
6839 &(DisplayRow(3)..DisplayRow(6)),
6840 Some(DisplayRow(1)),
6841 )
6842 })
6843 .unwrap();
6844 assert_eq!(relative_rows.len(), 3);
6845 assert_eq!(relative_rows[&DisplayRow(3)], 2);
6846 assert_eq!(relative_rows[&DisplayRow(4)], 3);
6847 assert_eq!(relative_rows[&DisplayRow(5)], 4);
6848
6849 // works if cursor is after screen
6850 let relative_rows = window
6851 .update(cx, |editor, cx| {
6852 let snapshot = editor.snapshot(cx);
6853 element.calculate_relative_line_numbers(
6854 &snapshot,
6855 &(DisplayRow(0)..DisplayRow(3)),
6856 Some(DisplayRow(6)),
6857 )
6858 })
6859 .unwrap();
6860 assert_eq!(relative_rows.len(), 3);
6861 assert_eq!(relative_rows[&DisplayRow(0)], 5);
6862 assert_eq!(relative_rows[&DisplayRow(1)], 4);
6863 assert_eq!(relative_rows[&DisplayRow(2)], 3);
6864 }
6865
6866 #[gpui::test]
6867 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
6868 init_test(cx, |_| {});
6869
6870 let window = cx.add_window(|cx| {
6871 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
6872 Editor::new(EditorMode::Full, buffer, None, true, cx)
6873 });
6874 let cx = &mut VisualTestContext::from_window(*window, cx);
6875 let editor = window.root(cx).unwrap();
6876 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6877
6878 window
6879 .update(cx, |editor, cx| {
6880 editor.cursor_shape = CursorShape::Block;
6881 editor.change_selections(None, cx, |s| {
6882 s.select_ranges([
6883 Point::new(0, 0)..Point::new(1, 0),
6884 Point::new(3, 2)..Point::new(3, 3),
6885 Point::new(5, 6)..Point::new(6, 0),
6886 ]);
6887 });
6888 })
6889 .unwrap();
6890
6891 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6892 EditorElement::new(&editor, style)
6893 });
6894
6895 assert_eq!(state.selections.len(), 1);
6896 let local_selections = &state.selections[0].1;
6897 assert_eq!(local_selections.len(), 3);
6898 // moves cursor back one line
6899 assert_eq!(
6900 local_selections[0].head,
6901 DisplayPoint::new(DisplayRow(0), 6)
6902 );
6903 assert_eq!(
6904 local_selections[0].range,
6905 DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
6906 );
6907
6908 // moves cursor back one column
6909 assert_eq!(
6910 local_selections[1].range,
6911 DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
6912 );
6913 assert_eq!(
6914 local_selections[1].head,
6915 DisplayPoint::new(DisplayRow(3), 2)
6916 );
6917
6918 // leaves cursor on the max point
6919 assert_eq!(
6920 local_selections[2].range,
6921 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
6922 );
6923 assert_eq!(
6924 local_selections[2].head,
6925 DisplayPoint::new(DisplayRow(6), 0)
6926 );
6927
6928 // active lines does not include 1 (even though the range of the selection does)
6929 assert_eq!(
6930 state.active_rows.keys().cloned().collect::<Vec<_>>(),
6931 vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
6932 );
6933
6934 // multi-buffer support
6935 // in DisplayPoint coordinates, this is what we're dealing with:
6936 // 0: [[file
6937 // 1: header
6938 // 2: section]]
6939 // 3: aaaaaa
6940 // 4: bbbbbb
6941 // 5: cccccc
6942 // 6:
6943 // 7: [[footer]]
6944 // 8: [[header]]
6945 // 9: ffffff
6946 // 10: gggggg
6947 // 11: hhhhhh
6948 // 12:
6949 // 13: [[footer]]
6950 // 14: [[file
6951 // 15: header
6952 // 16: section]]
6953 // 17: bbbbbb
6954 // 18: cccccc
6955 // 19: dddddd
6956 // 20: [[footer]]
6957 let window = cx.add_window(|cx| {
6958 let buffer = MultiBuffer::build_multi(
6959 [
6960 (
6961 &(sample_text(8, 6, 'a') + "\n"),
6962 vec![
6963 Point::new(0, 0)..Point::new(3, 0),
6964 Point::new(4, 0)..Point::new(7, 0),
6965 ],
6966 ),
6967 (
6968 &(sample_text(8, 6, 'a') + "\n"),
6969 vec![Point::new(1, 0)..Point::new(3, 0)],
6970 ),
6971 ],
6972 cx,
6973 );
6974 Editor::new(EditorMode::Full, buffer, None, true, cx)
6975 });
6976 let editor = window.root(cx).unwrap();
6977 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6978 let _state = window.update(cx, |editor, cx| {
6979 editor.cursor_shape = CursorShape::Block;
6980 editor.change_selections(None, cx, |s| {
6981 s.select_display_ranges([
6982 DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0),
6983 DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0),
6984 ]);
6985 });
6986 });
6987
6988 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6989 EditorElement::new(&editor, style)
6990 });
6991 assert_eq!(state.selections.len(), 1);
6992 let local_selections = &state.selections[0].1;
6993 assert_eq!(local_selections.len(), 2);
6994
6995 // moves cursor on excerpt boundary back a line
6996 // and doesn't allow selection to bleed through
6997 assert_eq!(
6998 local_selections[0].range,
6999 DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0)
7000 );
7001 assert_eq!(
7002 local_selections[0].head,
7003 DisplayPoint::new(DisplayRow(6), 0)
7004 );
7005 // moves cursor on buffer boundary back two lines
7006 // and doesn't allow selection to bleed through
7007 assert_eq!(
7008 local_selections[1].range,
7009 DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0)
7010 );
7011 assert_eq!(
7012 local_selections[1].head,
7013 DisplayPoint::new(DisplayRow(12), 0)
7014 );
7015 }
7016
7017 #[gpui::test]
7018 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
7019 init_test(cx, |_| {});
7020
7021 let window = cx.add_window(|cx| {
7022 let buffer = MultiBuffer::build_simple("", cx);
7023 Editor::new(EditorMode::Full, buffer, None, true, cx)
7024 });
7025 let cx = &mut VisualTestContext::from_window(*window, cx);
7026 let editor = window.root(cx).unwrap();
7027 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
7028 window
7029 .update(cx, |editor, cx| {
7030 editor.set_placeholder_text("hello", cx);
7031 editor.insert_blocks(
7032 [BlockProperties {
7033 style: BlockStyle::Fixed,
7034 placement: BlockPlacement::Above(Anchor::min()),
7035 height: 3,
7036 render: Arc::new(|cx| div().h(3. * cx.line_height()).into_any()),
7037 priority: 0,
7038 }],
7039 None,
7040 cx,
7041 );
7042
7043 // Blur the editor so that it displays placeholder text.
7044 cx.blur();
7045 })
7046 .unwrap();
7047
7048 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
7049 EditorElement::new(&editor, style)
7050 });
7051 assert_eq!(state.position_map.line_layouts.len(), 4);
7052 assert_eq!(
7053 state
7054 .line_numbers
7055 .iter()
7056 .map(Option::is_some)
7057 .collect::<Vec<_>>(),
7058 &[false, false, false, true]
7059 );
7060 }
7061
7062 #[gpui::test]
7063 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
7064 const TAB_SIZE: u32 = 4;
7065
7066 let input_text = "\t \t|\t| a b";
7067 let expected_invisibles = vec![
7068 Invisible::Tab {
7069 line_start_offset: 0,
7070 line_end_offset: TAB_SIZE as usize,
7071 },
7072 Invisible::Whitespace {
7073 line_offset: TAB_SIZE as usize,
7074 },
7075 Invisible::Tab {
7076 line_start_offset: TAB_SIZE as usize + 1,
7077 line_end_offset: TAB_SIZE as usize * 2,
7078 },
7079 Invisible::Tab {
7080 line_start_offset: TAB_SIZE as usize * 2 + 1,
7081 line_end_offset: TAB_SIZE as usize * 3,
7082 },
7083 Invisible::Whitespace {
7084 line_offset: TAB_SIZE as usize * 3 + 1,
7085 },
7086 Invisible::Whitespace {
7087 line_offset: TAB_SIZE as usize * 3 + 3,
7088 },
7089 ];
7090 assert_eq!(
7091 expected_invisibles.len(),
7092 input_text
7093 .chars()
7094 .filter(|initial_char| initial_char.is_whitespace())
7095 .count(),
7096 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
7097 );
7098
7099 for show_line_numbers in [true, false] {
7100 init_test(cx, |s| {
7101 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
7102 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
7103 });
7104
7105 let actual_invisibles = collect_invisibles_from_new_editor(
7106 cx,
7107 EditorMode::Full,
7108 input_text,
7109 px(500.0),
7110 show_line_numbers,
7111 );
7112
7113 assert_eq!(expected_invisibles, actual_invisibles);
7114 }
7115 }
7116
7117 #[gpui::test]
7118 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
7119 init_test(cx, |s| {
7120 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
7121 s.defaults.tab_size = NonZeroU32::new(4);
7122 });
7123
7124 for editor_mode_without_invisibles in [
7125 EditorMode::SingleLine { auto_width: false },
7126 EditorMode::AutoHeight { max_lines: 100 },
7127 ] {
7128 for show_line_numbers in [true, false] {
7129 let invisibles = collect_invisibles_from_new_editor(
7130 cx,
7131 editor_mode_without_invisibles,
7132 "\t\t\t| | a b",
7133 px(500.0),
7134 show_line_numbers,
7135 );
7136 assert!(invisibles.is_empty(),
7137 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
7138 }
7139 }
7140 }
7141
7142 #[gpui::test]
7143 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
7144 let tab_size = 4;
7145 let input_text = "a\tbcd ".repeat(9);
7146 let repeated_invisibles = [
7147 Invisible::Tab {
7148 line_start_offset: 1,
7149 line_end_offset: tab_size as usize,
7150 },
7151 Invisible::Whitespace {
7152 line_offset: tab_size as usize + 3,
7153 },
7154 Invisible::Whitespace {
7155 line_offset: tab_size as usize + 4,
7156 },
7157 Invisible::Whitespace {
7158 line_offset: tab_size as usize + 5,
7159 },
7160 Invisible::Whitespace {
7161 line_offset: tab_size as usize + 6,
7162 },
7163 Invisible::Whitespace {
7164 line_offset: tab_size as usize + 7,
7165 },
7166 ];
7167 let expected_invisibles = std::iter::once(repeated_invisibles)
7168 .cycle()
7169 .take(9)
7170 .flatten()
7171 .collect::<Vec<_>>();
7172 assert_eq!(
7173 expected_invisibles.len(),
7174 input_text
7175 .chars()
7176 .filter(|initial_char| initial_char.is_whitespace())
7177 .count(),
7178 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
7179 );
7180 info!("Expected invisibles: {expected_invisibles:?}");
7181
7182 init_test(cx, |_| {});
7183
7184 // Put the same string with repeating whitespace pattern into editors of various size,
7185 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
7186 let resize_step = 10.0;
7187 let mut editor_width = 200.0;
7188 while editor_width <= 1000.0 {
7189 for show_line_numbers in [true, false] {
7190 update_test_language_settings(cx, |s| {
7191 s.defaults.tab_size = NonZeroU32::new(tab_size);
7192 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
7193 s.defaults.preferred_line_length = Some(editor_width as u32);
7194 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
7195 });
7196
7197 let actual_invisibles = collect_invisibles_from_new_editor(
7198 cx,
7199 EditorMode::Full,
7200 &input_text,
7201 px(editor_width),
7202 show_line_numbers,
7203 );
7204
7205 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
7206 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
7207 let mut i = 0;
7208 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
7209 i = actual_index;
7210 match expected_invisibles.get(i) {
7211 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
7212 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
7213 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
7214 _ => {
7215 panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
7216 }
7217 },
7218 None => {
7219 panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
7220 }
7221 }
7222 }
7223 let missing_expected_invisibles = &expected_invisibles[i + 1..];
7224 assert!(
7225 missing_expected_invisibles.is_empty(),
7226 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
7227 );
7228
7229 editor_width += resize_step;
7230 }
7231 }
7232 }
7233
7234 #[gpui::test]
7235 fn test_inline_completion_popover_text(cx: &mut TestAppContext) {
7236 init_test(cx, |_| {});
7237
7238 // Test case 1: Simple insertion
7239 {
7240 let window = cx.add_window(|cx| {
7241 let buffer = MultiBuffer::build_simple("Hello, world!", cx);
7242 Editor::new(EditorMode::Full, buffer, None, true, cx)
7243 });
7244 let cx = &mut VisualTestContext::from_window(*window, cx);
7245
7246 window
7247 .update(cx, |editor, cx| {
7248 let snapshot = editor.snapshot(cx);
7249 let edit_range = snapshot.buffer_snapshot.anchor_after(Point::new(0, 6))
7250 ..snapshot.buffer_snapshot.anchor_before(Point::new(0, 6));
7251 let edits = vec![(edit_range, " beautiful".to_string())];
7252
7253 let (text, highlights) = inline_completion_popover_text(&snapshot, &edits, cx);
7254
7255 assert_eq!(text, "Hello, beautiful world!");
7256 assert_eq!(highlights.len(), 1);
7257 assert_eq!(highlights[0].0, 6..16);
7258 assert_eq!(
7259 highlights[0].1.background_color,
7260 Some(cx.theme().status().created_background)
7261 );
7262 })
7263 .unwrap();
7264 }
7265
7266 // Test case 2: Replacement
7267 {
7268 let window = cx.add_window(|cx| {
7269 let buffer = MultiBuffer::build_simple("This is a test.", cx);
7270 Editor::new(EditorMode::Full, buffer, None, true, cx)
7271 });
7272 let cx = &mut VisualTestContext::from_window(*window, cx);
7273
7274 window
7275 .update(cx, |editor, cx| {
7276 let snapshot = editor.snapshot(cx);
7277 let edits = vec![(
7278 snapshot.buffer_snapshot.anchor_after(Point::new(0, 0))
7279 ..snapshot.buffer_snapshot.anchor_before(Point::new(0, 4)),
7280 "That".to_string(),
7281 )];
7282
7283 let (text, highlights) = inline_completion_popover_text(&snapshot, &edits, cx);
7284
7285 assert_eq!(text, "That is a test.");
7286 assert_eq!(highlights.len(), 1);
7287 assert_eq!(highlights[0].0, 0..4);
7288 assert_eq!(
7289 highlights[0].1.background_color,
7290 Some(cx.theme().status().created_background)
7291 );
7292 })
7293 .unwrap();
7294 }
7295
7296 // Test case 3: Multiple edits
7297 {
7298 let window = cx.add_window(|cx| {
7299 let buffer = MultiBuffer::build_simple("Hello, world!", cx);
7300 Editor::new(EditorMode::Full, buffer, None, true, cx)
7301 });
7302 let cx = &mut VisualTestContext::from_window(*window, cx);
7303
7304 window
7305 .update(cx, |editor, cx| {
7306 let snapshot = editor.snapshot(cx);
7307 let edits = vec![
7308 (
7309 snapshot.buffer_snapshot.anchor_after(Point::new(0, 0))
7310 ..snapshot.buffer_snapshot.anchor_before(Point::new(0, 5)),
7311 "Greetings".into(),
7312 ),
7313 (
7314 snapshot.buffer_snapshot.anchor_after(Point::new(0, 12))
7315 ..snapshot.buffer_snapshot.anchor_before(Point::new(0, 12)),
7316 " and universe".into(),
7317 ),
7318 ];
7319
7320 let (text, highlights) = inline_completion_popover_text(&snapshot, &edits, cx);
7321
7322 assert_eq!(text, "Greetings, world and universe!");
7323 assert_eq!(highlights.len(), 2);
7324 assert_eq!(highlights[0].0, 0..9);
7325 assert_eq!(highlights[1].0, 16..29);
7326 assert_eq!(
7327 highlights[0].1.background_color,
7328 Some(cx.theme().status().created_background)
7329 );
7330 assert_eq!(
7331 highlights[1].1.background_color,
7332 Some(cx.theme().status().created_background)
7333 );
7334 })
7335 .unwrap();
7336 }
7337
7338 // Test case 4: Multiple lines with edits
7339 {
7340 let window = cx.add_window(|cx| {
7341 let buffer = MultiBuffer::build_simple(
7342 "First line\nSecond line\nThird line\nFourth line",
7343 cx,
7344 );
7345 Editor::new(EditorMode::Full, buffer, None, true, cx)
7346 });
7347 let cx = &mut VisualTestContext::from_window(*window, cx);
7348
7349 window
7350 .update(cx, |editor, cx| {
7351 let snapshot = editor.snapshot(cx);
7352 let edits = vec![
7353 (
7354 snapshot.buffer_snapshot.anchor_before(Point::new(1, 7))
7355 ..snapshot.buffer_snapshot.anchor_before(Point::new(1, 11)),
7356 "modified".to_string(),
7357 ),
7358 (
7359 snapshot.buffer_snapshot.anchor_before(Point::new(2, 0))
7360 ..snapshot.buffer_snapshot.anchor_before(Point::new(2, 10)),
7361 "New third line".to_string(),
7362 ),
7363 (
7364 snapshot.buffer_snapshot.anchor_before(Point::new(3, 6))
7365 ..snapshot.buffer_snapshot.anchor_before(Point::new(3, 6)),
7366 " updated".to_string(),
7367 ),
7368 ];
7369
7370 let (text, highlights) = inline_completion_popover_text(&snapshot, &edits, cx);
7371
7372 assert_eq!(text, "Second modified\nNew third line\nFourth updated line");
7373 assert_eq!(highlights.len(), 3);
7374 assert_eq!(highlights[0].0, 7..15); // "modified"
7375 assert_eq!(highlights[1].0, 16..30); // "New third line"
7376 assert_eq!(highlights[2].0, 37..45); // " updated"
7377
7378 for highlight in &highlights {
7379 assert_eq!(
7380 highlight.1.background_color,
7381 Some(cx.theme().status().created_background)
7382 );
7383 }
7384 })
7385 .unwrap();
7386 }
7387 }
7388
7389 fn collect_invisibles_from_new_editor(
7390 cx: &mut TestAppContext,
7391 editor_mode: EditorMode,
7392 input_text: &str,
7393 editor_width: Pixels,
7394 show_line_numbers: bool,
7395 ) -> Vec<Invisible> {
7396 info!(
7397 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
7398 editor_width.0
7399 );
7400 let window = cx.add_window(|cx| {
7401 let buffer = MultiBuffer::build_simple(input_text, cx);
7402 Editor::new(editor_mode, buffer, None, true, cx)
7403 });
7404 let cx = &mut VisualTestContext::from_window(*window, cx);
7405 let editor = window.root(cx).unwrap();
7406
7407 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
7408 window
7409 .update(cx, |editor, cx| {
7410 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
7411 editor.set_wrap_width(Some(editor_width), cx);
7412 editor.set_show_line_numbers(show_line_numbers, cx);
7413 })
7414 .unwrap();
7415 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
7416 EditorElement::new(&editor, style)
7417 });
7418 state
7419 .position_map
7420 .line_layouts
7421 .iter()
7422 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
7423 .cloned()
7424 .collect()
7425 }
7426}