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