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