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