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