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