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