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 tab_kbd = h_flex()
2759 .px_0p5()
2760 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
2761 .text_size(TextSize::XSmall.rems(cx))
2762 .text_color(cx.theme().colors().text.opacity(0.8))
2763 .child("tab");
2764
2765 let icon_container = div().mt(px(2.5)); // For optical alignment
2766
2767 let container_element = h_flex()
2768 .items_center()
2769 .py_0p5()
2770 .px_1()
2771 .gap_1()
2772 .bg(cx.theme().colors().editor_subheader_background)
2773 .border_1()
2774 .border_color(cx.theme().colors().text_accent.opacity(0.2))
2775 .rounded_md()
2776 .shadow_sm();
2777
2778 let target_display_point = target_position.to_display_point(editor_snapshot);
2779 if target_display_point.row().as_f32() < scroll_top {
2780 let mut element = container_element
2781 .child(tab_kbd)
2782 .child(Label::new("Jump to Edit").size(LabelSize::Small))
2783 .child(
2784 icon_container
2785 .child(Icon::new(IconName::ArrowUp).size(IconSize::Small)),
2786 )
2787 .into_any();
2788 let size = element.layout_as_root(AvailableSpace::min_size(), cx);
2789 let offset = point((text_bounds.size.width - size.width) / 2., PADDING_Y);
2790 element.prepaint_at(text_bounds.origin + offset, cx);
2791 Some(element)
2792 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
2793 let mut element = container_element
2794 .child(tab_kbd)
2795 .child(Label::new("Jump to Edit").size(LabelSize::Small))
2796 .child(
2797 icon_container
2798 .child(Icon::new(IconName::ArrowDown).size(IconSize::Small)),
2799 )
2800 .into_any();
2801 let size = element.layout_as_root(AvailableSpace::min_size(), cx);
2802 let offset = point(
2803 (text_bounds.size.width - size.width) / 2.,
2804 text_bounds.size.height - size.height - PADDING_Y,
2805 );
2806 element.prepaint_at(text_bounds.origin + offset, cx);
2807 Some(element)
2808 } else {
2809 let mut element = container_element
2810 .child(tab_kbd)
2811 .child(Label::new("Jump to Edit").size(LabelSize::Small))
2812 .into_any();
2813
2814 let target_line_end = DisplayPoint::new(
2815 target_display_point.row(),
2816 editor_snapshot.line_len(target_display_point.row()),
2817 );
2818 let origin = self.editor.update(cx, |editor, cx| {
2819 editor.display_to_pixel_point(target_line_end, editor_snapshot, cx)
2820 })?;
2821 element.prepaint_as_root(
2822 text_bounds.origin + origin + point(PADDING_X, px(0.)),
2823 AvailableSpace::min_size(),
2824 cx,
2825 );
2826 Some(element)
2827 }
2828 }
2829 InlineCompletion::Edit(edits) => {
2830 let edit_start = edits
2831 .first()
2832 .unwrap()
2833 .0
2834 .start
2835 .to_display_point(editor_snapshot);
2836 let edit_end = edits
2837 .last()
2838 .unwrap()
2839 .0
2840 .end
2841 .to_display_point(editor_snapshot);
2842
2843 let is_visible = visible_row_range.contains(&edit_start.row())
2844 || visible_row_range.contains(&edit_end.row());
2845 if !is_visible {
2846 return None;
2847 }
2848
2849 if all_edits_insertions_or_deletions(edits, &editor_snapshot.buffer_snapshot) {
2850 return None;
2851 }
2852
2853 let (text, highlights) = inline_completion_popover_text(editor_snapshot, edits, cx);
2854
2855 let longest_row =
2856 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
2857 let longest_line_width = if visible_row_range.contains(&longest_row) {
2858 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
2859 } else {
2860 layout_line(
2861 longest_row,
2862 editor_snapshot,
2863 style,
2864 editor_width,
2865 |_| false,
2866 cx,
2867 )
2868 .width
2869 };
2870
2871 let text = gpui::StyledText::new(text).with_highlights(&style.text, highlights);
2872
2873 let mut element = div()
2874 .bg(cx.theme().colors().editor_background)
2875 .border_1()
2876 .border_color(cx.theme().colors().border)
2877 .rounded_md()
2878 .px_1()
2879 .child(text)
2880 .into_any();
2881
2882 let origin = text_bounds.origin
2883 + point(
2884 longest_line_width + PADDING_X - scroll_pixel_position.x,
2885 edit_start.row().as_f32() * line_height - scroll_pixel_position.y,
2886 );
2887 element.prepaint_as_root(origin, AvailableSpace::min_size(), cx);
2888 Some(element)
2889 }
2890 }
2891 }
2892
2893 fn layout_mouse_context_menu(
2894 &self,
2895 editor_snapshot: &EditorSnapshot,
2896 visible_range: Range<DisplayRow>,
2897 content_origin: gpui::Point<Pixels>,
2898 cx: &mut WindowContext,
2899 ) -> Option<AnyElement> {
2900 let position = self.editor.update(cx, |editor, cx| {
2901 let visible_start_point = editor.display_to_pixel_point(
2902 DisplayPoint::new(visible_range.start, 0),
2903 editor_snapshot,
2904 cx,
2905 )?;
2906 let visible_end_point = editor.display_to_pixel_point(
2907 DisplayPoint::new(visible_range.end, 0),
2908 editor_snapshot,
2909 cx,
2910 )?;
2911
2912 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
2913 let (source_display_point, position) = match mouse_context_menu.position {
2914 MenuPosition::PinnedToScreen(point) => (None, point),
2915 MenuPosition::PinnedToEditor { source, offset } => {
2916 let source_display_point = source.to_display_point(editor_snapshot);
2917 let source_point = editor.to_pixel_point(source, editor_snapshot, cx)?;
2918 let position = content_origin + source_point + offset;
2919 (Some(source_display_point), position)
2920 }
2921 };
2922
2923 let source_included = source_display_point.map_or(true, |source_display_point| {
2924 visible_range
2925 .to_inclusive()
2926 .contains(&source_display_point.row())
2927 });
2928 let position_included =
2929 visible_start_point.y <= position.y && position.y <= visible_end_point.y;
2930 if !source_included && !position_included {
2931 None
2932 } else {
2933 Some(position)
2934 }
2935 })?;
2936
2937 let mut element = self.editor.update(cx, |editor, _| {
2938 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
2939 let context_menu = mouse_context_menu.context_menu.clone();
2940
2941 Some(
2942 deferred(
2943 anchored()
2944 .position(position)
2945 .child(context_menu)
2946 .anchor(AnchorCorner::TopLeft)
2947 .snap_to_window_with_margin(px(8.)),
2948 )
2949 .with_priority(1)
2950 .into_any(),
2951 )
2952 })?;
2953
2954 element.prepaint_as_root(position, AvailableSpace::min_size(), cx);
2955 Some(element)
2956 }
2957
2958 #[allow(clippy::too_many_arguments)]
2959 fn layout_hover_popovers(
2960 &self,
2961 snapshot: &EditorSnapshot,
2962 hitbox: &Hitbox,
2963 text_hitbox: &Hitbox,
2964 visible_display_row_range: Range<DisplayRow>,
2965 content_origin: gpui::Point<Pixels>,
2966 scroll_pixel_position: gpui::Point<Pixels>,
2967 line_layouts: &[LineWithInvisibles],
2968 line_height: Pixels,
2969 em_width: Pixels,
2970 cx: &mut WindowContext,
2971 ) {
2972 struct MeasuredHoverPopover {
2973 element: AnyElement,
2974 size: Size<Pixels>,
2975 horizontal_offset: Pixels,
2976 }
2977
2978 let max_size = size(
2979 (120. * em_width) // Default size
2980 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
2981 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2982 (16. * line_height) // Default size
2983 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
2984 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2985 );
2986
2987 let hover_popovers = self.editor.update(cx, |editor, cx| {
2988 editor
2989 .hover_state
2990 .render(snapshot, visible_display_row_range.clone(), max_size, cx)
2991 });
2992 let Some((position, hover_popovers)) = hover_popovers else {
2993 return;
2994 };
2995
2996 // This is safe because we check on layout whether the required row is available
2997 let hovered_row_layout =
2998 &line_layouts[position.row().minus(visible_display_row_range.start) as usize];
2999
3000 // Compute Hovered Point
3001 let x =
3002 hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
3003 let y = position.row().as_f32() * line_height - scroll_pixel_position.y;
3004 let hovered_point = content_origin + point(x, y);
3005
3006 let mut overall_height = Pixels::ZERO;
3007 let mut measured_hover_popovers = Vec::new();
3008 for mut hover_popover in hover_popovers {
3009 let size = hover_popover.layout_as_root(AvailableSpace::min_size(), cx);
3010 let horizontal_offset =
3011 (text_hitbox.upper_right().x - (hovered_point.x + size.width)).min(Pixels::ZERO);
3012
3013 overall_height += HOVER_POPOVER_GAP + size.height;
3014
3015 measured_hover_popovers.push(MeasuredHoverPopover {
3016 element: hover_popover,
3017 size,
3018 horizontal_offset,
3019 });
3020 }
3021 overall_height += HOVER_POPOVER_GAP;
3022
3023 fn draw_occluder(width: Pixels, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
3024 let mut occlusion = div()
3025 .size_full()
3026 .occlude()
3027 .on_mouse_move(|_, cx| cx.stop_propagation())
3028 .into_any_element();
3029 occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), cx);
3030 cx.defer_draw(occlusion, origin, 2);
3031 }
3032
3033 if hovered_point.y > overall_height {
3034 // There is enough space above. Render popovers above the hovered point
3035 let mut current_y = hovered_point.y;
3036 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
3037 let size = popover.size;
3038 let popover_origin = point(
3039 hovered_point.x + popover.horizontal_offset,
3040 current_y - size.height,
3041 );
3042
3043 cx.defer_draw(popover.element, popover_origin, 2);
3044 if position != itertools::Position::Last {
3045 let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
3046 draw_occluder(size.width, origin, cx);
3047 }
3048
3049 current_y = popover_origin.y - HOVER_POPOVER_GAP;
3050 }
3051 } else {
3052 // There is not enough space above. Render popovers below the hovered point
3053 let mut current_y = hovered_point.y + line_height;
3054 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
3055 let size = popover.size;
3056 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
3057
3058 cx.defer_draw(popover.element, popover_origin, 2);
3059 if position != itertools::Position::Last {
3060 let origin = point(popover_origin.x, popover_origin.y + size.height);
3061 draw_occluder(size.width, origin, cx);
3062 }
3063
3064 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
3065 }
3066 }
3067 }
3068
3069 #[allow(clippy::too_many_arguments)]
3070 fn layout_signature_help(
3071 &self,
3072 hitbox: &Hitbox,
3073 content_origin: gpui::Point<Pixels>,
3074 scroll_pixel_position: gpui::Point<Pixels>,
3075 newest_selection_head: Option<DisplayPoint>,
3076 start_row: DisplayRow,
3077 line_layouts: &[LineWithInvisibles],
3078 line_height: Pixels,
3079 em_width: Pixels,
3080 cx: &mut WindowContext,
3081 ) {
3082 if !self.editor.focus_handle(cx).is_focused(cx) {
3083 return;
3084 }
3085 let Some(newest_selection_head) = newest_selection_head else {
3086 return;
3087 };
3088 let selection_row = newest_selection_head.row();
3089 if selection_row < start_row {
3090 return;
3091 }
3092 let Some(cursor_row_layout) = line_layouts.get(selection_row.minus(start_row) as usize)
3093 else {
3094 return;
3095 };
3096
3097 let start_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
3098 - scroll_pixel_position.x
3099 + content_origin.x;
3100 let start_y =
3101 selection_row.as_f32() * line_height + content_origin.y - scroll_pixel_position.y;
3102
3103 let max_size = size(
3104 (120. * em_width) // Default size
3105 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
3106 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
3107 (16. * line_height) // Default size
3108 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
3109 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
3110 );
3111
3112 let maybe_element = self.editor.update(cx, |editor, cx| {
3113 if let Some(popover) = editor.signature_help_state.popover_mut() {
3114 let element = popover.render(
3115 &self.style,
3116 max_size,
3117 editor.workspace.as_ref().map(|(w, _)| w.clone()),
3118 cx,
3119 );
3120 Some(element)
3121 } else {
3122 None
3123 }
3124 });
3125 if let Some(mut element) = maybe_element {
3126 let window_size = cx.viewport_size();
3127 let size = element.layout_as_root(Size::<AvailableSpace>::default(), cx);
3128 let mut point = point(start_x, start_y - size.height);
3129
3130 // Adjusting to ensure the popover does not overflow in the X-axis direction.
3131 if point.x + size.width >= window_size.width {
3132 point.x = window_size.width - size.width;
3133 }
3134
3135 cx.defer_draw(element, point, 1)
3136 }
3137 }
3138
3139 fn paint_background(&self, layout: &EditorLayout, cx: &mut WindowContext) {
3140 cx.paint_layer(layout.hitbox.bounds, |cx| {
3141 let scroll_top = layout.position_map.snapshot.scroll_position().y;
3142 let gutter_bg = cx.theme().colors().editor_gutter_background;
3143 cx.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
3144 cx.paint_quad(fill(layout.text_hitbox.bounds, self.style.background));
3145
3146 if let EditorMode::Full = layout.mode {
3147 let mut active_rows = layout.active_rows.iter().peekable();
3148 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
3149 let mut end_row = start_row.0;
3150 while active_rows
3151 .peek()
3152 .map_or(false, |(active_row, has_selection)| {
3153 active_row.0 == end_row + 1
3154 && *has_selection == contains_non_empty_selection
3155 })
3156 {
3157 active_rows.next().unwrap();
3158 end_row += 1;
3159 }
3160
3161 if !contains_non_empty_selection {
3162 let highlight_h_range =
3163 match layout.position_map.snapshot.current_line_highlight {
3164 CurrentLineHighlight::Gutter => Some(Range {
3165 start: layout.hitbox.left(),
3166 end: layout.gutter_hitbox.right(),
3167 }),
3168 CurrentLineHighlight::Line => Some(Range {
3169 start: layout.text_hitbox.bounds.left(),
3170 end: layout.text_hitbox.bounds.right(),
3171 }),
3172 CurrentLineHighlight::All => Some(Range {
3173 start: layout.hitbox.left(),
3174 end: layout.hitbox.right(),
3175 }),
3176 CurrentLineHighlight::None => None,
3177 };
3178 if let Some(range) = highlight_h_range {
3179 let active_line_bg = cx.theme().colors().editor_active_line_background;
3180 let bounds = Bounds {
3181 origin: point(
3182 range.start,
3183 layout.hitbox.origin.y
3184 + (start_row.as_f32() - scroll_top)
3185 * layout.position_map.line_height,
3186 ),
3187 size: size(
3188 range.end - range.start,
3189 layout.position_map.line_height
3190 * (end_row - start_row.0 + 1) as f32,
3191 ),
3192 };
3193 cx.paint_quad(fill(bounds, active_line_bg));
3194 }
3195 }
3196 }
3197
3198 let mut paint_highlight =
3199 |highlight_row_start: DisplayRow, highlight_row_end: DisplayRow, color| {
3200 let origin = point(
3201 layout.hitbox.origin.x,
3202 layout.hitbox.origin.y
3203 + (highlight_row_start.as_f32() - scroll_top)
3204 * layout.position_map.line_height,
3205 );
3206 let size = size(
3207 layout.hitbox.size.width,
3208 layout.position_map.line_height
3209 * highlight_row_end.next_row().minus(highlight_row_start) as f32,
3210 );
3211 cx.paint_quad(fill(Bounds { origin, size }, color));
3212 };
3213
3214 let mut current_paint: Option<(Hsla, Range<DisplayRow>)> = None;
3215 for (&new_row, &new_color) in &layout.highlighted_rows {
3216 match &mut current_paint {
3217 Some((current_color, current_range)) => {
3218 let current_color = *current_color;
3219 let new_range_started = current_color != new_color
3220 || current_range.end.next_row() != new_row;
3221 if new_range_started {
3222 paint_highlight(
3223 current_range.start,
3224 current_range.end,
3225 current_color,
3226 );
3227 current_paint = Some((new_color, new_row..new_row));
3228 continue;
3229 } else {
3230 current_range.end = current_range.end.next_row();
3231 }
3232 }
3233 None => current_paint = Some((new_color, new_row..new_row)),
3234 };
3235 }
3236 if let Some((color, range)) = current_paint {
3237 paint_highlight(range.start, range.end, color);
3238 }
3239
3240 let scroll_left =
3241 layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
3242
3243 for (wrap_position, active) in layout.wrap_guides.iter() {
3244 let x = (layout.text_hitbox.origin.x
3245 + *wrap_position
3246 + layout.position_map.em_width / 2.)
3247 - scroll_left;
3248
3249 let show_scrollbars = layout
3250 .scrollbar_layout
3251 .as_ref()
3252 .map_or(false, |scrollbar| scrollbar.visible);
3253 if x < layout.text_hitbox.origin.x
3254 || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
3255 {
3256 continue;
3257 }
3258
3259 let color = if *active {
3260 cx.theme().colors().editor_active_wrap_guide
3261 } else {
3262 cx.theme().colors().editor_wrap_guide
3263 };
3264 cx.paint_quad(fill(
3265 Bounds {
3266 origin: point(x, layout.text_hitbox.origin.y),
3267 size: size(px(1.), layout.text_hitbox.size.height),
3268 },
3269 color,
3270 ));
3271 }
3272 }
3273 })
3274 }
3275
3276 fn paint_indent_guides(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3277 let Some(indent_guides) = &layout.indent_guides else {
3278 return;
3279 };
3280
3281 let faded_color = |color: Hsla, alpha: f32| {
3282 let mut faded = color;
3283 faded.a = alpha;
3284 faded
3285 };
3286
3287 for indent_guide in indent_guides {
3288 let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
3289 let settings = indent_guide.settings;
3290
3291 // TODO fixed for now, expose them through themes later
3292 const INDENT_AWARE_ALPHA: f32 = 0.2;
3293 const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
3294 const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
3295 const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
3296
3297 let line_color = match (settings.coloring, indent_guide.active) {
3298 (IndentGuideColoring::Disabled, _) => None,
3299 (IndentGuideColoring::Fixed, false) => {
3300 Some(cx.theme().colors().editor_indent_guide)
3301 }
3302 (IndentGuideColoring::Fixed, true) => {
3303 Some(cx.theme().colors().editor_indent_guide_active)
3304 }
3305 (IndentGuideColoring::IndentAware, false) => {
3306 Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
3307 }
3308 (IndentGuideColoring::IndentAware, true) => {
3309 Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
3310 }
3311 };
3312
3313 let background_color = match (settings.background_coloring, indent_guide.active) {
3314 (IndentGuideBackgroundColoring::Disabled, _) => None,
3315 (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
3316 indent_accent_colors,
3317 INDENT_AWARE_BACKGROUND_ALPHA,
3318 )),
3319 (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
3320 indent_accent_colors,
3321 INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
3322 )),
3323 };
3324
3325 let requested_line_width = if indent_guide.active {
3326 settings.active_line_width
3327 } else {
3328 settings.line_width
3329 }
3330 .clamp(1, 10);
3331 let mut line_indicator_width = 0.;
3332 if let Some(color) = line_color {
3333 cx.paint_quad(fill(
3334 Bounds {
3335 origin: indent_guide.origin,
3336 size: size(px(requested_line_width as f32), indent_guide.length),
3337 },
3338 color,
3339 ));
3340 line_indicator_width = requested_line_width as f32;
3341 }
3342
3343 if let Some(color) = background_color {
3344 let width = indent_guide.single_indent_width - px(line_indicator_width);
3345 cx.paint_quad(fill(
3346 Bounds {
3347 origin: point(
3348 indent_guide.origin.x + px(line_indicator_width),
3349 indent_guide.origin.y,
3350 ),
3351 size: size(width, indent_guide.length),
3352 },
3353 color,
3354 ));
3355 }
3356 }
3357 }
3358
3359 fn paint_line_numbers(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3360 let line_height = layout.position_map.line_height;
3361 let scroll_position = layout.position_map.snapshot.scroll_position();
3362 let scroll_top = scroll_position.y * line_height;
3363
3364 cx.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
3365
3366 for (ix, line) in layout.line_numbers.iter().enumerate() {
3367 if let Some(line) = line {
3368 let line_origin = layout.gutter_hitbox.origin
3369 + point(
3370 layout.gutter_hitbox.size.width
3371 - line.width
3372 - layout.gutter_dimensions.right_padding,
3373 ix as f32 * line_height - (scroll_top % line_height),
3374 );
3375
3376 line.paint(line_origin, line_height, cx).log_err();
3377 }
3378 }
3379 }
3380
3381 fn paint_diff_hunks(layout: &mut EditorLayout, cx: &mut WindowContext) {
3382 if layout.display_hunks.is_empty() {
3383 return;
3384 }
3385
3386 let line_height = layout.position_map.line_height;
3387 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3388 for (hunk, hitbox) in &layout.display_hunks {
3389 let hunk_to_paint = match hunk {
3390 DisplayDiffHunk::Folded { .. } => {
3391 let hunk_bounds = Self::diff_hunk_bounds(
3392 &layout.position_map.snapshot,
3393 line_height,
3394 layout.gutter_hitbox.bounds,
3395 hunk,
3396 );
3397 Some((
3398 hunk_bounds,
3399 cx.theme().status().modified,
3400 Corners::all(px(0.)),
3401 ))
3402 }
3403 DisplayDiffHunk::Unfolded { status, .. } => {
3404 hitbox.as_ref().map(|hunk_hitbox| match status {
3405 DiffHunkStatus::Added => (
3406 hunk_hitbox.bounds,
3407 cx.theme().status().created,
3408 Corners::all(px(0.)),
3409 ),
3410 DiffHunkStatus::Modified => (
3411 hunk_hitbox.bounds,
3412 cx.theme().status().modified,
3413 Corners::all(px(0.)),
3414 ),
3415 DiffHunkStatus::Removed => (
3416 Bounds::new(
3417 point(
3418 hunk_hitbox.origin.x - hunk_hitbox.size.width,
3419 hunk_hitbox.origin.y,
3420 ),
3421 size(hunk_hitbox.size.width * px(2.), hunk_hitbox.size.height),
3422 ),
3423 cx.theme().status().deleted,
3424 Corners::all(1. * line_height),
3425 ),
3426 })
3427 }
3428 };
3429
3430 if let Some((hunk_bounds, background_color, corner_radii)) = hunk_to_paint {
3431 cx.paint_quad(quad(
3432 hunk_bounds,
3433 corner_radii,
3434 background_color,
3435 Edges::default(),
3436 transparent_black(),
3437 ));
3438 }
3439 }
3440 });
3441 }
3442
3443 pub(super) fn diff_hunk_bounds(
3444 snapshot: &EditorSnapshot,
3445 line_height: Pixels,
3446 gutter_bounds: Bounds<Pixels>,
3447 hunk: &DisplayDiffHunk,
3448 ) -> Bounds<Pixels> {
3449 let scroll_position = snapshot.scroll_position();
3450 let scroll_top = scroll_position.y * line_height;
3451
3452 match hunk {
3453 DisplayDiffHunk::Folded { display_row, .. } => {
3454 let start_y = display_row.as_f32() * line_height - scroll_top;
3455 let end_y = start_y + line_height;
3456
3457 let width = Self::diff_hunk_strip_width(line_height);
3458 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
3459 let highlight_size = size(width, end_y - start_y);
3460 Bounds::new(highlight_origin, highlight_size)
3461 }
3462 DisplayDiffHunk::Unfolded {
3463 display_row_range,
3464 status,
3465 ..
3466 } => match status {
3467 DiffHunkStatus::Added | DiffHunkStatus::Modified => {
3468 let start_row = display_row_range.start;
3469 let end_row = display_row_range.end;
3470 // If we're in a multibuffer, row range span might include an
3471 // excerpt header, so if we were to draw the marker straight away,
3472 // the hunk might include the rows of that header.
3473 // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
3474 // Instead, we simply check whether the range we're dealing with includes
3475 // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
3476 let end_row_in_current_excerpt = snapshot
3477 .blocks_in_range(start_row..end_row)
3478 .find_map(|(start_row, block)| {
3479 if matches!(block, Block::ExcerptBoundary { .. }) {
3480 Some(start_row)
3481 } else {
3482 None
3483 }
3484 })
3485 .unwrap_or(end_row);
3486
3487 let start_y = start_row.as_f32() * line_height - scroll_top;
3488 let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
3489
3490 let width = Self::diff_hunk_strip_width(line_height);
3491 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
3492 let highlight_size = size(width, end_y - start_y);
3493 Bounds::new(highlight_origin, highlight_size)
3494 }
3495 DiffHunkStatus::Removed => {
3496 let row = display_row_range.start;
3497
3498 let offset = line_height / 2.;
3499 let start_y = row.as_f32() * line_height - offset - scroll_top;
3500 let end_y = start_y + line_height;
3501
3502 let width = (0.35 * line_height).floor();
3503 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
3504 let highlight_size = size(width, end_y - start_y);
3505 Bounds::new(highlight_origin, highlight_size)
3506 }
3507 },
3508 }
3509 }
3510
3511 /// Returns the width of the diff strip that will be displayed in the gutter.
3512 pub(super) fn diff_hunk_strip_width(line_height: Pixels) -> Pixels {
3513 // We floor the value to prevent pixel rounding.
3514 (0.275 * line_height).floor()
3515 }
3516
3517 fn paint_gutter_indicators(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3518 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3519 cx.with_element_namespace("crease_toggles", |cx| {
3520 for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
3521 crease_toggle.paint(cx);
3522 }
3523 });
3524
3525 for test_indicator in layout.test_indicators.iter_mut() {
3526 test_indicator.paint(cx);
3527 }
3528
3529 if let Some(indicator) = layout.code_actions_indicator.as_mut() {
3530 indicator.paint(cx);
3531 }
3532 });
3533 }
3534
3535 fn paint_gutter_highlights(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3536 for (_, hunk_hitbox) in &layout.display_hunks {
3537 if let Some(hunk_hitbox) = hunk_hitbox {
3538 cx.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
3539 }
3540 }
3541
3542 let show_git_gutter = layout
3543 .position_map
3544 .snapshot
3545 .show_git_diff_gutter
3546 .unwrap_or_else(|| {
3547 matches!(
3548 ProjectSettings::get_global(cx).git.git_gutter,
3549 Some(GitGutterSetting::TrackedFiles)
3550 )
3551 });
3552 if show_git_gutter {
3553 Self::paint_diff_hunks(layout, cx)
3554 }
3555
3556 let highlight_width = 0.275 * layout.position_map.line_height;
3557 let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
3558 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3559 for (range, color) in &layout.highlighted_gutter_ranges {
3560 let start_row = if range.start.row() < layout.visible_display_row_range.start {
3561 layout.visible_display_row_range.start - DisplayRow(1)
3562 } else {
3563 range.start.row()
3564 };
3565 let end_row = if range.end.row() > layout.visible_display_row_range.end {
3566 layout.visible_display_row_range.end + DisplayRow(1)
3567 } else {
3568 range.end.row()
3569 };
3570
3571 let start_y = layout.gutter_hitbox.top()
3572 + start_row.0 as f32 * layout.position_map.line_height
3573 - layout.position_map.scroll_pixel_position.y;
3574 let end_y = layout.gutter_hitbox.top()
3575 + (end_row.0 + 1) as f32 * layout.position_map.line_height
3576 - layout.position_map.scroll_pixel_position.y;
3577 let bounds = Bounds::from_corners(
3578 point(layout.gutter_hitbox.left(), start_y),
3579 point(layout.gutter_hitbox.left() + highlight_width, end_y),
3580 );
3581 cx.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
3582 }
3583 });
3584 }
3585
3586 fn paint_blamed_display_rows(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3587 let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
3588 return;
3589 };
3590
3591 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3592 for mut blame_element in blamed_display_rows.into_iter() {
3593 blame_element.paint(cx);
3594 }
3595 })
3596 }
3597
3598 fn paint_text(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3599 cx.with_content_mask(
3600 Some(ContentMask {
3601 bounds: layout.text_hitbox.bounds,
3602 }),
3603 |cx| {
3604 let cursor_style = if self
3605 .editor
3606 .read(cx)
3607 .hovered_link_state
3608 .as_ref()
3609 .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
3610 {
3611 CursorStyle::PointingHand
3612 } else {
3613 CursorStyle::IBeam
3614 };
3615 cx.set_cursor_style(cursor_style, &layout.text_hitbox);
3616
3617 let invisible_display_ranges = self.paint_highlights(layout, cx);
3618 self.paint_lines(&invisible_display_ranges, layout, cx);
3619 self.paint_redactions(layout, cx);
3620 self.paint_cursors(layout, cx);
3621 self.paint_inline_blame(layout, cx);
3622 cx.with_element_namespace("crease_trailers", |cx| {
3623 for trailer in layout.crease_trailers.iter_mut().flatten() {
3624 trailer.element.paint(cx);
3625 }
3626 });
3627 },
3628 )
3629 }
3630
3631 fn paint_highlights(
3632 &mut self,
3633 layout: &mut EditorLayout,
3634 cx: &mut WindowContext,
3635 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
3636 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3637 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
3638 let line_end_overshoot = 0.15 * layout.position_map.line_height;
3639 for (range, color) in &layout.highlighted_ranges {
3640 self.paint_highlighted_range(
3641 range.clone(),
3642 *color,
3643 Pixels::ZERO,
3644 line_end_overshoot,
3645 layout,
3646 cx,
3647 );
3648 }
3649
3650 let corner_radius = 0.15 * layout.position_map.line_height;
3651
3652 for (player_color, selections) in &layout.selections {
3653 for selection in selections.iter() {
3654 self.paint_highlighted_range(
3655 selection.range.clone(),
3656 player_color.selection,
3657 corner_radius,
3658 corner_radius * 2.,
3659 layout,
3660 cx,
3661 );
3662
3663 if selection.is_local && !selection.range.is_empty() {
3664 invisible_display_ranges.push(selection.range.clone());
3665 }
3666 }
3667 }
3668 invisible_display_ranges
3669 })
3670 }
3671
3672 fn paint_lines(
3673 &mut self,
3674 invisible_display_ranges: &[Range<DisplayPoint>],
3675 layout: &mut EditorLayout,
3676 cx: &mut WindowContext,
3677 ) {
3678 let whitespace_setting = self
3679 .editor
3680 .read(cx)
3681 .buffer
3682 .read(cx)
3683 .settings_at(0, cx)
3684 .show_whitespaces;
3685
3686 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
3687 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
3688 line_with_invisibles.draw(
3689 layout,
3690 row,
3691 layout.content_origin,
3692 whitespace_setting,
3693 invisible_display_ranges,
3694 cx,
3695 )
3696 }
3697
3698 for line_element in &mut layout.line_elements {
3699 line_element.paint(cx);
3700 }
3701 }
3702
3703 fn paint_redactions(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
3704 if layout.redacted_ranges.is_empty() {
3705 return;
3706 }
3707
3708 let line_end_overshoot = layout.line_end_overshoot();
3709
3710 // A softer than perfect black
3711 let redaction_color = gpui::rgb(0x0e1111);
3712
3713 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3714 for range in layout.redacted_ranges.iter() {
3715 self.paint_highlighted_range(
3716 range.clone(),
3717 redaction_color.into(),
3718 Pixels::ZERO,
3719 line_end_overshoot,
3720 layout,
3721 cx,
3722 );
3723 }
3724 });
3725 }
3726
3727 fn paint_cursors(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3728 for cursor in &mut layout.visible_cursors {
3729 cursor.paint(layout.content_origin, cx);
3730 }
3731 }
3732
3733 fn paint_scrollbar(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3734 let Some(scrollbar_layout) = layout.scrollbar_layout.as_ref() else {
3735 return;
3736 };
3737
3738 let thumb_bounds = scrollbar_layout.thumb_bounds();
3739 if scrollbar_layout.visible {
3740 cx.paint_layer(scrollbar_layout.hitbox.bounds, |cx| {
3741 cx.paint_quad(quad(
3742 scrollbar_layout.hitbox.bounds,
3743 Corners::default(),
3744 cx.theme().colors().scrollbar_track_background,
3745 Edges {
3746 top: Pixels::ZERO,
3747 right: Pixels::ZERO,
3748 bottom: Pixels::ZERO,
3749 left: ScrollbarLayout::BORDER_WIDTH,
3750 },
3751 cx.theme().colors().scrollbar_track_border,
3752 ));
3753
3754 let fast_markers =
3755 self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
3756 // Refresh slow scrollbar markers in the background. Below, we paint whatever markers have already been computed.
3757 self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, cx);
3758
3759 let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
3760 for marker in markers.iter().chain(&fast_markers) {
3761 let mut marker = marker.clone();
3762 marker.bounds.origin += scrollbar_layout.hitbox.origin;
3763 cx.paint_quad(marker);
3764 }
3765
3766 cx.paint_quad(quad(
3767 thumb_bounds,
3768 Corners::default(),
3769 cx.theme().colors().scrollbar_thumb_background,
3770 Edges {
3771 top: Pixels::ZERO,
3772 right: Pixels::ZERO,
3773 bottom: Pixels::ZERO,
3774 left: ScrollbarLayout::BORDER_WIDTH,
3775 },
3776 cx.theme().colors().scrollbar_thumb_border,
3777 ));
3778 });
3779 }
3780
3781 cx.set_cursor_style(CursorStyle::Arrow, &scrollbar_layout.hitbox);
3782
3783 let row_height = scrollbar_layout.row_height;
3784 let row_range = scrollbar_layout.visible_row_range.clone();
3785
3786 cx.on_mouse_event({
3787 let editor = self.editor.clone();
3788 let hitbox = scrollbar_layout.hitbox.clone();
3789 let mut mouse_position = cx.mouse_position();
3790 move |event: &MouseMoveEvent, phase, cx| {
3791 if phase == DispatchPhase::Capture {
3792 return;
3793 }
3794
3795 editor.update(cx, |editor, cx| {
3796 if event.pressed_button == Some(MouseButton::Left)
3797 && editor.scroll_manager.is_dragging_scrollbar()
3798 {
3799 let y = mouse_position.y;
3800 let new_y = event.position.y;
3801 if (hitbox.top()..hitbox.bottom()).contains(&y) {
3802 let mut position = editor.scroll_position(cx);
3803 position.y += (new_y - y) / row_height;
3804 if position.y < 0.0 {
3805 position.y = 0.0;
3806 }
3807 editor.set_scroll_position(position, cx);
3808 }
3809
3810 cx.stop_propagation();
3811 } else {
3812 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
3813 if hitbox.is_hovered(cx) {
3814 editor.scroll_manager.show_scrollbar(cx);
3815 }
3816 }
3817 mouse_position = event.position;
3818 })
3819 }
3820 });
3821
3822 if self.editor.read(cx).scroll_manager.is_dragging_scrollbar() {
3823 cx.on_mouse_event({
3824 let editor = self.editor.clone();
3825 move |_: &MouseUpEvent, phase, cx| {
3826 if phase == DispatchPhase::Capture {
3827 return;
3828 }
3829
3830 editor.update(cx, |editor, cx| {
3831 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
3832 cx.stop_propagation();
3833 });
3834 }
3835 });
3836 } else {
3837 cx.on_mouse_event({
3838 let editor = self.editor.clone();
3839 let hitbox = scrollbar_layout.hitbox.clone();
3840 move |event: &MouseDownEvent, phase, cx| {
3841 if phase == DispatchPhase::Capture || !hitbox.is_hovered(cx) {
3842 return;
3843 }
3844
3845 editor.update(cx, |editor, cx| {
3846 editor.scroll_manager.set_is_dragging_scrollbar(true, cx);
3847
3848 let y = event.position.y;
3849 if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
3850 let center_row = ((y - hitbox.top()) / row_height).round() as u32;
3851 let top_row = center_row
3852 .saturating_sub((row_range.end - row_range.start) as u32 / 2);
3853 let mut position = editor.scroll_position(cx);
3854 position.y = top_row as f32;
3855 editor.set_scroll_position(position, cx);
3856 } else {
3857 editor.scroll_manager.show_scrollbar(cx);
3858 }
3859
3860 cx.stop_propagation();
3861 });
3862 }
3863 });
3864 }
3865 }
3866
3867 fn collect_fast_scrollbar_markers(
3868 &self,
3869 layout: &EditorLayout,
3870 scrollbar_layout: &ScrollbarLayout,
3871 cx: &mut WindowContext,
3872 ) -> Vec<PaintQuad> {
3873 const LIMIT: usize = 100;
3874 if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
3875 return vec![];
3876 }
3877 let cursor_ranges = layout
3878 .cursors
3879 .iter()
3880 .map(|(point, color)| ColoredRange {
3881 start: point.row(),
3882 end: point.row(),
3883 color: *color,
3884 })
3885 .collect_vec();
3886 scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
3887 }
3888
3889 fn refresh_slow_scrollbar_markers(
3890 &self,
3891 layout: &EditorLayout,
3892 scrollbar_layout: &ScrollbarLayout,
3893 cx: &mut WindowContext,
3894 ) {
3895 self.editor.update(cx, |editor, cx| {
3896 if !editor.is_singleton(cx)
3897 || !editor
3898 .scrollbar_marker_state
3899 .should_refresh(scrollbar_layout.hitbox.size)
3900 {
3901 return;
3902 }
3903
3904 let scrollbar_layout = scrollbar_layout.clone();
3905 let background_highlights = editor.background_highlights.clone();
3906 let snapshot = layout.position_map.snapshot.clone();
3907 let theme = cx.theme().clone();
3908 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
3909
3910 editor.scrollbar_marker_state.dirty = false;
3911 editor.scrollbar_marker_state.pending_refresh =
3912 Some(cx.spawn(|editor, mut cx| async move {
3913 let scrollbar_size = scrollbar_layout.hitbox.size;
3914 let scrollbar_markers = cx
3915 .background_executor()
3916 .spawn(async move {
3917 let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
3918 let mut marker_quads = Vec::new();
3919 if scrollbar_settings.git_diff {
3920 let marker_row_ranges = snapshot
3921 .diff_map
3922 .diff_hunks(&snapshot.buffer_snapshot)
3923 .map(|hunk| {
3924 let start_display_row =
3925 MultiBufferPoint::new(hunk.row_range.start.0, 0)
3926 .to_display_point(&snapshot.display_snapshot)
3927 .row();
3928 let mut end_display_row =
3929 MultiBufferPoint::new(hunk.row_range.end.0, 0)
3930 .to_display_point(&snapshot.display_snapshot)
3931 .row();
3932 if end_display_row != start_display_row {
3933 end_display_row.0 -= 1;
3934 }
3935 let color = match hunk_status(&hunk) {
3936 DiffHunkStatus::Added => theme.status().created,
3937 DiffHunkStatus::Modified => theme.status().modified,
3938 DiffHunkStatus::Removed => theme.status().deleted,
3939 };
3940 ColoredRange {
3941 start: start_display_row,
3942 end: end_display_row,
3943 color,
3944 }
3945 });
3946
3947 marker_quads.extend(
3948 scrollbar_layout
3949 .marker_quads_for_ranges(marker_row_ranges, Some(0)),
3950 );
3951 }
3952
3953 for (background_highlight_id, (_, background_ranges)) in
3954 background_highlights.iter()
3955 {
3956 let is_search_highlights = *background_highlight_id
3957 == TypeId::of::<BufferSearchHighlights>();
3958 let is_symbol_occurrences = *background_highlight_id
3959 == TypeId::of::<DocumentHighlightRead>()
3960 || *background_highlight_id
3961 == TypeId::of::<DocumentHighlightWrite>();
3962 if (is_search_highlights && scrollbar_settings.search_results)
3963 || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
3964 {
3965 let mut color = theme.status().info;
3966 if is_symbol_occurrences {
3967 color.fade_out(0.5);
3968 }
3969 let marker_row_ranges = background_ranges.iter().map(|range| {
3970 let display_start = range
3971 .start
3972 .to_display_point(&snapshot.display_snapshot);
3973 let display_end =
3974 range.end.to_display_point(&snapshot.display_snapshot);
3975 ColoredRange {
3976 start: display_start.row(),
3977 end: display_end.row(),
3978 color,
3979 }
3980 });
3981 marker_quads.extend(
3982 scrollbar_layout
3983 .marker_quads_for_ranges(marker_row_ranges, Some(1)),
3984 );
3985 }
3986 }
3987
3988 if scrollbar_settings.diagnostics {
3989 let diagnostics = snapshot
3990 .buffer_snapshot
3991 .diagnostics_in_range::<_, Point>(
3992 Point::zero()..max_point,
3993 false,
3994 )
3995 // We want to sort by severity, in order to paint the most severe diagnostics last.
3996 .sorted_by_key(|diagnostic| {
3997 std::cmp::Reverse(diagnostic.diagnostic.severity)
3998 });
3999
4000 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
4001 let start_display = diagnostic
4002 .range
4003 .start
4004 .to_display_point(&snapshot.display_snapshot);
4005 let end_display = diagnostic
4006 .range
4007 .end
4008 .to_display_point(&snapshot.display_snapshot);
4009 let color = match diagnostic.diagnostic.severity {
4010 DiagnosticSeverity::ERROR => theme.status().error,
4011 DiagnosticSeverity::WARNING => theme.status().warning,
4012 DiagnosticSeverity::INFORMATION => theme.status().info,
4013 _ => theme.status().hint,
4014 };
4015 ColoredRange {
4016 start: start_display.row(),
4017 end: end_display.row(),
4018 color,
4019 }
4020 });
4021 marker_quads.extend(
4022 scrollbar_layout
4023 .marker_quads_for_ranges(marker_row_ranges, Some(2)),
4024 );
4025 }
4026
4027 Arc::from(marker_quads)
4028 })
4029 .await;
4030
4031 editor.update(&mut cx, |editor, cx| {
4032 editor.scrollbar_marker_state.markers = scrollbar_markers;
4033 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
4034 editor.scrollbar_marker_state.pending_refresh = None;
4035 cx.notify();
4036 })?;
4037
4038 Ok(())
4039 }));
4040 });
4041 }
4042
4043 #[allow(clippy::too_many_arguments)]
4044 fn paint_highlighted_range(
4045 &self,
4046 range: Range<DisplayPoint>,
4047 color: Hsla,
4048 corner_radius: Pixels,
4049 line_end_overshoot: Pixels,
4050 layout: &EditorLayout,
4051 cx: &mut WindowContext,
4052 ) {
4053 let start_row = layout.visible_display_row_range.start;
4054 let end_row = layout.visible_display_row_range.end;
4055 if range.start != range.end {
4056 let row_range = if range.end.column() == 0 {
4057 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
4058 } else {
4059 cmp::max(range.start.row(), start_row)
4060 ..cmp::min(range.end.row().next_row(), end_row)
4061 };
4062
4063 let highlighted_range = HighlightedRange {
4064 color,
4065 line_height: layout.position_map.line_height,
4066 corner_radius,
4067 start_y: layout.content_origin.y
4068 + row_range.start.as_f32() * layout.position_map.line_height
4069 - layout.position_map.scroll_pixel_position.y,
4070 lines: row_range
4071 .iter_rows()
4072 .map(|row| {
4073 let line_layout =
4074 &layout.position_map.line_layouts[row.minus(start_row) as usize];
4075 HighlightedRangeLine {
4076 start_x: if row == range.start.row() {
4077 layout.content_origin.x
4078 + line_layout.x_for_index(range.start.column() as usize)
4079 - layout.position_map.scroll_pixel_position.x
4080 } else {
4081 layout.content_origin.x
4082 - layout.position_map.scroll_pixel_position.x
4083 },
4084 end_x: if row == range.end.row() {
4085 layout.content_origin.x
4086 + line_layout.x_for_index(range.end.column() as usize)
4087 - layout.position_map.scroll_pixel_position.x
4088 } else {
4089 layout.content_origin.x + line_layout.width + line_end_overshoot
4090 - layout.position_map.scroll_pixel_position.x
4091 },
4092 }
4093 })
4094 .collect(),
4095 };
4096
4097 highlighted_range.paint(layout.text_hitbox.bounds, cx);
4098 }
4099 }
4100
4101 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
4102 if let Some(mut inline_blame) = layout.inline_blame.take() {
4103 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
4104 inline_blame.paint(cx);
4105 })
4106 }
4107 }
4108
4109 fn paint_blocks(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
4110 for mut block in layout.blocks.drain(..) {
4111 block.element.paint(cx);
4112 }
4113 }
4114
4115 fn paint_inline_completion_popover(
4116 &mut self,
4117 layout: &mut EditorLayout,
4118 cx: &mut WindowContext,
4119 ) {
4120 if let Some(inline_completion_popover) = layout.inline_completion_popover.as_mut() {
4121 inline_completion_popover.paint(cx);
4122 }
4123 }
4124
4125 fn paint_mouse_context_menu(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
4126 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
4127 mouse_context_menu.paint(cx);
4128 }
4129 }
4130
4131 fn paint_scroll_wheel_listener(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
4132 cx.on_mouse_event({
4133 let position_map = layout.position_map.clone();
4134 let editor = self.editor.clone();
4135 let hitbox = layout.hitbox.clone();
4136 let mut delta = ScrollDelta::default();
4137
4138 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
4139 // accidentally turn off their scrolling.
4140 let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
4141
4142 move |event: &ScrollWheelEvent, phase, cx| {
4143 if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
4144 delta = delta.coalesce(event.delta);
4145 editor.update(cx, |editor, cx| {
4146 let position_map: &PositionMap = &position_map;
4147
4148 let line_height = position_map.line_height;
4149 let max_glyph_width = position_map.em_width;
4150 let (delta, axis) = match delta {
4151 gpui::ScrollDelta::Pixels(mut pixels) => {
4152 //Trackpad
4153 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
4154 (pixels, axis)
4155 }
4156
4157 gpui::ScrollDelta::Lines(lines) => {
4158 //Not trackpad
4159 let pixels =
4160 point(lines.x * max_glyph_width, lines.y * line_height);
4161 (pixels, None)
4162 }
4163 };
4164
4165 let current_scroll_position = position_map.snapshot.scroll_position();
4166 let x = (current_scroll_position.x * max_glyph_width
4167 - (delta.x * scroll_sensitivity))
4168 / max_glyph_width;
4169 let y = (current_scroll_position.y * line_height
4170 - (delta.y * scroll_sensitivity))
4171 / line_height;
4172 let mut scroll_position =
4173 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
4174 let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
4175 if forbid_vertical_scroll {
4176 scroll_position.y = current_scroll_position.y;
4177 }
4178
4179 if scroll_position != current_scroll_position {
4180 editor.scroll(scroll_position, axis, cx);
4181 cx.stop_propagation();
4182 } else if y < 0. {
4183 // Due to clamping, we may fail to detect cases of overscroll to the top;
4184 // We want the scroll manager to get an update in such cases and detect the change of direction
4185 // on the next frame.
4186 cx.notify();
4187 }
4188 });
4189 }
4190 }
4191 });
4192 }
4193
4194 fn paint_mouse_listeners(
4195 &mut self,
4196 layout: &EditorLayout,
4197 hovered_hunk: Option<HoveredHunk>,
4198 cx: &mut WindowContext,
4199 ) {
4200 self.paint_scroll_wheel_listener(layout, cx);
4201
4202 cx.on_mouse_event({
4203 let position_map = layout.position_map.clone();
4204 let editor = self.editor.clone();
4205 let text_hitbox = layout.text_hitbox.clone();
4206 let gutter_hitbox = layout.gutter_hitbox.clone();
4207
4208 move |event: &MouseDownEvent, phase, cx| {
4209 if phase == DispatchPhase::Bubble {
4210 match event.button {
4211 MouseButton::Left => editor.update(cx, |editor, cx| {
4212 Self::mouse_left_down(
4213 editor,
4214 event,
4215 hovered_hunk.clone(),
4216 &position_map,
4217 &text_hitbox,
4218 &gutter_hitbox,
4219 cx,
4220 );
4221 }),
4222 MouseButton::Right => editor.update(cx, |editor, cx| {
4223 Self::mouse_right_down(editor, event, &position_map, &text_hitbox, cx);
4224 }),
4225 MouseButton::Middle => editor.update(cx, |editor, cx| {
4226 Self::mouse_middle_down(editor, event, &position_map, &text_hitbox, cx);
4227 }),
4228 _ => {}
4229 };
4230 }
4231 }
4232 });
4233
4234 cx.on_mouse_event({
4235 let editor = self.editor.clone();
4236 let position_map = layout.position_map.clone();
4237 let text_hitbox = layout.text_hitbox.clone();
4238
4239 move |event: &MouseUpEvent, phase, cx| {
4240 if phase == DispatchPhase::Bubble {
4241 editor.update(cx, |editor, cx| {
4242 Self::mouse_up(editor, event, &position_map, &text_hitbox, cx)
4243 });
4244 }
4245 }
4246 });
4247 cx.on_mouse_event({
4248 let position_map = layout.position_map.clone();
4249 let editor = self.editor.clone();
4250 let text_hitbox = layout.text_hitbox.clone();
4251 let gutter_hitbox = layout.gutter_hitbox.clone();
4252
4253 move |event: &MouseMoveEvent, phase, cx| {
4254 if phase == DispatchPhase::Bubble {
4255 editor.update(cx, |editor, cx| {
4256 if editor.hover_state.focused(cx) {
4257 return;
4258 }
4259 if event.pressed_button == Some(MouseButton::Left)
4260 || event.pressed_button == Some(MouseButton::Middle)
4261 {
4262 Self::mouse_dragged(
4263 editor,
4264 event,
4265 &position_map,
4266 text_hitbox.bounds,
4267 cx,
4268 )
4269 }
4270
4271 Self::mouse_moved(
4272 editor,
4273 event,
4274 &position_map,
4275 &text_hitbox,
4276 &gutter_hitbox,
4277 cx,
4278 )
4279 });
4280 }
4281 }
4282 });
4283 }
4284
4285 fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
4286 bounds.upper_right().x - self.style.scrollbar_width
4287 }
4288
4289 fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
4290 let style = &self.style;
4291 let font_size = style.text.font_size.to_pixels(cx.rem_size());
4292 let layout = cx
4293 .text_system()
4294 .shape_line(
4295 SharedString::from(" ".repeat(column)),
4296 font_size,
4297 &[TextRun {
4298 len: column,
4299 font: style.text.font(),
4300 color: Hsla::default(),
4301 background_color: None,
4302 underline: None,
4303 strikethrough: None,
4304 }],
4305 )
4306 .unwrap();
4307
4308 layout.width
4309 }
4310
4311 fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
4312 let digit_count = (snapshot.widest_line_number() as f32).log10().floor() as usize + 1;
4313 self.column_pixels(digit_count, cx)
4314 }
4315}
4316
4317fn inline_completion_popover_text(
4318 editor_snapshot: &EditorSnapshot,
4319 edits: &Vec<(Range<Anchor>, String)>,
4320 cx: &WindowContext,
4321) -> (String, Vec<(Range<usize>, HighlightStyle)>) {
4322 let edit_start = edits
4323 .first()
4324 .unwrap()
4325 .0
4326 .start
4327 .to_display_point(editor_snapshot);
4328
4329 let mut text = String::new();
4330 let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
4331 let mut highlights = Vec::new();
4332 for (old_range, new_text) in edits {
4333 let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
4334 text.extend(
4335 editor_snapshot
4336 .buffer_snapshot
4337 .chunks(offset..old_offset_range.start, false)
4338 .map(|chunk| chunk.text),
4339 );
4340 offset = old_offset_range.end;
4341
4342 let start = text.len();
4343 text.push_str(new_text);
4344 let end = text.len();
4345 highlights.push((
4346 start..end,
4347 HighlightStyle {
4348 background_color: Some(cx.theme().status().created_background),
4349 ..Default::default()
4350 },
4351 ));
4352 }
4353
4354 let edit_end = edits
4355 .last()
4356 .unwrap()
4357 .0
4358 .end
4359 .to_display_point(editor_snapshot);
4360 let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
4361 .to_offset(editor_snapshot, Bias::Right);
4362 text.extend(
4363 editor_snapshot
4364 .buffer_snapshot
4365 .chunks(offset..end_of_line, false)
4366 .map(|chunk| chunk.text),
4367 );
4368
4369 (text, highlights)
4370}
4371
4372fn all_edits_insertions_or_deletions(
4373 edits: &Vec<(Range<Anchor>, String)>,
4374 snapshot: &MultiBufferSnapshot,
4375) -> bool {
4376 let mut all_insertions = true;
4377 let mut all_deletions = true;
4378
4379 for (range, new_text) in edits.iter() {
4380 let range_is_empty = range.to_offset(&snapshot).is_empty();
4381 let text_is_empty = new_text.is_empty();
4382
4383 if range_is_empty != text_is_empty {
4384 if range_is_empty {
4385 all_deletions = false;
4386 } else {
4387 all_insertions = false;
4388 }
4389 } else {
4390 return false;
4391 }
4392
4393 if !all_insertions && !all_deletions {
4394 return false;
4395 }
4396 }
4397 all_insertions || all_deletions
4398}
4399
4400#[allow(clippy::too_many_arguments)]
4401fn prepaint_gutter_button(
4402 button: IconButton,
4403 row: DisplayRow,
4404 line_height: Pixels,
4405 gutter_dimensions: &GutterDimensions,
4406 scroll_pixel_position: gpui::Point<Pixels>,
4407 gutter_hitbox: &Hitbox,
4408 rows_with_hunk_bounds: &HashMap<DisplayRow, Bounds<Pixels>>,
4409 cx: &mut WindowContext<'_>,
4410) -> AnyElement {
4411 let mut button = button.into_any_element();
4412 let available_space = size(
4413 AvailableSpace::MinContent,
4414 AvailableSpace::Definite(line_height),
4415 );
4416 let indicator_size = button.layout_as_root(available_space, cx);
4417
4418 let blame_width = gutter_dimensions.git_blame_entries_width;
4419 let gutter_width = rows_with_hunk_bounds
4420 .get(&row)
4421 .map(|bounds| bounds.size.width);
4422 let left_offset = blame_width.max(gutter_width).unwrap_or_default();
4423
4424 let mut x = left_offset;
4425 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
4426 - indicator_size.width
4427 - left_offset;
4428 x += available_width / 2.;
4429
4430 let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
4431 y += (line_height - indicator_size.height) / 2.;
4432
4433 button.prepaint_as_root(gutter_hitbox.origin + point(x, y), available_space, cx);
4434 button
4435}
4436
4437fn render_inline_blame_entry(
4438 blame: &gpui::Model<GitBlame>,
4439 blame_entry: BlameEntry,
4440 style: &EditorStyle,
4441 workspace: Option<WeakView<Workspace>>,
4442 cx: &mut WindowContext<'_>,
4443) -> AnyElement {
4444 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
4445
4446 let author = blame_entry.author.as_deref().unwrap_or_default();
4447 let summary_enabled = ProjectSettings::get_global(cx)
4448 .git
4449 .show_inline_commit_summary();
4450
4451 let text = match blame_entry.summary.as_ref() {
4452 Some(summary) if summary_enabled => {
4453 format!("{}, {} - {}", author, relative_timestamp, summary)
4454 }
4455 _ => format!("{}, {}", author, relative_timestamp),
4456 };
4457
4458 let details = blame.read(cx).details_for_entry(&blame_entry);
4459
4460 let tooltip = cx.new_view(|_| BlameEntryTooltip::new(blame_entry, details, style, workspace));
4461
4462 h_flex()
4463 .id("inline-blame")
4464 .w_full()
4465 .font_family(style.text.font().family)
4466 .text_color(cx.theme().status().hint)
4467 .line_height(style.text.line_height)
4468 .child(Icon::new(IconName::FileGit).color(Color::Hint))
4469 .child(text)
4470 .gap_2()
4471 .hoverable_tooltip(move |_| tooltip.clone().into())
4472 .into_any()
4473}
4474
4475fn render_blame_entry(
4476 ix: usize,
4477 blame: &gpui::Model<GitBlame>,
4478 blame_entry: BlameEntry,
4479 style: &EditorStyle,
4480 last_used_color: &mut Option<(PlayerColor, Oid)>,
4481 editor: View<Editor>,
4482 cx: &mut WindowContext<'_>,
4483) -> AnyElement {
4484 let mut sha_color = cx
4485 .theme()
4486 .players()
4487 .color_for_participant(blame_entry.sha.into());
4488 // If the last color we used is the same as the one we get for this line, but
4489 // the commit SHAs are different, then we try again to get a different color.
4490 match *last_used_color {
4491 Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
4492 let index: u32 = blame_entry.sha.into();
4493 sha_color = cx.theme().players().color_for_participant(index + 1);
4494 }
4495 _ => {}
4496 };
4497 last_used_color.replace((sha_color, blame_entry.sha));
4498
4499 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
4500
4501 let short_commit_id = blame_entry.sha.display_short();
4502
4503 let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
4504 let name = util::truncate_and_trailoff(author_name, GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED);
4505
4506 let details = blame.read(cx).details_for_entry(&blame_entry);
4507
4508 let workspace = editor.read(cx).workspace.as_ref().map(|(w, _)| w.clone());
4509
4510 let tooltip = cx.new_view(|_| {
4511 BlameEntryTooltip::new(blame_entry.clone(), details.clone(), style, workspace)
4512 });
4513
4514 h_flex()
4515 .w_full()
4516 .justify_between()
4517 .font_family(style.text.font().family)
4518 .line_height(style.text.line_height)
4519 .id(("blame", ix))
4520 .text_color(cx.theme().status().hint)
4521 .pr_2()
4522 .gap_2()
4523 .child(
4524 h_flex()
4525 .items_center()
4526 .gap_2()
4527 .child(div().text_color(sha_color.cursor).child(short_commit_id))
4528 .child(name),
4529 )
4530 .child(relative_timestamp)
4531 .on_mouse_down(MouseButton::Right, {
4532 let blame_entry = blame_entry.clone();
4533 let details = details.clone();
4534 move |event, cx| {
4535 deploy_blame_entry_context_menu(
4536 &blame_entry,
4537 details.as_ref(),
4538 editor.clone(),
4539 event.position,
4540 cx,
4541 );
4542 }
4543 })
4544 .hover(|style| style.bg(cx.theme().colors().element_hover))
4545 .when_some(
4546 details.and_then(|details| details.permalink),
4547 |this, url| {
4548 let url = url.clone();
4549 this.cursor_pointer().on_click(move |_, cx| {
4550 cx.stop_propagation();
4551 cx.open_url(url.as_str())
4552 })
4553 },
4554 )
4555 .hoverable_tooltip(move |_| tooltip.clone().into())
4556 .into_any()
4557}
4558
4559fn deploy_blame_entry_context_menu(
4560 blame_entry: &BlameEntry,
4561 details: Option<&CommitDetails>,
4562 editor: View<Editor>,
4563 position: gpui::Point<Pixels>,
4564 cx: &mut WindowContext<'_>,
4565) {
4566 let context_menu = ContextMenu::build(cx, move |menu, _| {
4567 let sha = format!("{}", blame_entry.sha);
4568 menu.on_blur_subscription(Subscription::new(|| {}))
4569 .entry("Copy commit SHA", None, move |cx| {
4570 cx.write_to_clipboard(ClipboardItem::new_string(sha.clone()));
4571 })
4572 .when_some(
4573 details.and_then(|details| details.permalink.clone()),
4574 |this, url| this.entry("Open permalink", None, move |cx| cx.open_url(url.as_str())),
4575 )
4576 });
4577
4578 editor.update(cx, move |editor, cx| {
4579 editor.mouse_context_menu = Some(MouseContextMenu::new(
4580 MenuPosition::PinnedToScreen(position),
4581 context_menu,
4582 cx,
4583 ));
4584 cx.notify();
4585 });
4586}
4587
4588#[derive(Debug)]
4589pub(crate) struct LineWithInvisibles {
4590 fragments: SmallVec<[LineFragment; 1]>,
4591 invisibles: Vec<Invisible>,
4592 len: usize,
4593 width: Pixels,
4594 font_size: Pixels,
4595}
4596
4597#[allow(clippy::large_enum_variant)]
4598enum LineFragment {
4599 Text(ShapedLine),
4600 Element {
4601 element: Option<AnyElement>,
4602 size: Size<Pixels>,
4603 len: usize,
4604 },
4605}
4606
4607impl fmt::Debug for LineFragment {
4608 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4609 match self {
4610 LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
4611 LineFragment::Element { size, len, .. } => f
4612 .debug_struct("Element")
4613 .field("size", size)
4614 .field("len", len)
4615 .finish(),
4616 }
4617 }
4618}
4619
4620impl LineWithInvisibles {
4621 #[allow(clippy::too_many_arguments)]
4622 fn from_chunks<'a>(
4623 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
4624 editor_style: &EditorStyle,
4625 max_line_len: usize,
4626 max_line_count: usize,
4627 editor_mode: EditorMode,
4628 text_width: Pixels,
4629 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
4630 cx: &mut WindowContext,
4631 ) -> Vec<Self> {
4632 let text_style = &editor_style.text;
4633 let mut layouts = Vec::with_capacity(max_line_count);
4634 let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
4635 let mut line = String::new();
4636 let mut invisibles = Vec::new();
4637 let mut width = Pixels::ZERO;
4638 let mut len = 0;
4639 let mut styles = Vec::new();
4640 let mut non_whitespace_added = false;
4641 let mut row = 0;
4642 let mut line_exceeded_max_len = false;
4643 let font_size = text_style.font_size.to_pixels(cx.rem_size());
4644
4645 let ellipsis = SharedString::from("⋯");
4646
4647 for highlighted_chunk in chunks.chain([HighlightedChunk {
4648 text: "\n",
4649 style: None,
4650 is_tab: false,
4651 replacement: None,
4652 }]) {
4653 if let Some(replacement) = highlighted_chunk.replacement {
4654 if !line.is_empty() {
4655 let shaped_line = cx
4656 .text_system()
4657 .shape_line(line.clone().into(), font_size, &styles)
4658 .unwrap();
4659 width += shaped_line.width;
4660 len += shaped_line.len;
4661 fragments.push(LineFragment::Text(shaped_line));
4662 line.clear();
4663 styles.clear();
4664 }
4665
4666 match replacement {
4667 ChunkReplacement::Renderer(renderer) => {
4668 let available_width = if renderer.constrain_width {
4669 let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
4670 ellipsis.clone()
4671 } else {
4672 SharedString::from(Arc::from(highlighted_chunk.text))
4673 };
4674 let shaped_line = cx
4675 .text_system()
4676 .shape_line(
4677 chunk,
4678 font_size,
4679 &[text_style.to_run(highlighted_chunk.text.len())],
4680 )
4681 .unwrap();
4682 AvailableSpace::Definite(shaped_line.width)
4683 } else {
4684 AvailableSpace::MinContent
4685 };
4686
4687 let mut element = (renderer.render)(&mut ChunkRendererContext {
4688 context: cx,
4689 max_width: text_width,
4690 });
4691 let line_height = text_style.line_height_in_pixels(cx.rem_size());
4692 let size = element.layout_as_root(
4693 size(available_width, AvailableSpace::Definite(line_height)),
4694 cx,
4695 );
4696
4697 width += size.width;
4698 len += highlighted_chunk.text.len();
4699 fragments.push(LineFragment::Element {
4700 element: Some(element),
4701 size,
4702 len: highlighted_chunk.text.len(),
4703 });
4704 }
4705 ChunkReplacement::Str(x) => {
4706 let text_style = if let Some(style) = highlighted_chunk.style {
4707 Cow::Owned(text_style.clone().highlight(style))
4708 } else {
4709 Cow::Borrowed(text_style)
4710 };
4711
4712 let run = TextRun {
4713 len: x.len(),
4714 font: text_style.font(),
4715 color: text_style.color,
4716 background_color: text_style.background_color,
4717 underline: text_style.underline,
4718 strikethrough: text_style.strikethrough,
4719 };
4720 let line_layout = cx
4721 .text_system()
4722 .shape_line(x, font_size, &[run])
4723 .unwrap()
4724 .with_len(highlighted_chunk.text.len());
4725
4726 width += line_layout.width;
4727 len += highlighted_chunk.text.len();
4728 fragments.push(LineFragment::Text(line_layout))
4729 }
4730 }
4731 } else {
4732 for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
4733 if ix > 0 {
4734 let shaped_line = cx
4735 .text_system()
4736 .shape_line(line.clone().into(), font_size, &styles)
4737 .unwrap();
4738 width += shaped_line.width;
4739 len += shaped_line.len;
4740 fragments.push(LineFragment::Text(shaped_line));
4741 layouts.push(Self {
4742 width: mem::take(&mut width),
4743 len: mem::take(&mut len),
4744 fragments: mem::take(&mut fragments),
4745 invisibles: std::mem::take(&mut invisibles),
4746 font_size,
4747 });
4748
4749 line.clear();
4750 styles.clear();
4751 row += 1;
4752 line_exceeded_max_len = false;
4753 non_whitespace_added = false;
4754 if row == max_line_count {
4755 return layouts;
4756 }
4757 }
4758
4759 if !line_chunk.is_empty() && !line_exceeded_max_len {
4760 let text_style = if let Some(style) = highlighted_chunk.style {
4761 Cow::Owned(text_style.clone().highlight(style))
4762 } else {
4763 Cow::Borrowed(text_style)
4764 };
4765
4766 if line.len() + line_chunk.len() > max_line_len {
4767 let mut chunk_len = max_line_len - line.len();
4768 while !line_chunk.is_char_boundary(chunk_len) {
4769 chunk_len -= 1;
4770 }
4771 line_chunk = &line_chunk[..chunk_len];
4772 line_exceeded_max_len = true;
4773 }
4774
4775 styles.push(TextRun {
4776 len: line_chunk.len(),
4777 font: text_style.font(),
4778 color: text_style.color,
4779 background_color: text_style.background_color,
4780 underline: text_style.underline,
4781 strikethrough: text_style.strikethrough,
4782 });
4783
4784 if editor_mode == EditorMode::Full {
4785 // Line wrap pads its contents with fake whitespaces,
4786 // avoid printing them
4787 let is_soft_wrapped = is_row_soft_wrapped(row);
4788 if highlighted_chunk.is_tab {
4789 if non_whitespace_added || !is_soft_wrapped {
4790 invisibles.push(Invisible::Tab {
4791 line_start_offset: line.len(),
4792 line_end_offset: line.len() + line_chunk.len(),
4793 });
4794 }
4795 } else {
4796 invisibles.extend(
4797 line_chunk
4798 .bytes()
4799 .enumerate()
4800 .filter(|(_, line_byte)| {
4801 let is_whitespace =
4802 (*line_byte as char).is_whitespace();
4803 non_whitespace_added |= !is_whitespace;
4804 is_whitespace
4805 && (non_whitespace_added || !is_soft_wrapped)
4806 })
4807 .map(|(whitespace_index, _)| Invisible::Whitespace {
4808 line_offset: line.len() + whitespace_index,
4809 }),
4810 )
4811 }
4812 }
4813
4814 line.push_str(line_chunk);
4815 }
4816 }
4817 }
4818 }
4819
4820 layouts
4821 }
4822
4823 fn prepaint(
4824 &mut self,
4825 line_height: Pixels,
4826 scroll_pixel_position: gpui::Point<Pixels>,
4827 row: DisplayRow,
4828 content_origin: gpui::Point<Pixels>,
4829 line_elements: &mut SmallVec<[AnyElement; 1]>,
4830 cx: &mut WindowContext,
4831 ) {
4832 let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
4833 let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
4834 for fragment in &mut self.fragments {
4835 match fragment {
4836 LineFragment::Text(line) => {
4837 fragment_origin.x += line.width;
4838 }
4839 LineFragment::Element { element, size, .. } => {
4840 let mut element = element
4841 .take()
4842 .expect("you can't prepaint LineWithInvisibles twice");
4843
4844 // Center the element vertically within the line.
4845 let mut element_origin = fragment_origin;
4846 element_origin.y += (line_height - size.height) / 2.;
4847 element.prepaint_at(element_origin, cx);
4848 line_elements.push(element);
4849
4850 fragment_origin.x += size.width;
4851 }
4852 }
4853 }
4854 }
4855
4856 fn draw(
4857 &self,
4858 layout: &EditorLayout,
4859 row: DisplayRow,
4860 content_origin: gpui::Point<Pixels>,
4861 whitespace_setting: ShowWhitespaceSetting,
4862 selection_ranges: &[Range<DisplayPoint>],
4863 cx: &mut WindowContext,
4864 ) {
4865 let line_height = layout.position_map.line_height;
4866 let line_y = line_height
4867 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
4868
4869 let mut fragment_origin =
4870 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
4871
4872 for fragment in &self.fragments {
4873 match fragment {
4874 LineFragment::Text(line) => {
4875 line.paint(fragment_origin, line_height, cx).log_err();
4876 fragment_origin.x += line.width;
4877 }
4878 LineFragment::Element { size, .. } => {
4879 fragment_origin.x += size.width;
4880 }
4881 }
4882 }
4883
4884 self.draw_invisibles(
4885 selection_ranges,
4886 layout,
4887 content_origin,
4888 line_y,
4889 row,
4890 line_height,
4891 whitespace_setting,
4892 cx,
4893 );
4894 }
4895
4896 #[allow(clippy::too_many_arguments)]
4897 fn draw_invisibles(
4898 &self,
4899 selection_ranges: &[Range<DisplayPoint>],
4900 layout: &EditorLayout,
4901 content_origin: gpui::Point<Pixels>,
4902 line_y: Pixels,
4903 row: DisplayRow,
4904 line_height: Pixels,
4905 whitespace_setting: ShowWhitespaceSetting,
4906 cx: &mut WindowContext,
4907 ) {
4908 let extract_whitespace_info = |invisible: &Invisible| {
4909 let (token_offset, token_end_offset, invisible_symbol) = match invisible {
4910 Invisible::Tab {
4911 line_start_offset,
4912 line_end_offset,
4913 } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
4914 Invisible::Whitespace { line_offset } => {
4915 (*line_offset, line_offset + 1, &layout.space_invisible)
4916 }
4917 };
4918
4919 let x_offset = self.x_for_index(token_offset);
4920 let invisible_offset =
4921 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
4922 let origin = content_origin
4923 + gpui::point(
4924 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
4925 line_y,
4926 );
4927
4928 (
4929 [token_offset, token_end_offset],
4930 Box::new(move |cx: &mut WindowContext| {
4931 invisible_symbol.paint(origin, line_height, cx).log_err();
4932 }),
4933 )
4934 };
4935
4936 let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
4937 match whitespace_setting {
4938 ShowWhitespaceSetting::None => (),
4939 ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(cx)),
4940 ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
4941 let invisible_point = DisplayPoint::new(row, start as u32);
4942 if !selection_ranges
4943 .iter()
4944 .any(|region| region.start <= invisible_point && invisible_point < region.end)
4945 {
4946 return;
4947 }
4948
4949 paint(cx);
4950 }),
4951
4952 // For a whitespace to be on a boundary, any of the following conditions need to be met:
4953 // - It is a tab
4954 // - It is adjacent to an edge (start or end)
4955 // - It is adjacent to a whitespace (left or right)
4956 ShowWhitespaceSetting::Boundary => {
4957 // 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
4958 // the above cases.
4959 // Note: We zip in the original `invisibles` to check for tab equality
4960 let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut WindowContext)>)> = None;
4961 for (([start, end], paint), invisible) in
4962 invisible_iter.zip_eq(self.invisibles.iter())
4963 {
4964 let should_render = match (&last_seen, invisible) {
4965 (_, Invisible::Tab { .. }) => true,
4966 (Some((_, last_end, _)), _) => *last_end == start,
4967 _ => false,
4968 };
4969
4970 if should_render || start == 0 || end == self.len {
4971 paint(cx);
4972
4973 // Since we are scanning from the left, we will skip over the first available whitespace that is part
4974 // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
4975 if let Some((should_render_last, last_end, paint_last)) = last_seen {
4976 // Note that we need to make sure that the last one is actually adjacent
4977 if !should_render_last && last_end == start {
4978 paint_last(cx);
4979 }
4980 }
4981 }
4982
4983 // Manually render anything within a selection
4984 let invisible_point = DisplayPoint::new(row, start as u32);
4985 if selection_ranges.iter().any(|region| {
4986 region.start <= invisible_point && invisible_point < region.end
4987 }) {
4988 paint(cx);
4989 }
4990
4991 last_seen = Some((should_render, end, paint));
4992 }
4993 }
4994 }
4995 }
4996
4997 pub fn x_for_index(&self, index: usize) -> Pixels {
4998 let mut fragment_start_x = Pixels::ZERO;
4999 let mut fragment_start_index = 0;
5000
5001 for fragment in &self.fragments {
5002 match fragment {
5003 LineFragment::Text(shaped_line) => {
5004 let fragment_end_index = fragment_start_index + shaped_line.len;
5005 if index < fragment_end_index {
5006 return fragment_start_x
5007 + shaped_line.x_for_index(index - fragment_start_index);
5008 }
5009 fragment_start_x += shaped_line.width;
5010 fragment_start_index = fragment_end_index;
5011 }
5012 LineFragment::Element { len, size, .. } => {
5013 let fragment_end_index = fragment_start_index + len;
5014 if index < fragment_end_index {
5015 return fragment_start_x;
5016 }
5017 fragment_start_x += size.width;
5018 fragment_start_index = fragment_end_index;
5019 }
5020 }
5021 }
5022
5023 fragment_start_x
5024 }
5025
5026 pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
5027 let mut fragment_start_x = Pixels::ZERO;
5028 let mut fragment_start_index = 0;
5029
5030 for fragment in &self.fragments {
5031 match fragment {
5032 LineFragment::Text(shaped_line) => {
5033 let fragment_end_x = fragment_start_x + shaped_line.width;
5034 if x < fragment_end_x {
5035 return Some(
5036 fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
5037 );
5038 }
5039 fragment_start_x = fragment_end_x;
5040 fragment_start_index += shaped_line.len;
5041 }
5042 LineFragment::Element { len, size, .. } => {
5043 let fragment_end_x = fragment_start_x + size.width;
5044 if x < fragment_end_x {
5045 return Some(fragment_start_index);
5046 }
5047 fragment_start_index += len;
5048 fragment_start_x = fragment_end_x;
5049 }
5050 }
5051 }
5052
5053 None
5054 }
5055
5056 pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
5057 let mut fragment_start_index = 0;
5058
5059 for fragment in &self.fragments {
5060 match fragment {
5061 LineFragment::Text(shaped_line) => {
5062 let fragment_end_index = fragment_start_index + shaped_line.len;
5063 if index < fragment_end_index {
5064 return shaped_line.font_id_for_index(index - fragment_start_index);
5065 }
5066 fragment_start_index = fragment_end_index;
5067 }
5068 LineFragment::Element { len, .. } => {
5069 let fragment_end_index = fragment_start_index + len;
5070 if index < fragment_end_index {
5071 return None;
5072 }
5073 fragment_start_index = fragment_end_index;
5074 }
5075 }
5076 }
5077
5078 None
5079 }
5080}
5081
5082#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5083enum Invisible {
5084 /// A tab character
5085 ///
5086 /// A tab character is internally represented by spaces (configured by the user's tab width)
5087 /// aligned to the nearest column, so it's necessary to store the start and end offset for
5088 /// adjacency checks.
5089 Tab {
5090 line_start_offset: usize,
5091 line_end_offset: usize,
5092 },
5093 Whitespace {
5094 line_offset: usize,
5095 },
5096}
5097
5098impl EditorElement {
5099 /// Returns the rem size to use when rendering the [`EditorElement`].
5100 ///
5101 /// This allows UI elements to scale based on the `buffer_font_size`.
5102 fn rem_size(&self, cx: &WindowContext) -> Option<Pixels> {
5103 match self.editor.read(cx).mode {
5104 EditorMode::Full => {
5105 let buffer_font_size = self.style.text.font_size;
5106 match buffer_font_size {
5107 AbsoluteLength::Pixels(pixels) => {
5108 let rem_size_scale = {
5109 // Our default UI font size is 14px on a 16px base scale.
5110 // This means the default UI font size is 0.875rems.
5111 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
5112
5113 // We then determine the delta between a single rem and the default font
5114 // size scale.
5115 let default_font_size_delta = 1. - default_font_size_scale;
5116
5117 // Finally, we add this delta to 1rem to get the scale factor that
5118 // should be used to scale up the UI.
5119 1. + default_font_size_delta
5120 };
5121
5122 Some(pixels * rem_size_scale)
5123 }
5124 AbsoluteLength::Rems(rems) => {
5125 Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
5126 }
5127 }
5128 }
5129 // We currently use single-line and auto-height editors in UI contexts,
5130 // so we don't want to scale everything with the buffer font size, as it
5131 // ends up looking off.
5132 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => None,
5133 }
5134 }
5135}
5136
5137impl Element for EditorElement {
5138 type RequestLayoutState = ();
5139 type PrepaintState = EditorLayout;
5140
5141 fn id(&self) -> Option<ElementId> {
5142 None
5143 }
5144
5145 fn request_layout(
5146 &mut self,
5147 _: Option<&GlobalElementId>,
5148 cx: &mut WindowContext,
5149 ) -> (gpui::LayoutId, ()) {
5150 let rem_size = self.rem_size(cx);
5151 cx.with_rem_size(rem_size, |cx| {
5152 self.editor.update(cx, |editor, cx| {
5153 editor.set_style(self.style.clone(), cx);
5154
5155 let layout_id = match editor.mode {
5156 EditorMode::SingleLine { auto_width } => {
5157 let rem_size = cx.rem_size();
5158
5159 let height = self.style.text.line_height_in_pixels(rem_size);
5160 if auto_width {
5161 let editor_handle = cx.view().clone();
5162 let style = self.style.clone();
5163 cx.request_measured_layout(Style::default(), move |_, _, cx| {
5164 let editor_snapshot =
5165 editor_handle.update(cx, |editor, cx| editor.snapshot(cx));
5166 let line = Self::layout_lines(
5167 DisplayRow(0)..DisplayRow(1),
5168 &editor_snapshot,
5169 &style,
5170 px(f32::MAX),
5171 |_| false, // Single lines never soft wrap
5172 cx,
5173 )
5174 .pop()
5175 .unwrap();
5176
5177 let font_id = cx.text_system().resolve_font(&style.text.font());
5178 let font_size = style.text.font_size.to_pixels(cx.rem_size());
5179 let em_width = cx
5180 .text_system()
5181 .typographic_bounds(font_id, font_size, 'm')
5182 .unwrap()
5183 .size
5184 .width;
5185
5186 size(line.width + em_width, height)
5187 })
5188 } else {
5189 let mut style = Style::default();
5190 style.size.height = height.into();
5191 style.size.width = relative(1.).into();
5192 cx.request_layout(style, None)
5193 }
5194 }
5195 EditorMode::AutoHeight { max_lines } => {
5196 let editor_handle = cx.view().clone();
5197 let max_line_number_width =
5198 self.max_line_number_width(&editor.snapshot(cx), cx);
5199 cx.request_measured_layout(
5200 Style::default(),
5201 move |known_dimensions, available_space, cx| {
5202 editor_handle
5203 .update(cx, |editor, cx| {
5204 compute_auto_height_layout(
5205 editor,
5206 max_lines,
5207 max_line_number_width,
5208 known_dimensions,
5209 available_space.width,
5210 cx,
5211 )
5212 })
5213 .unwrap_or_default()
5214 },
5215 )
5216 }
5217 EditorMode::Full => {
5218 let mut style = Style::default();
5219 style.size.width = relative(1.).into();
5220 style.size.height = relative(1.).into();
5221 cx.request_layout(style, None)
5222 }
5223 };
5224
5225 (layout_id, ())
5226 })
5227 })
5228 }
5229
5230 fn prepaint(
5231 &mut self,
5232 _: Option<&GlobalElementId>,
5233 bounds: Bounds<Pixels>,
5234 _: &mut Self::RequestLayoutState,
5235 cx: &mut WindowContext,
5236 ) -> Self::PrepaintState {
5237 let text_style = TextStyleRefinement {
5238 font_size: Some(self.style.text.font_size),
5239 line_height: Some(self.style.text.line_height),
5240 ..Default::default()
5241 };
5242 let focus_handle = self.editor.focus_handle(cx);
5243 cx.set_view_id(self.editor.entity_id());
5244 cx.set_focus_handle(&focus_handle);
5245
5246 let rem_size = self.rem_size(cx);
5247 cx.with_rem_size(rem_size, |cx| {
5248 cx.with_text_style(Some(text_style), |cx| {
5249 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
5250 let mut snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
5251 let style = self.style.clone();
5252
5253 let font_id = cx.text_system().resolve_font(&style.text.font());
5254 let font_size = style.text.font_size.to_pixels(cx.rem_size());
5255 let line_height = style.text.line_height_in_pixels(cx.rem_size());
5256 let em_width = cx
5257 .text_system()
5258 .typographic_bounds(font_id, font_size, 'm')
5259 .unwrap()
5260 .size
5261 .width;
5262 let em_advance = cx
5263 .text_system()
5264 .advance(font_id, font_size, 'm')
5265 .unwrap()
5266 .width;
5267
5268 let gutter_dimensions = snapshot.gutter_dimensions(
5269 font_id,
5270 font_size,
5271 em_width,
5272 em_advance,
5273 self.max_line_number_width(&snapshot, cx),
5274 cx,
5275 );
5276 let text_width = bounds.size.width - gutter_dimensions.width;
5277
5278 let right_margin = if snapshot.mode == EditorMode::Full {
5279 EditorElement::SCROLLBAR_WIDTH
5280 } else {
5281 px(0.)
5282 };
5283 let overscroll = size(em_width + right_margin, px(0.));
5284
5285 let editor_width =
5286 text_width - gutter_dimensions.margin - overscroll.width - em_width;
5287
5288 snapshot = self.editor.update(cx, |editor, cx| {
5289 editor.last_bounds = Some(bounds);
5290 editor.gutter_dimensions = gutter_dimensions;
5291 editor.set_visible_line_count(bounds.size.height / line_height, cx);
5292
5293 if matches!(editor.mode, EditorMode::AutoHeight { .. }) {
5294 snapshot
5295 } else {
5296 let wrap_width = match editor.soft_wrap_mode(cx) {
5297 SoftWrap::GitDiff => None,
5298 SoftWrap::None => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
5299 SoftWrap::EditorWidth => Some(editor_width),
5300 SoftWrap::Column(column) => Some(column as f32 * em_advance),
5301 SoftWrap::Bounded(column) => {
5302 Some(editor_width.min(column as f32 * em_advance))
5303 }
5304 };
5305
5306 if editor.set_wrap_width(wrap_width, cx) {
5307 editor.snapshot(cx)
5308 } else {
5309 snapshot
5310 }
5311 }
5312 });
5313
5314 let wrap_guides = self
5315 .editor
5316 .read(cx)
5317 .wrap_guides(cx)
5318 .iter()
5319 .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
5320 .collect::<SmallVec<[_; 2]>>();
5321
5322 let hitbox = cx.insert_hitbox(bounds, false);
5323 let gutter_hitbox =
5324 cx.insert_hitbox(gutter_bounds(bounds, gutter_dimensions), false);
5325 let text_hitbox = cx.insert_hitbox(
5326 Bounds {
5327 origin: gutter_hitbox.upper_right(),
5328 size: size(text_width, bounds.size.height),
5329 },
5330 false,
5331 );
5332 // Offset the content_bounds from the text_bounds by the gutter margin (which
5333 // is roughly half a character wide) to make hit testing work more like how we want.
5334 let content_origin =
5335 text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
5336
5337 let height_in_lines = bounds.size.height / line_height;
5338 let max_row = snapshot.max_point().row().as_f32();
5339 let max_scroll_top = if matches!(snapshot.mode, EditorMode::AutoHeight { .. }) {
5340 (max_row - height_in_lines + 1.).max(0.)
5341 } else {
5342 let settings = EditorSettings::get_global(cx);
5343 match settings.scroll_beyond_last_line {
5344 ScrollBeyondLastLine::OnePage => max_row,
5345 ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
5346 ScrollBeyondLastLine::VerticalScrollMargin => {
5347 (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
5348 .max(0.)
5349 }
5350 }
5351 };
5352
5353 let mut autoscroll_request = None;
5354 let mut autoscroll_containing_element = false;
5355 let mut autoscroll_horizontally = false;
5356 self.editor.update(cx, |editor, cx| {
5357 autoscroll_request = editor.autoscroll_request();
5358 autoscroll_containing_element =
5359 autoscroll_request.is_some() || editor.has_pending_selection();
5360 autoscroll_horizontally =
5361 editor.autoscroll_vertically(bounds, line_height, max_scroll_top, cx);
5362 snapshot = editor.snapshot(cx);
5363 });
5364
5365 let mut scroll_position = snapshot.scroll_position();
5366 // The scroll position is a fractional point, the whole number of which represents
5367 // the top of the window in terms of display rows.
5368 let start_row = DisplayRow(scroll_position.y as u32);
5369 let max_row = snapshot.max_point().row();
5370 let end_row = cmp::min(
5371 (scroll_position.y + height_in_lines).ceil() as u32,
5372 max_row.next_row().0,
5373 );
5374 let end_row = DisplayRow(end_row);
5375
5376 let buffer_rows = snapshot
5377 .buffer_rows(start_row)
5378 .take((start_row..end_row).len())
5379 .collect::<Vec<_>>();
5380 let is_row_soft_wrapped =
5381 |row| buffer_rows.get(row).copied().flatten().is_none();
5382
5383 let start_anchor = if start_row == Default::default() {
5384 Anchor::min()
5385 } else {
5386 snapshot.buffer_snapshot.anchor_before(
5387 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
5388 )
5389 };
5390 let end_anchor = if end_row > max_row {
5391 Anchor::max()
5392 } else {
5393 snapshot.buffer_snapshot.anchor_before(
5394 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
5395 )
5396 };
5397
5398 let highlighted_rows = self
5399 .editor
5400 .update(cx, |editor, cx| editor.highlighted_display_rows(cx));
5401 let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
5402 start_anchor..end_anchor,
5403 &snapshot.display_snapshot,
5404 cx.theme().colors(),
5405 );
5406 let highlighted_gutter_ranges =
5407 self.editor.read(cx).gutter_highlights_in_range(
5408 start_anchor..end_anchor,
5409 &snapshot.display_snapshot,
5410 cx,
5411 );
5412
5413 let redacted_ranges = self.editor.read(cx).redacted_ranges(
5414 start_anchor..end_anchor,
5415 &snapshot.display_snapshot,
5416 cx,
5417 );
5418
5419 let local_selections: Vec<Selection<Point>> =
5420 self.editor.update(cx, |editor, cx| {
5421 let mut selections = editor
5422 .selections
5423 .disjoint_in_range(start_anchor..end_anchor, cx);
5424 selections.extend(editor.selections.pending(cx));
5425 selections
5426 });
5427
5428 let (selections, active_rows, newest_selection_head) = self.layout_selections(
5429 start_anchor,
5430 end_anchor,
5431 &local_selections,
5432 &snapshot,
5433 start_row,
5434 end_row,
5435 cx,
5436 );
5437
5438 let line_numbers = self.layout_line_numbers(
5439 start_row..end_row,
5440 buffer_rows.iter().copied(),
5441 &active_rows,
5442 newest_selection_head,
5443 &snapshot,
5444 cx,
5445 );
5446
5447 let mut crease_toggles = cx.with_element_namespace("crease_toggles", |cx| {
5448 self.layout_crease_toggles(
5449 start_row..end_row,
5450 buffer_rows.iter().copied(),
5451 &active_rows,
5452 &snapshot,
5453 cx,
5454 )
5455 });
5456 let crease_trailers = cx.with_element_namespace("crease_trailers", |cx| {
5457 self.layout_crease_trailers(buffer_rows.iter().copied(), &snapshot, cx)
5458 });
5459
5460 let display_hunks = self.layout_gutter_git_hunks(
5461 line_height,
5462 &gutter_hitbox,
5463 start_row..end_row,
5464 start_anchor..end_anchor,
5465 &snapshot,
5466 cx,
5467 );
5468
5469 let mut max_visible_line_width = Pixels::ZERO;
5470 let mut line_layouts = Self::layout_lines(
5471 start_row..end_row,
5472 &snapshot,
5473 &self.style,
5474 editor_width,
5475 is_row_soft_wrapped,
5476 cx,
5477 );
5478 for line_with_invisibles in &line_layouts {
5479 if line_with_invisibles.width > max_visible_line_width {
5480 max_visible_line_width = line_with_invisibles.width;
5481 }
5482 }
5483
5484 let longest_line_width = layout_line(
5485 snapshot.longest_row(),
5486 &snapshot,
5487 &style,
5488 editor_width,
5489 is_row_soft_wrapped,
5490 cx,
5491 )
5492 .width;
5493 let mut scroll_width =
5494 longest_line_width.max(max_visible_line_width) + overscroll.width;
5495
5496 let blocks = cx.with_element_namespace("blocks", |cx| {
5497 self.render_blocks(
5498 start_row..end_row,
5499 &snapshot,
5500 &hitbox,
5501 &text_hitbox,
5502 editor_width,
5503 &mut scroll_width,
5504 &gutter_dimensions,
5505 em_width,
5506 gutter_dimensions.full_width(),
5507 line_height,
5508 &line_layouts,
5509 &local_selections,
5510 is_row_soft_wrapped,
5511 cx,
5512 )
5513 });
5514 let mut blocks = match blocks {
5515 Ok(blocks) => blocks,
5516 Err(resized_blocks) => {
5517 self.editor.update(cx, |editor, cx| {
5518 editor.resize_blocks(resized_blocks, autoscroll_request, cx)
5519 });
5520 return self.prepaint(None, bounds, &mut (), cx);
5521 }
5522 };
5523
5524 let start_buffer_row =
5525 MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
5526 let end_buffer_row =
5527 MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
5528
5529 let scroll_max = point(
5530 ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
5531 max_row.as_f32(),
5532 );
5533
5534 self.editor.update(cx, |editor, cx| {
5535 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
5536
5537 let autoscrolled = if autoscroll_horizontally {
5538 editor.autoscroll_horizontally(
5539 start_row,
5540 text_hitbox.size.width,
5541 scroll_width,
5542 em_width,
5543 &line_layouts,
5544 cx,
5545 )
5546 } else {
5547 false
5548 };
5549
5550 if clamped || autoscrolled {
5551 snapshot = editor.snapshot(cx);
5552 scroll_position = snapshot.scroll_position();
5553 }
5554 });
5555
5556 let scroll_pixel_position = point(
5557 scroll_position.x * em_width,
5558 scroll_position.y * line_height,
5559 );
5560
5561 let indent_guides = self.layout_indent_guides(
5562 content_origin,
5563 text_hitbox.origin,
5564 start_buffer_row..end_buffer_row,
5565 scroll_pixel_position,
5566 line_height,
5567 &snapshot,
5568 cx,
5569 );
5570
5571 let crease_trailers = cx.with_element_namespace("crease_trailers", |cx| {
5572 self.prepaint_crease_trailers(
5573 crease_trailers,
5574 &line_layouts,
5575 line_height,
5576 content_origin,
5577 scroll_pixel_position,
5578 em_width,
5579 cx,
5580 )
5581 });
5582
5583 let mut inline_blame = None;
5584 if let Some(newest_selection_head) = newest_selection_head {
5585 let display_row = newest_selection_head.row();
5586 if (start_row..end_row).contains(&display_row) {
5587 let line_ix = display_row.minus(start_row) as usize;
5588 let line_layout = &line_layouts[line_ix];
5589 let crease_trailer_layout = crease_trailers[line_ix].as_ref();
5590 inline_blame = self.layout_inline_blame(
5591 display_row,
5592 &snapshot.display_snapshot,
5593 line_layout,
5594 crease_trailer_layout,
5595 em_width,
5596 content_origin,
5597 scroll_pixel_position,
5598 line_height,
5599 cx,
5600 );
5601 }
5602 }
5603
5604 let blamed_display_rows = self.layout_blame_entries(
5605 buffer_rows.into_iter(),
5606 em_width,
5607 scroll_position,
5608 line_height,
5609 &gutter_hitbox,
5610 gutter_dimensions.git_blame_entries_width,
5611 cx,
5612 );
5613
5614 let scroll_max = point(
5615 ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
5616 max_scroll_top,
5617 );
5618
5619 self.editor.update(cx, |editor, cx| {
5620 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
5621
5622 let autoscrolled = if autoscroll_horizontally {
5623 editor.autoscroll_horizontally(
5624 start_row,
5625 text_hitbox.size.width,
5626 scroll_width,
5627 em_width,
5628 &line_layouts,
5629 cx,
5630 )
5631 } else {
5632 false
5633 };
5634
5635 if clamped || autoscrolled {
5636 snapshot = editor.snapshot(cx);
5637 scroll_position = snapshot.scroll_position();
5638 }
5639 });
5640
5641 let line_elements = self.prepaint_lines(
5642 start_row,
5643 &mut line_layouts,
5644 line_height,
5645 scroll_pixel_position,
5646 content_origin,
5647 cx,
5648 );
5649
5650 let mut block_start_rows = HashSet::default();
5651 cx.with_element_namespace("blocks", |cx| {
5652 self.layout_blocks(
5653 &mut blocks,
5654 &mut block_start_rows,
5655 &hitbox,
5656 line_height,
5657 scroll_pixel_position,
5658 cx,
5659 );
5660 });
5661
5662 let cursors = self.collect_cursors(&snapshot, cx);
5663 let visible_row_range = start_row..end_row;
5664 let non_visible_cursors = cursors
5665 .iter()
5666 .any(move |c| !visible_row_range.contains(&c.0.row()));
5667
5668 let visible_cursors = self.layout_visible_cursors(
5669 &snapshot,
5670 &selections,
5671 &block_start_rows,
5672 start_row..end_row,
5673 &line_layouts,
5674 &text_hitbox,
5675 content_origin,
5676 scroll_position,
5677 scroll_pixel_position,
5678 line_height,
5679 em_width,
5680 autoscroll_containing_element,
5681 cx,
5682 );
5683
5684 let scrollbar_layout = self.layout_scrollbar(
5685 &snapshot,
5686 bounds,
5687 scroll_position,
5688 height_in_lines,
5689 non_visible_cursors,
5690 cx,
5691 );
5692
5693 let gutter_settings = EditorSettings::get_global(cx).gutter;
5694
5695 let expanded_add_hunks_by_rows = self.editor.update(cx, |editor, _| {
5696 editor
5697 .diff_map
5698 .hunks(false)
5699 .filter(|hunk| hunk.status == DiffHunkStatus::Added)
5700 .map(|expanded_hunk| {
5701 let start_row = expanded_hunk
5702 .hunk_range
5703 .start
5704 .to_display_point(&snapshot)
5705 .row();
5706 (start_row, expanded_hunk.clone())
5707 })
5708 .collect::<HashMap<_, _>>()
5709 });
5710
5711 let rows_with_hunk_bounds = display_hunks
5712 .iter()
5713 .filter_map(|(hunk, hitbox)| Some((hunk, hitbox.as_ref()?.bounds)))
5714 .fold(
5715 HashMap::default(),
5716 |mut rows_with_hunk_bounds, (hunk, bounds)| {
5717 match hunk {
5718 DisplayDiffHunk::Folded { display_row } => {
5719 rows_with_hunk_bounds.insert(*display_row, bounds);
5720 }
5721 DisplayDiffHunk::Unfolded {
5722 display_row_range, ..
5723 } => {
5724 for display_row in display_row_range.iter_rows() {
5725 rows_with_hunk_bounds.insert(display_row, bounds);
5726 }
5727 }
5728 }
5729 rows_with_hunk_bounds
5730 },
5731 );
5732 let mut _context_menu_visible = false;
5733 let mut code_actions_indicator = None;
5734 if let Some(newest_selection_head) = newest_selection_head {
5735 if (start_row..end_row).contains(&newest_selection_head.row()) {
5736 _context_menu_visible = self.layout_context_menu(
5737 line_height,
5738 &hitbox,
5739 &text_hitbox,
5740 content_origin,
5741 start_row,
5742 scroll_pixel_position,
5743 &line_layouts,
5744 newest_selection_head,
5745 gutter_dimensions.width - gutter_dimensions.left_padding,
5746 cx,
5747 );
5748
5749 let show_code_actions = snapshot
5750 .show_code_actions
5751 .unwrap_or(gutter_settings.code_actions);
5752 if show_code_actions {
5753 let newest_selection_point =
5754 newest_selection_head.to_point(&snapshot.display_snapshot);
5755 let newest_selection_display_row =
5756 newest_selection_point.to_display_point(&snapshot).row();
5757 if !expanded_add_hunks_by_rows
5758 .contains_key(&newest_selection_display_row)
5759 {
5760 let buffer = snapshot.buffer_snapshot.buffer_line_for_row(
5761 MultiBufferRow(newest_selection_point.row),
5762 );
5763 if let Some((buffer, range)) = buffer {
5764 let buffer_id = buffer.remote_id();
5765 let row = range.start.row;
5766 let has_test_indicator = self
5767 .editor
5768 .read(cx)
5769 .tasks
5770 .contains_key(&(buffer_id, row));
5771
5772 if !has_test_indicator {
5773 code_actions_indicator = self
5774 .layout_code_actions_indicator(
5775 line_height,
5776 newest_selection_head,
5777 scroll_pixel_position,
5778 &gutter_dimensions,
5779 &gutter_hitbox,
5780 &rows_with_hunk_bounds,
5781 cx,
5782 );
5783 }
5784 }
5785 }
5786 }
5787 }
5788 }
5789
5790 let test_indicators = if gutter_settings.runnables {
5791 self.layout_run_indicators(
5792 line_height,
5793 start_row..end_row,
5794 scroll_pixel_position,
5795 &gutter_dimensions,
5796 &gutter_hitbox,
5797 &rows_with_hunk_bounds,
5798 &snapshot,
5799 cx,
5800 )
5801 } else {
5802 Vec::new()
5803 };
5804
5805 self.layout_signature_help(
5806 &hitbox,
5807 content_origin,
5808 scroll_pixel_position,
5809 newest_selection_head,
5810 start_row,
5811 &line_layouts,
5812 line_height,
5813 em_width,
5814 cx,
5815 );
5816
5817 if !cx.has_active_drag() {
5818 self.layout_hover_popovers(
5819 &snapshot,
5820 &hitbox,
5821 &text_hitbox,
5822 start_row..end_row,
5823 content_origin,
5824 scroll_pixel_position,
5825 &line_layouts,
5826 line_height,
5827 em_width,
5828 cx,
5829 );
5830 }
5831
5832 let inline_completion_popover = self.layout_inline_completion_popover(
5833 &text_hitbox.bounds,
5834 &snapshot,
5835 start_row..end_row,
5836 scroll_position.y,
5837 scroll_position.y + height_in_lines,
5838 &line_layouts,
5839 line_height,
5840 scroll_pixel_position,
5841 editor_width,
5842 &style,
5843 cx,
5844 );
5845
5846 let mouse_context_menu = self.layout_mouse_context_menu(
5847 &snapshot,
5848 start_row..end_row,
5849 content_origin,
5850 cx,
5851 );
5852
5853 cx.with_element_namespace("crease_toggles", |cx| {
5854 self.prepaint_crease_toggles(
5855 &mut crease_toggles,
5856 line_height,
5857 &gutter_dimensions,
5858 gutter_settings,
5859 scroll_pixel_position,
5860 &gutter_hitbox,
5861 cx,
5862 )
5863 });
5864
5865 let invisible_symbol_font_size = font_size / 2.;
5866 let tab_invisible = cx
5867 .text_system()
5868 .shape_line(
5869 "→".into(),
5870 invisible_symbol_font_size,
5871 &[TextRun {
5872 len: "→".len(),
5873 font: self.style.text.font(),
5874 color: cx.theme().colors().editor_invisible,
5875 background_color: None,
5876 underline: None,
5877 strikethrough: None,
5878 }],
5879 )
5880 .unwrap();
5881 let space_invisible = cx
5882 .text_system()
5883 .shape_line(
5884 "•".into(),
5885 invisible_symbol_font_size,
5886 &[TextRun {
5887 len: "•".len(),
5888 font: self.style.text.font(),
5889 color: cx.theme().colors().editor_invisible,
5890 background_color: None,
5891 underline: None,
5892 strikethrough: None,
5893 }],
5894 )
5895 .unwrap();
5896
5897 EditorLayout {
5898 mode: snapshot.mode,
5899 position_map: Rc::new(PositionMap {
5900 size: bounds.size,
5901 scroll_pixel_position,
5902 scroll_max,
5903 line_layouts,
5904 line_height,
5905 em_width,
5906 em_advance,
5907 snapshot,
5908 }),
5909 visible_display_row_range: start_row..end_row,
5910 wrap_guides,
5911 indent_guides,
5912 hitbox,
5913 text_hitbox,
5914 gutter_hitbox,
5915 gutter_dimensions,
5916 display_hunks,
5917 content_origin,
5918 scrollbar_layout,
5919 active_rows,
5920 highlighted_rows,
5921 highlighted_ranges,
5922 highlighted_gutter_ranges,
5923 redacted_ranges,
5924 line_elements,
5925 line_numbers,
5926 blamed_display_rows,
5927 inline_blame,
5928 blocks,
5929 cursors,
5930 visible_cursors,
5931 selections,
5932 inline_completion_popover,
5933 mouse_context_menu,
5934 test_indicators,
5935 code_actions_indicator,
5936 crease_toggles,
5937 crease_trailers,
5938 tab_invisible,
5939 space_invisible,
5940 }
5941 })
5942 })
5943 })
5944 }
5945
5946 fn paint(
5947 &mut self,
5948 _: Option<&GlobalElementId>,
5949 bounds: Bounds<gpui::Pixels>,
5950 _: &mut Self::RequestLayoutState,
5951 layout: &mut Self::PrepaintState,
5952 cx: &mut WindowContext,
5953 ) {
5954 let focus_handle = self.editor.focus_handle(cx);
5955 let key_context = self.editor.update(cx, |editor, cx| editor.key_context(cx));
5956 cx.set_key_context(key_context);
5957 cx.handle_input(
5958 &focus_handle,
5959 ElementInputHandler::new(bounds, self.editor.clone()),
5960 );
5961 self.register_actions(cx);
5962 self.register_key_listeners(cx, layout);
5963
5964 let text_style = TextStyleRefinement {
5965 font_size: Some(self.style.text.font_size),
5966 line_height: Some(self.style.text.line_height),
5967 ..Default::default()
5968 };
5969 let hovered_hunk = layout
5970 .display_hunks
5971 .iter()
5972 .find_map(|(hunk, hunk_hitbox)| match hunk {
5973 DisplayDiffHunk::Folded { .. } => None,
5974 DisplayDiffHunk::Unfolded {
5975 diff_base_byte_range,
5976 multi_buffer_range,
5977 status,
5978 ..
5979 } => {
5980 if hunk_hitbox
5981 .as_ref()
5982 .map(|hitbox| hitbox.is_hovered(cx))
5983 .unwrap_or(false)
5984 {
5985 Some(HoveredHunk {
5986 status: *status,
5987 multi_buffer_range: multi_buffer_range.clone(),
5988 diff_base_byte_range: diff_base_byte_range.clone(),
5989 })
5990 } else {
5991 None
5992 }
5993 }
5994 });
5995 let rem_size = self.rem_size(cx);
5996 cx.with_rem_size(rem_size, |cx| {
5997 cx.with_text_style(Some(text_style), |cx| {
5998 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
5999 self.paint_mouse_listeners(layout, hovered_hunk, cx);
6000 self.paint_background(layout, cx);
6001 self.paint_indent_guides(layout, cx);
6002
6003 if layout.gutter_hitbox.size.width > Pixels::ZERO {
6004 self.paint_blamed_display_rows(layout, cx);
6005 self.paint_line_numbers(layout, cx);
6006 }
6007
6008 self.paint_text(layout, cx);
6009
6010 if layout.gutter_hitbox.size.width > Pixels::ZERO {
6011 self.paint_gutter_highlights(layout, cx);
6012 self.paint_gutter_indicators(layout, cx);
6013 }
6014
6015 if !layout.blocks.is_empty() {
6016 cx.with_element_namespace("blocks", |cx| {
6017 self.paint_blocks(layout, cx);
6018 });
6019 }
6020
6021 self.paint_scrollbar(layout, cx);
6022 self.paint_inline_completion_popover(layout, cx);
6023 self.paint_mouse_context_menu(layout, cx);
6024 });
6025 })
6026 })
6027 }
6028}
6029
6030pub(super) fn gutter_bounds(
6031 editor_bounds: Bounds<Pixels>,
6032 gutter_dimensions: GutterDimensions,
6033) -> Bounds<Pixels> {
6034 Bounds {
6035 origin: editor_bounds.origin,
6036 size: size(gutter_dimensions.width, editor_bounds.size.height),
6037 }
6038}
6039
6040impl IntoElement for EditorElement {
6041 type Element = Self;
6042
6043 fn into_element(self) -> Self::Element {
6044 self
6045 }
6046}
6047
6048pub struct EditorLayout {
6049 position_map: Rc<PositionMap>,
6050 hitbox: Hitbox,
6051 text_hitbox: Hitbox,
6052 gutter_hitbox: Hitbox,
6053 gutter_dimensions: GutterDimensions,
6054 content_origin: gpui::Point<Pixels>,
6055 scrollbar_layout: Option<ScrollbarLayout>,
6056 mode: EditorMode,
6057 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
6058 indent_guides: Option<Vec<IndentGuideLayout>>,
6059 visible_display_row_range: Range<DisplayRow>,
6060 active_rows: BTreeMap<DisplayRow, bool>,
6061 highlighted_rows: BTreeMap<DisplayRow, Hsla>,
6062 line_elements: SmallVec<[AnyElement; 1]>,
6063 line_numbers: Vec<Option<ShapedLine>>,
6064 display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
6065 blamed_display_rows: Option<Vec<AnyElement>>,
6066 inline_blame: Option<AnyElement>,
6067 blocks: Vec<BlockLayout>,
6068 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
6069 highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
6070 redacted_ranges: Vec<Range<DisplayPoint>>,
6071 cursors: Vec<(DisplayPoint, Hsla)>,
6072 visible_cursors: Vec<CursorLayout>,
6073 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
6074 code_actions_indicator: Option<AnyElement>,
6075 test_indicators: Vec<AnyElement>,
6076 crease_toggles: Vec<Option<AnyElement>>,
6077 crease_trailers: Vec<Option<CreaseTrailerLayout>>,
6078 inline_completion_popover: Option<AnyElement>,
6079 mouse_context_menu: Option<AnyElement>,
6080 tab_invisible: ShapedLine,
6081 space_invisible: ShapedLine,
6082}
6083
6084impl EditorLayout {
6085 fn line_end_overshoot(&self) -> Pixels {
6086 0.15 * self.position_map.line_height
6087 }
6088}
6089
6090struct ColoredRange<T> {
6091 start: T,
6092 end: T,
6093 color: Hsla,
6094}
6095
6096#[derive(Clone)]
6097struct ScrollbarLayout {
6098 hitbox: Hitbox,
6099 visible_row_range: Range<f32>,
6100 visible: bool,
6101 row_height: Pixels,
6102 thumb_height: Pixels,
6103}
6104
6105impl ScrollbarLayout {
6106 const BORDER_WIDTH: Pixels = px(1.0);
6107 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
6108 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
6109 const MIN_THUMB_HEIGHT: Pixels = px(20.0);
6110
6111 fn thumb_bounds(&self) -> Bounds<Pixels> {
6112 let thumb_top = self.y_for_row(self.visible_row_range.start);
6113 let thumb_bottom = thumb_top + self.thumb_height;
6114 Bounds::from_corners(
6115 point(self.hitbox.left(), thumb_top),
6116 point(self.hitbox.right(), thumb_bottom),
6117 )
6118 }
6119
6120 fn y_for_row(&self, row: f32) -> Pixels {
6121 self.hitbox.top() + row * self.row_height
6122 }
6123
6124 fn marker_quads_for_ranges(
6125 &self,
6126 row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
6127 column: Option<usize>,
6128 ) -> Vec<PaintQuad> {
6129 struct MinMax {
6130 min: Pixels,
6131 max: Pixels,
6132 }
6133 let (x_range, height_limit) = if let Some(column) = column {
6134 let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
6135 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
6136 let end = start + column_width;
6137 (
6138 Range { start, end },
6139 MinMax {
6140 min: Self::MIN_MARKER_HEIGHT,
6141 max: px(f32::MAX),
6142 },
6143 )
6144 } else {
6145 (
6146 Range {
6147 start: Self::BORDER_WIDTH,
6148 end: self.hitbox.size.width,
6149 },
6150 MinMax {
6151 min: Self::LINE_MARKER_HEIGHT,
6152 max: Self::LINE_MARKER_HEIGHT,
6153 },
6154 )
6155 };
6156
6157 let row_to_y = |row: DisplayRow| row.as_f32() * self.row_height;
6158 let mut pixel_ranges = row_ranges
6159 .into_iter()
6160 .map(|range| {
6161 let start_y = row_to_y(range.start);
6162 let end_y = row_to_y(range.end)
6163 + self.row_height.max(height_limit.min).min(height_limit.max);
6164 ColoredRange {
6165 start: start_y,
6166 end: end_y,
6167 color: range.color,
6168 }
6169 })
6170 .peekable();
6171
6172 let mut quads = Vec::new();
6173 while let Some(mut pixel_range) = pixel_ranges.next() {
6174 while let Some(next_pixel_range) = pixel_ranges.peek() {
6175 if pixel_range.end >= next_pixel_range.start - px(1.0)
6176 && pixel_range.color == next_pixel_range.color
6177 {
6178 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
6179 pixel_ranges.next();
6180 } else {
6181 break;
6182 }
6183 }
6184
6185 let bounds = Bounds::from_corners(
6186 point(x_range.start, pixel_range.start),
6187 point(x_range.end, pixel_range.end),
6188 );
6189 quads.push(quad(
6190 bounds,
6191 Corners::default(),
6192 pixel_range.color,
6193 Edges::default(),
6194 Hsla::transparent_black(),
6195 ));
6196 }
6197
6198 quads
6199 }
6200}
6201
6202struct CreaseTrailerLayout {
6203 element: AnyElement,
6204 bounds: Bounds<Pixels>,
6205}
6206
6207struct PositionMap {
6208 size: Size<Pixels>,
6209 line_height: Pixels,
6210 scroll_pixel_position: gpui::Point<Pixels>,
6211 scroll_max: gpui::Point<f32>,
6212 em_width: Pixels,
6213 em_advance: Pixels,
6214 line_layouts: Vec<LineWithInvisibles>,
6215 snapshot: EditorSnapshot,
6216}
6217
6218#[derive(Debug, Copy, Clone)]
6219pub struct PointForPosition {
6220 pub previous_valid: DisplayPoint,
6221 pub next_valid: DisplayPoint,
6222 pub exact_unclipped: DisplayPoint,
6223 pub column_overshoot_after_line_end: u32,
6224}
6225
6226impl PointForPosition {
6227 pub fn as_valid(&self) -> Option<DisplayPoint> {
6228 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
6229 Some(self.previous_valid)
6230 } else {
6231 None
6232 }
6233 }
6234}
6235
6236impl PositionMap {
6237 fn point_for_position(
6238 &self,
6239 text_bounds: Bounds<Pixels>,
6240 position: gpui::Point<Pixels>,
6241 ) -> PointForPosition {
6242 let scroll_position = self.snapshot.scroll_position();
6243 let position = position - text_bounds.origin;
6244 let y = position.y.max(px(0.)).min(self.size.height);
6245 let x = position.x + (scroll_position.x * self.em_width);
6246 let row = ((y / self.line_height) + scroll_position.y) as u32;
6247
6248 let (column, x_overshoot_after_line_end) = if let Some(line) = self
6249 .line_layouts
6250 .get(row as usize - scroll_position.y as usize)
6251 {
6252 if let Some(ix) = line.index_for_x(x) {
6253 (ix as u32, px(0.))
6254 } else {
6255 (line.len as u32, px(0.).max(x - line.width))
6256 }
6257 } else {
6258 (0, x)
6259 };
6260
6261 let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
6262 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
6263 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
6264
6265 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
6266 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
6267 PointForPosition {
6268 previous_valid,
6269 next_valid,
6270 exact_unclipped,
6271 column_overshoot_after_line_end,
6272 }
6273 }
6274}
6275
6276struct BlockLayout {
6277 id: BlockId,
6278 row: Option<DisplayRow>,
6279 element: AnyElement,
6280 available_space: Size<AvailableSpace>,
6281 style: BlockStyle,
6282}
6283
6284fn layout_line(
6285 row: DisplayRow,
6286 snapshot: &EditorSnapshot,
6287 style: &EditorStyle,
6288 text_width: Pixels,
6289 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
6290 cx: &mut WindowContext,
6291) -> LineWithInvisibles {
6292 let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
6293 LineWithInvisibles::from_chunks(
6294 chunks,
6295 &style,
6296 MAX_LINE_LEN,
6297 1,
6298 snapshot.mode,
6299 text_width,
6300 is_row_soft_wrapped,
6301 cx,
6302 )
6303 .pop()
6304 .unwrap()
6305}
6306
6307#[derive(Debug)]
6308pub struct IndentGuideLayout {
6309 origin: gpui::Point<Pixels>,
6310 length: Pixels,
6311 single_indent_width: Pixels,
6312 depth: u32,
6313 active: bool,
6314 settings: IndentGuideSettings,
6315}
6316
6317pub struct CursorLayout {
6318 origin: gpui::Point<Pixels>,
6319 block_width: Pixels,
6320 line_height: Pixels,
6321 color: Hsla,
6322 shape: CursorShape,
6323 block_text: Option<ShapedLine>,
6324 cursor_name: Option<AnyElement>,
6325}
6326
6327#[derive(Debug)]
6328pub struct CursorName {
6329 string: SharedString,
6330 color: Hsla,
6331 is_top_row: bool,
6332}
6333
6334impl CursorLayout {
6335 pub fn new(
6336 origin: gpui::Point<Pixels>,
6337 block_width: Pixels,
6338 line_height: Pixels,
6339 color: Hsla,
6340 shape: CursorShape,
6341 block_text: Option<ShapedLine>,
6342 ) -> CursorLayout {
6343 CursorLayout {
6344 origin,
6345 block_width,
6346 line_height,
6347 color,
6348 shape,
6349 block_text,
6350 cursor_name: None,
6351 }
6352 }
6353
6354 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
6355 Bounds {
6356 origin: self.origin + origin,
6357 size: size(self.block_width, self.line_height),
6358 }
6359 }
6360
6361 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
6362 match self.shape {
6363 CursorShape::Bar => Bounds {
6364 origin: self.origin + origin,
6365 size: size(px(2.0), self.line_height),
6366 },
6367 CursorShape::Block | CursorShape::Hollow => Bounds {
6368 origin: self.origin + origin,
6369 size: size(self.block_width, self.line_height),
6370 },
6371 CursorShape::Underline => Bounds {
6372 origin: self.origin
6373 + origin
6374 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
6375 size: size(self.block_width, px(2.0)),
6376 },
6377 }
6378 }
6379
6380 pub fn layout(
6381 &mut self,
6382 origin: gpui::Point<Pixels>,
6383 cursor_name: Option<CursorName>,
6384 cx: &mut WindowContext,
6385 ) {
6386 if let Some(cursor_name) = cursor_name {
6387 let bounds = self.bounds(origin);
6388 let text_size = self.line_height / 1.5;
6389
6390 let name_origin = if cursor_name.is_top_row {
6391 point(bounds.right() - px(1.), bounds.top())
6392 } else {
6393 point(bounds.left(), bounds.top() - text_size / 2. - px(1.))
6394 };
6395 let mut name_element = div()
6396 .bg(self.color)
6397 .text_size(text_size)
6398 .px_0p5()
6399 .line_height(text_size + px(2.))
6400 .text_color(cursor_name.color)
6401 .child(cursor_name.string.clone())
6402 .into_any_element();
6403
6404 name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), cx);
6405
6406 self.cursor_name = Some(name_element);
6407 }
6408 }
6409
6410 pub fn paint(&mut self, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
6411 let bounds = self.bounds(origin);
6412
6413 //Draw background or border quad
6414 let cursor = if matches!(self.shape, CursorShape::Hollow) {
6415 outline(bounds, self.color)
6416 } else {
6417 fill(bounds, self.color)
6418 };
6419
6420 if let Some(name) = &mut self.cursor_name {
6421 name.paint(cx);
6422 }
6423
6424 cx.paint_quad(cursor);
6425
6426 if let Some(block_text) = &self.block_text {
6427 block_text
6428 .paint(self.origin + origin, self.line_height, cx)
6429 .log_err();
6430 }
6431 }
6432
6433 pub fn shape(&self) -> CursorShape {
6434 self.shape
6435 }
6436}
6437
6438#[derive(Debug)]
6439pub struct HighlightedRange {
6440 pub start_y: Pixels,
6441 pub line_height: Pixels,
6442 pub lines: Vec<HighlightedRangeLine>,
6443 pub color: Hsla,
6444 pub corner_radius: Pixels,
6445}
6446
6447#[derive(Debug)]
6448pub struct HighlightedRangeLine {
6449 pub start_x: Pixels,
6450 pub end_x: Pixels,
6451}
6452
6453impl HighlightedRange {
6454 pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut WindowContext) {
6455 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
6456 self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
6457 self.paint_lines(
6458 self.start_y + self.line_height,
6459 &self.lines[1..],
6460 bounds,
6461 cx,
6462 );
6463 } else {
6464 self.paint_lines(self.start_y, &self.lines, bounds, cx);
6465 }
6466 }
6467
6468 fn paint_lines(
6469 &self,
6470 start_y: Pixels,
6471 lines: &[HighlightedRangeLine],
6472 _bounds: Bounds<Pixels>,
6473 cx: &mut WindowContext,
6474 ) {
6475 if lines.is_empty() {
6476 return;
6477 }
6478
6479 let first_line = lines.first().unwrap();
6480 let last_line = lines.last().unwrap();
6481
6482 let first_top_left = point(first_line.start_x, start_y);
6483 let first_top_right = point(first_line.end_x, start_y);
6484
6485 let curve_height = point(Pixels::ZERO, self.corner_radius);
6486 let curve_width = |start_x: Pixels, end_x: Pixels| {
6487 let max = (end_x - start_x) / 2.;
6488 let width = if max < self.corner_radius {
6489 max
6490 } else {
6491 self.corner_radius
6492 };
6493
6494 point(width, Pixels::ZERO)
6495 };
6496
6497 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
6498 let mut path = gpui::Path::new(first_top_right - top_curve_width);
6499 path.curve_to(first_top_right + curve_height, first_top_right);
6500
6501 let mut iter = lines.iter().enumerate().peekable();
6502 while let Some((ix, line)) = iter.next() {
6503 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
6504
6505 if let Some((_, next_line)) = iter.peek() {
6506 let next_top_right = point(next_line.end_x, bottom_right.y);
6507
6508 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
6509 Ordering::Equal => {
6510 path.line_to(bottom_right);
6511 }
6512 Ordering::Less => {
6513 let curve_width = curve_width(next_top_right.x, bottom_right.x);
6514 path.line_to(bottom_right - curve_height);
6515 if self.corner_radius > Pixels::ZERO {
6516 path.curve_to(bottom_right - curve_width, bottom_right);
6517 }
6518 path.line_to(next_top_right + curve_width);
6519 if self.corner_radius > Pixels::ZERO {
6520 path.curve_to(next_top_right + curve_height, next_top_right);
6521 }
6522 }
6523 Ordering::Greater => {
6524 let curve_width = curve_width(bottom_right.x, next_top_right.x);
6525 path.line_to(bottom_right - curve_height);
6526 if self.corner_radius > Pixels::ZERO {
6527 path.curve_to(bottom_right + curve_width, bottom_right);
6528 }
6529 path.line_to(next_top_right - curve_width);
6530 if self.corner_radius > Pixels::ZERO {
6531 path.curve_to(next_top_right + curve_height, next_top_right);
6532 }
6533 }
6534 }
6535 } else {
6536 let curve_width = curve_width(line.start_x, line.end_x);
6537 path.line_to(bottom_right - curve_height);
6538 if self.corner_radius > Pixels::ZERO {
6539 path.curve_to(bottom_right - curve_width, bottom_right);
6540 }
6541
6542 let bottom_left = point(line.start_x, bottom_right.y);
6543 path.line_to(bottom_left + curve_width);
6544 if self.corner_radius > Pixels::ZERO {
6545 path.curve_to(bottom_left - curve_height, bottom_left);
6546 }
6547 }
6548 }
6549
6550 if first_line.start_x > last_line.start_x {
6551 let curve_width = curve_width(last_line.start_x, first_line.start_x);
6552 let second_top_left = point(last_line.start_x, start_y + self.line_height);
6553 path.line_to(second_top_left + curve_height);
6554 if self.corner_radius > Pixels::ZERO {
6555 path.curve_to(second_top_left + curve_width, second_top_left);
6556 }
6557 let first_bottom_left = point(first_line.start_x, second_top_left.y);
6558 path.line_to(first_bottom_left - curve_width);
6559 if self.corner_radius > Pixels::ZERO {
6560 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
6561 }
6562 }
6563
6564 path.line_to(first_top_left + curve_height);
6565 if self.corner_radius > Pixels::ZERO {
6566 path.curve_to(first_top_left + top_curve_width, first_top_left);
6567 }
6568 path.line_to(first_top_right - top_curve_width);
6569
6570 cx.paint_path(path, self.color);
6571 }
6572}
6573
6574pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
6575 (delta.pow(1.5) / 100.0).into()
6576}
6577
6578fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
6579 (delta.pow(1.2) / 300.0).into()
6580}
6581
6582pub fn register_action<T: Action>(
6583 view: &View<Editor>,
6584 cx: &mut WindowContext,
6585 listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
6586) {
6587 let view = view.clone();
6588 cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
6589 let action = action.downcast_ref().unwrap();
6590 if phase == DispatchPhase::Bubble {
6591 view.update(cx, |editor, cx| {
6592 listener(editor, action, cx);
6593 })
6594 }
6595 })
6596}
6597
6598fn compute_auto_height_layout(
6599 editor: &mut Editor,
6600 max_lines: usize,
6601 max_line_number_width: Pixels,
6602 known_dimensions: Size<Option<Pixels>>,
6603 available_width: AvailableSpace,
6604 cx: &mut ViewContext<Editor>,
6605) -> Option<Size<Pixels>> {
6606 let width = known_dimensions.width.or({
6607 if let AvailableSpace::Definite(available_width) = available_width {
6608 Some(available_width)
6609 } else {
6610 None
6611 }
6612 })?;
6613 if let Some(height) = known_dimensions.height {
6614 return Some(size(width, height));
6615 }
6616
6617 let style = editor.style.as_ref().unwrap();
6618 let font_id = cx.text_system().resolve_font(&style.text.font());
6619 let font_size = style.text.font_size.to_pixels(cx.rem_size());
6620 let line_height = style.text.line_height_in_pixels(cx.rem_size());
6621 let em_width = cx
6622 .text_system()
6623 .typographic_bounds(font_id, font_size, 'm')
6624 .unwrap()
6625 .size
6626 .width;
6627 let em_advance = cx
6628 .text_system()
6629 .advance(font_id, font_size, 'm')
6630 .unwrap()
6631 .width;
6632
6633 let mut snapshot = editor.snapshot(cx);
6634 let gutter_dimensions = snapshot.gutter_dimensions(
6635 font_id,
6636 font_size,
6637 em_width,
6638 em_advance,
6639 max_line_number_width,
6640 cx,
6641 );
6642
6643 editor.gutter_dimensions = gutter_dimensions;
6644 let text_width = width - gutter_dimensions.width;
6645 let overscroll = size(em_width, px(0.));
6646
6647 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
6648 if editor.set_wrap_width(Some(editor_width), cx) {
6649 snapshot = editor.snapshot(cx);
6650 }
6651
6652 let scroll_height = Pixels::from(snapshot.max_point().row().next_row().0) * line_height;
6653 let height = scroll_height
6654 .max(line_height)
6655 .min(line_height * max_lines as f32);
6656
6657 Some(size(width, height))
6658}
6659
6660#[cfg(test)]
6661mod tests {
6662 use super::*;
6663 use crate::{
6664 display_map::{BlockPlacement, BlockProperties},
6665 editor_tests::{init_test, update_test_language_settings},
6666 Editor, MultiBuffer,
6667 };
6668 use gpui::{TestAppContext, VisualTestContext};
6669 use language::language_settings;
6670 use log::info;
6671 use std::num::NonZeroU32;
6672 use util::test::sample_text;
6673
6674 #[gpui::test]
6675 fn test_shape_line_numbers(cx: &mut TestAppContext) {
6676 init_test(cx, |_| {});
6677 let window = cx.add_window(|cx| {
6678 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
6679 Editor::new(EditorMode::Full, buffer, None, true, cx)
6680 });
6681
6682 let editor = window.root(cx).unwrap();
6683 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6684 let element = EditorElement::new(&editor, style);
6685 let snapshot = window.update(cx, |editor, cx| editor.snapshot(cx)).unwrap();
6686
6687 let layouts = cx
6688 .update_window(*window, |_, cx| {
6689 element.layout_line_numbers(
6690 DisplayRow(0)..DisplayRow(6),
6691 (0..6).map(MultiBufferRow).map(Some),
6692 &Default::default(),
6693 Some(DisplayPoint::new(DisplayRow(0), 0)),
6694 &snapshot,
6695 cx,
6696 )
6697 })
6698 .unwrap();
6699 assert_eq!(layouts.len(), 6);
6700
6701 let relative_rows = window
6702 .update(cx, |editor, cx| {
6703 let snapshot = editor.snapshot(cx);
6704 element.calculate_relative_line_numbers(
6705 &snapshot,
6706 &(DisplayRow(0)..DisplayRow(6)),
6707 Some(DisplayRow(3)),
6708 )
6709 })
6710 .unwrap();
6711 assert_eq!(relative_rows[&DisplayRow(0)], 3);
6712 assert_eq!(relative_rows[&DisplayRow(1)], 2);
6713 assert_eq!(relative_rows[&DisplayRow(2)], 1);
6714 // current line has no relative number
6715 assert_eq!(relative_rows[&DisplayRow(4)], 1);
6716 assert_eq!(relative_rows[&DisplayRow(5)], 2);
6717
6718 // works if cursor is before screen
6719 let relative_rows = window
6720 .update(cx, |editor, cx| {
6721 let snapshot = editor.snapshot(cx);
6722 element.calculate_relative_line_numbers(
6723 &snapshot,
6724 &(DisplayRow(3)..DisplayRow(6)),
6725 Some(DisplayRow(1)),
6726 )
6727 })
6728 .unwrap();
6729 assert_eq!(relative_rows.len(), 3);
6730 assert_eq!(relative_rows[&DisplayRow(3)], 2);
6731 assert_eq!(relative_rows[&DisplayRow(4)], 3);
6732 assert_eq!(relative_rows[&DisplayRow(5)], 4);
6733
6734 // works if cursor is after screen
6735 let relative_rows = window
6736 .update(cx, |editor, cx| {
6737 let snapshot = editor.snapshot(cx);
6738 element.calculate_relative_line_numbers(
6739 &snapshot,
6740 &(DisplayRow(0)..DisplayRow(3)),
6741 Some(DisplayRow(6)),
6742 )
6743 })
6744 .unwrap();
6745 assert_eq!(relative_rows.len(), 3);
6746 assert_eq!(relative_rows[&DisplayRow(0)], 5);
6747 assert_eq!(relative_rows[&DisplayRow(1)], 4);
6748 assert_eq!(relative_rows[&DisplayRow(2)], 3);
6749 }
6750
6751 #[gpui::test]
6752 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
6753 init_test(cx, |_| {});
6754
6755 let window = cx.add_window(|cx| {
6756 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
6757 Editor::new(EditorMode::Full, buffer, None, true, cx)
6758 });
6759 let cx = &mut VisualTestContext::from_window(*window, cx);
6760 let editor = window.root(cx).unwrap();
6761 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6762
6763 window
6764 .update(cx, |editor, cx| {
6765 editor.cursor_shape = CursorShape::Block;
6766 editor.change_selections(None, cx, |s| {
6767 s.select_ranges([
6768 Point::new(0, 0)..Point::new(1, 0),
6769 Point::new(3, 2)..Point::new(3, 3),
6770 Point::new(5, 6)..Point::new(6, 0),
6771 ]);
6772 });
6773 })
6774 .unwrap();
6775
6776 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6777 EditorElement::new(&editor, style)
6778 });
6779
6780 assert_eq!(state.selections.len(), 1);
6781 let local_selections = &state.selections[0].1;
6782 assert_eq!(local_selections.len(), 3);
6783 // moves cursor back one line
6784 assert_eq!(
6785 local_selections[0].head,
6786 DisplayPoint::new(DisplayRow(0), 6)
6787 );
6788 assert_eq!(
6789 local_selections[0].range,
6790 DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
6791 );
6792
6793 // moves cursor back one column
6794 assert_eq!(
6795 local_selections[1].range,
6796 DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
6797 );
6798 assert_eq!(
6799 local_selections[1].head,
6800 DisplayPoint::new(DisplayRow(3), 2)
6801 );
6802
6803 // leaves cursor on the max point
6804 assert_eq!(
6805 local_selections[2].range,
6806 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
6807 );
6808 assert_eq!(
6809 local_selections[2].head,
6810 DisplayPoint::new(DisplayRow(6), 0)
6811 );
6812
6813 // active lines does not include 1 (even though the range of the selection does)
6814 assert_eq!(
6815 state.active_rows.keys().cloned().collect::<Vec<_>>(),
6816 vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
6817 );
6818
6819 // multi-buffer support
6820 // in DisplayPoint coordinates, this is what we're dealing with:
6821 // 0: [[file
6822 // 1: header
6823 // 2: section]]
6824 // 3: aaaaaa
6825 // 4: bbbbbb
6826 // 5: cccccc
6827 // 6:
6828 // 7: [[footer]]
6829 // 8: [[header]]
6830 // 9: ffffff
6831 // 10: gggggg
6832 // 11: hhhhhh
6833 // 12:
6834 // 13: [[footer]]
6835 // 14: [[file
6836 // 15: header
6837 // 16: section]]
6838 // 17: bbbbbb
6839 // 18: cccccc
6840 // 19: dddddd
6841 // 20: [[footer]]
6842 let window = cx.add_window(|cx| {
6843 let buffer = MultiBuffer::build_multi(
6844 [
6845 (
6846 &(sample_text(8, 6, 'a') + "\n"),
6847 vec![
6848 Point::new(0, 0)..Point::new(3, 0),
6849 Point::new(4, 0)..Point::new(7, 0),
6850 ],
6851 ),
6852 (
6853 &(sample_text(8, 6, 'a') + "\n"),
6854 vec![Point::new(1, 0)..Point::new(3, 0)],
6855 ),
6856 ],
6857 cx,
6858 );
6859 Editor::new(EditorMode::Full, buffer, None, true, cx)
6860 });
6861 let editor = window.root(cx).unwrap();
6862 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6863 let _state = window.update(cx, |editor, cx| {
6864 editor.cursor_shape = CursorShape::Block;
6865 editor.change_selections(None, cx, |s| {
6866 s.select_display_ranges([
6867 DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0),
6868 DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0),
6869 ]);
6870 });
6871 });
6872
6873 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6874 EditorElement::new(&editor, style)
6875 });
6876 assert_eq!(state.selections.len(), 1);
6877 let local_selections = &state.selections[0].1;
6878 assert_eq!(local_selections.len(), 2);
6879
6880 // moves cursor on excerpt boundary back a line
6881 // and doesn't allow selection to bleed through
6882 assert_eq!(
6883 local_selections[0].range,
6884 DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0)
6885 );
6886 assert_eq!(
6887 local_selections[0].head,
6888 DisplayPoint::new(DisplayRow(6), 0)
6889 );
6890 // moves cursor on buffer boundary back two lines
6891 // and doesn't allow selection to bleed through
6892 assert_eq!(
6893 local_selections[1].range,
6894 DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0)
6895 );
6896 assert_eq!(
6897 local_selections[1].head,
6898 DisplayPoint::new(DisplayRow(12), 0)
6899 );
6900 }
6901
6902 #[gpui::test]
6903 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
6904 init_test(cx, |_| {});
6905
6906 let window = cx.add_window(|cx| {
6907 let buffer = MultiBuffer::build_simple("", cx);
6908 Editor::new(EditorMode::Full, buffer, None, true, cx)
6909 });
6910 let cx = &mut VisualTestContext::from_window(*window, cx);
6911 let editor = window.root(cx).unwrap();
6912 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6913 window
6914 .update(cx, |editor, cx| {
6915 editor.set_placeholder_text("hello", cx);
6916 editor.insert_blocks(
6917 [BlockProperties {
6918 style: BlockStyle::Fixed,
6919 placement: BlockPlacement::Above(Anchor::min()),
6920 height: 3,
6921 render: Arc::new(|cx| div().h(3. * cx.line_height()).into_any()),
6922 priority: 0,
6923 }],
6924 None,
6925 cx,
6926 );
6927
6928 // Blur the editor so that it displays placeholder text.
6929 cx.blur();
6930 })
6931 .unwrap();
6932
6933 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6934 EditorElement::new(&editor, style)
6935 });
6936 assert_eq!(state.position_map.line_layouts.len(), 4);
6937 assert_eq!(
6938 state
6939 .line_numbers
6940 .iter()
6941 .map(Option::is_some)
6942 .collect::<Vec<_>>(),
6943 &[false, false, false, true]
6944 );
6945 }
6946
6947 #[gpui::test]
6948 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
6949 const TAB_SIZE: u32 = 4;
6950
6951 let input_text = "\t \t|\t| a b";
6952 let expected_invisibles = vec![
6953 Invisible::Tab {
6954 line_start_offset: 0,
6955 line_end_offset: TAB_SIZE as usize,
6956 },
6957 Invisible::Whitespace {
6958 line_offset: TAB_SIZE as usize,
6959 },
6960 Invisible::Tab {
6961 line_start_offset: TAB_SIZE as usize + 1,
6962 line_end_offset: TAB_SIZE as usize * 2,
6963 },
6964 Invisible::Tab {
6965 line_start_offset: TAB_SIZE as usize * 2 + 1,
6966 line_end_offset: TAB_SIZE as usize * 3,
6967 },
6968 Invisible::Whitespace {
6969 line_offset: TAB_SIZE as usize * 3 + 1,
6970 },
6971 Invisible::Whitespace {
6972 line_offset: TAB_SIZE as usize * 3 + 3,
6973 },
6974 ];
6975 assert_eq!(
6976 expected_invisibles.len(),
6977 input_text
6978 .chars()
6979 .filter(|initial_char| initial_char.is_whitespace())
6980 .count(),
6981 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
6982 );
6983
6984 for show_line_numbers in [true, false] {
6985 init_test(cx, |s| {
6986 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6987 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
6988 });
6989
6990 let actual_invisibles = collect_invisibles_from_new_editor(
6991 cx,
6992 EditorMode::Full,
6993 input_text,
6994 px(500.0),
6995 show_line_numbers,
6996 );
6997
6998 assert_eq!(expected_invisibles, actual_invisibles);
6999 }
7000 }
7001
7002 #[gpui::test]
7003 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
7004 init_test(cx, |s| {
7005 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
7006 s.defaults.tab_size = NonZeroU32::new(4);
7007 });
7008
7009 for editor_mode_without_invisibles in [
7010 EditorMode::SingleLine { auto_width: false },
7011 EditorMode::AutoHeight { max_lines: 100 },
7012 ] {
7013 for show_line_numbers in [true, false] {
7014 let invisibles = collect_invisibles_from_new_editor(
7015 cx,
7016 editor_mode_without_invisibles,
7017 "\t\t\t| | a b",
7018 px(500.0),
7019 show_line_numbers,
7020 );
7021 assert!(invisibles.is_empty(),
7022 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
7023 }
7024 }
7025 }
7026
7027 #[gpui::test]
7028 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
7029 let tab_size = 4;
7030 let input_text = "a\tbcd ".repeat(9);
7031 let repeated_invisibles = [
7032 Invisible::Tab {
7033 line_start_offset: 1,
7034 line_end_offset: tab_size as usize,
7035 },
7036 Invisible::Whitespace {
7037 line_offset: tab_size as usize + 3,
7038 },
7039 Invisible::Whitespace {
7040 line_offset: tab_size as usize + 4,
7041 },
7042 Invisible::Whitespace {
7043 line_offset: tab_size as usize + 5,
7044 },
7045 Invisible::Whitespace {
7046 line_offset: tab_size as usize + 6,
7047 },
7048 Invisible::Whitespace {
7049 line_offset: tab_size as usize + 7,
7050 },
7051 ];
7052 let expected_invisibles = std::iter::once(repeated_invisibles)
7053 .cycle()
7054 .take(9)
7055 .flatten()
7056 .collect::<Vec<_>>();
7057 assert_eq!(
7058 expected_invisibles.len(),
7059 input_text
7060 .chars()
7061 .filter(|initial_char| initial_char.is_whitespace())
7062 .count(),
7063 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
7064 );
7065 info!("Expected invisibles: {expected_invisibles:?}");
7066
7067 init_test(cx, |_| {});
7068
7069 // Put the same string with repeating whitespace pattern into editors of various size,
7070 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
7071 let resize_step = 10.0;
7072 let mut editor_width = 200.0;
7073 while editor_width <= 1000.0 {
7074 for show_line_numbers in [true, false] {
7075 update_test_language_settings(cx, |s| {
7076 s.defaults.tab_size = NonZeroU32::new(tab_size);
7077 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
7078 s.defaults.preferred_line_length = Some(editor_width as u32);
7079 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
7080 });
7081
7082 let actual_invisibles = collect_invisibles_from_new_editor(
7083 cx,
7084 EditorMode::Full,
7085 &input_text,
7086 px(editor_width),
7087 show_line_numbers,
7088 );
7089
7090 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
7091 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
7092 let mut i = 0;
7093 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
7094 i = actual_index;
7095 match expected_invisibles.get(i) {
7096 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
7097 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
7098 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
7099 _ => {
7100 panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
7101 }
7102 },
7103 None => {
7104 panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
7105 }
7106 }
7107 }
7108 let missing_expected_invisibles = &expected_invisibles[i + 1..];
7109 assert!(
7110 missing_expected_invisibles.is_empty(),
7111 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
7112 );
7113
7114 editor_width += resize_step;
7115 }
7116 }
7117 }
7118
7119 #[gpui::test]
7120 fn test_inline_completion_popover_text(cx: &mut TestAppContext) {
7121 init_test(cx, |_| {});
7122
7123 // Test case 1: Simple insertion
7124 {
7125 let window = cx.add_window(|cx| {
7126 let buffer = MultiBuffer::build_simple("Hello, world!", cx);
7127 Editor::new(EditorMode::Full, buffer, None, true, cx)
7128 });
7129 let cx = &mut VisualTestContext::from_window(*window, cx);
7130
7131 window
7132 .update(cx, |editor, cx| {
7133 let snapshot = editor.snapshot(cx);
7134 let edit_range = snapshot.buffer_snapshot.anchor_after(Point::new(0, 6))
7135 ..snapshot.buffer_snapshot.anchor_before(Point::new(0, 6));
7136 let edits = vec![(edit_range, " beautiful".to_string())];
7137
7138 let (text, highlights) = inline_completion_popover_text(&snapshot, &edits, cx);
7139
7140 assert_eq!(text, "Hello, beautiful world!");
7141 assert_eq!(highlights.len(), 1);
7142 assert_eq!(highlights[0].0, 6..16);
7143 assert_eq!(
7144 highlights[0].1.background_color,
7145 Some(cx.theme().status().created_background)
7146 );
7147 })
7148 .unwrap();
7149 }
7150
7151 // Test case 2: Replacement
7152 {
7153 let window = cx.add_window(|cx| {
7154 let buffer = MultiBuffer::build_simple("This is a test.", cx);
7155 Editor::new(EditorMode::Full, buffer, None, true, cx)
7156 });
7157 let cx = &mut VisualTestContext::from_window(*window, cx);
7158
7159 window
7160 .update(cx, |editor, cx| {
7161 let snapshot = editor.snapshot(cx);
7162 let edits = vec![(
7163 snapshot.buffer_snapshot.anchor_after(Point::new(0, 0))
7164 ..snapshot.buffer_snapshot.anchor_before(Point::new(0, 4)),
7165 "That".to_string(),
7166 )];
7167
7168 let (text, highlights) = inline_completion_popover_text(&snapshot, &edits, cx);
7169
7170 assert_eq!(text, "That is a test.");
7171 assert_eq!(highlights.len(), 1);
7172 assert_eq!(highlights[0].0, 0..4);
7173 assert_eq!(
7174 highlights[0].1.background_color,
7175 Some(cx.theme().status().created_background)
7176 );
7177 })
7178 .unwrap();
7179 }
7180
7181 // Test case 3: Multiple edits
7182 {
7183 let window = cx.add_window(|cx| {
7184 let buffer = MultiBuffer::build_simple("Hello, world!", cx);
7185 Editor::new(EditorMode::Full, buffer, None, true, cx)
7186 });
7187 let cx = &mut VisualTestContext::from_window(*window, cx);
7188
7189 window
7190 .update(cx, |editor, cx| {
7191 let snapshot = editor.snapshot(cx);
7192 let edits = vec![
7193 (
7194 snapshot.buffer_snapshot.anchor_after(Point::new(0, 0))
7195 ..snapshot.buffer_snapshot.anchor_before(Point::new(0, 5)),
7196 "Greetings".into(),
7197 ),
7198 (
7199 snapshot.buffer_snapshot.anchor_after(Point::new(0, 12))
7200 ..snapshot.buffer_snapshot.anchor_before(Point::new(0, 12)),
7201 " and universe".into(),
7202 ),
7203 ];
7204
7205 let (text, highlights) = inline_completion_popover_text(&snapshot, &edits, cx);
7206
7207 assert_eq!(text, "Greetings, world and universe!");
7208 assert_eq!(highlights.len(), 2);
7209 assert_eq!(highlights[0].0, 0..9);
7210 assert_eq!(highlights[1].0, 16..29);
7211 assert_eq!(
7212 highlights[0].1.background_color,
7213 Some(cx.theme().status().created_background)
7214 );
7215 assert_eq!(
7216 highlights[1].1.background_color,
7217 Some(cx.theme().status().created_background)
7218 );
7219 })
7220 .unwrap();
7221 }
7222
7223 // Test case 4: Multiple lines with edits
7224 {
7225 let window = cx.add_window(|cx| {
7226 let buffer = MultiBuffer::build_simple(
7227 "First line\nSecond line\nThird line\nFourth line",
7228 cx,
7229 );
7230 Editor::new(EditorMode::Full, buffer, None, true, cx)
7231 });
7232 let cx = &mut VisualTestContext::from_window(*window, cx);
7233
7234 window
7235 .update(cx, |editor, cx| {
7236 let snapshot = editor.snapshot(cx);
7237 let edits = vec![
7238 (
7239 snapshot.buffer_snapshot.anchor_before(Point::new(1, 7))
7240 ..snapshot.buffer_snapshot.anchor_before(Point::new(1, 11)),
7241 "modified".to_string(),
7242 ),
7243 (
7244 snapshot.buffer_snapshot.anchor_before(Point::new(2, 0))
7245 ..snapshot.buffer_snapshot.anchor_before(Point::new(2, 10)),
7246 "New third line".to_string(),
7247 ),
7248 (
7249 snapshot.buffer_snapshot.anchor_before(Point::new(3, 6))
7250 ..snapshot.buffer_snapshot.anchor_before(Point::new(3, 6)),
7251 " updated".to_string(),
7252 ),
7253 ];
7254
7255 let (text, highlights) = inline_completion_popover_text(&snapshot, &edits, cx);
7256
7257 assert_eq!(text, "Second modified\nNew third line\nFourth updated line");
7258 assert_eq!(highlights.len(), 3);
7259 assert_eq!(highlights[0].0, 7..15); // "modified"
7260 assert_eq!(highlights[1].0, 16..30); // "New third line"
7261 assert_eq!(highlights[2].0, 37..45); // " updated"
7262
7263 for highlight in &highlights {
7264 assert_eq!(
7265 highlight.1.background_color,
7266 Some(cx.theme().status().created_background)
7267 );
7268 }
7269 })
7270 .unwrap();
7271 }
7272 }
7273
7274 fn collect_invisibles_from_new_editor(
7275 cx: &mut TestAppContext,
7276 editor_mode: EditorMode,
7277 input_text: &str,
7278 editor_width: Pixels,
7279 show_line_numbers: bool,
7280 ) -> Vec<Invisible> {
7281 info!(
7282 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
7283 editor_width.0
7284 );
7285 let window = cx.add_window(|cx| {
7286 let buffer = MultiBuffer::build_simple(input_text, cx);
7287 Editor::new(editor_mode, buffer, None, true, cx)
7288 });
7289 let cx = &mut VisualTestContext::from_window(*window, cx);
7290 let editor = window.root(cx).unwrap();
7291
7292 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
7293 window
7294 .update(cx, |editor, cx| {
7295 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
7296 editor.set_wrap_width(Some(editor_width), cx);
7297 editor.set_show_line_numbers(show_line_numbers, cx);
7298 })
7299 .unwrap();
7300 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
7301 EditorElement::new(&editor, style)
7302 });
7303 state
7304 .position_map
7305 .line_layouts
7306 .iter()
7307 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
7308 .cloned()
7309 .collect()
7310 }
7311}