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