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