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