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