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