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