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