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