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