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