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