element.rs

   1use crate::{
   2    code_context_menus::{CodeActionsMenu, MENU_ASIDE_MAX_WIDTH, MENU_ASIDE_MIN_WIDTH, MENU_GAP},
   3    commit_tooltip::{blame_entry_relative_timestamp, CommitTooltip, ParsedCommitMessage},
   4    display_map::{
   5        Block, BlockContext, BlockStyle, DisplaySnapshot, HighlightedChunk, ToDisplayPoint,
   6    },
   7    editor_settings::{
   8        CurrentLineHighlight, DoubleClickInMultibuffer, MultiCursorModifier, ScrollBeyondLastLine,
   9        ScrollbarDiagnostics, ShowScrollbar,
  10    },
  11    git::blame::GitBlame,
  12    hover_popover::{
  13        self, hover_at, HOVER_POPOVER_GAP, MIN_POPOVER_CHARACTER_WIDTH, MIN_POPOVER_LINE_HEIGHT,
  14    },
  15    inlay_hint_settings,
  16    items::BufferSearchHighlights,
  17    mouse_context_menu::{self, MenuPosition, MouseContextMenu},
  18    scroll::{axis_pair, scroll_amount::ScrollAmount, AxisPair},
  19    BlockId, ChunkReplacement, ContextMenuPlacement, CursorShape, CustomBlockId, DisplayDiffHunk,
  20    DisplayPoint, DisplayRow, DocumentHighlightRead, DocumentHighlightWrite, EditDisplayMode,
  21    Editor, EditorMode, EditorSettings, EditorSnapshot, EditorStyle, FocusedBlock, GoToHunk,
  22    GoToPreviousHunk, GutterDimensions, HalfPageDown, HalfPageUp, HandleInput, HoveredCursor,
  23    InlayHintRefreshReason, InlineCompletion, JumpData, LineDown, LineHighlight, LineUp,
  24    OpenExcerpts, PageDown, PageUp, Point, RowExt, RowRangeExt, SelectPhase, SelectedTextHighlight,
  25    Selection, SoftWrap, StickyHeaderExcerpt, ToPoint, ToggleFold, COLUMNAR_SELECTION_MODIFIERS,
  26    CURSORS_VISIBLE_FOR, FILE_HEADER_HEIGHT, GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED, MAX_LINE_LEN,
  27    MIN_LINE_NUMBER_DIGITS, MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
  28};
  29use buffer_diff::{DiffHunkStatus, DiffHunkStatusKind};
  30use client::ParticipantIndex;
  31use collections::{BTreeMap, HashMap, HashSet};
  32use feature_flags::{Debugger, FeatureFlagAppExt};
  33use file_icons::FileIcons;
  34use git::{blame::BlameEntry, status::FileStatus, Oid};
  35use gpui::{
  36    anchored, deferred, div, fill, linear_color_stop, linear_gradient, outline, point, px, quad,
  37    relative, size, solid_background, transparent_black, Action, AnyElement, App, AvailableSpace,
  38    Axis, Bounds, ClickEvent, ClipboardItem, ContentMask, Context, Corner, Corners, CursorStyle,
  39    DispatchPhase, Edges, Element, ElementInputHandler, Entity, Focusable as _, FontId,
  40    GlobalElementId, Hitbox, Hsla, InteractiveElement, IntoElement, Keystroke, Length,
  41    ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PaintQuad,
  42    ParentElement, Pixels, ScrollDelta, ScrollWheelEvent, ShapedLine, SharedString, Size,
  43    StatefulInteractiveElement, Style, Styled, Subscription, TextRun, TextStyleRefinement, Window,
  44};
  45use inline_completion::Direction;
  46use itertools::Itertools;
  47use language::{
  48    language_settings::{
  49        IndentGuideBackgroundColoring, IndentGuideColoring, IndentGuideSettings,
  50        ShowWhitespaceSetting,
  51    },
  52    ChunkRendererContext,
  53};
  54use lsp::DiagnosticSeverity;
  55use multi_buffer::{
  56    Anchor, ExcerptId, ExcerptInfo, ExpandExcerptDirection, ExpandInfo, MultiBufferPoint,
  57    MultiBufferRow, RowInfo,
  58};
  59use project::{
  60    debugger::breakpoint_store::{Breakpoint, BreakpointKind},
  61    project_settings::{self, GitGutterSetting, GitHunkStyleSetting, ProjectSettings},
  62};
  63use settings::Settings;
  64use smallvec::{smallvec, SmallVec};
  65use std::{
  66    any::TypeId,
  67    borrow::Cow,
  68    cmp::{self, Ordering},
  69    fmt::{self, Write},
  70    iter, mem,
  71    ops::{Deref, Range},
  72    rc::Rc,
  73    sync::Arc,
  74};
  75use sum_tree::Bias;
  76use text::BufferId;
  77use theme::{ActiveTheme, Appearance, BufferLineHeight, PlayerColor};
  78use ui::{
  79    h_flex, prelude::*, ButtonLike, ContextMenu, IconButtonShape, KeyBinding, Tooltip,
  80    POPOVER_Y_PADDING,
  81};
  82use unicode_segmentation::UnicodeSegmentation;
  83use util::{debug_panic, RangeExt, ResultExt};
  84use workspace::{item::Item, notifications::NotifyTaskExt};
  85
  86const INLINE_BLAME_PADDING_EM_WIDTHS: f32 = 7.;
  87const MIN_SCROLL_THUMB_SIZE: f32 = 25.;
  88
  89/// Determines what kinds of highlights should be applied to a lines background.
  90#[derive(Clone, Copy, Default)]
  91struct LineHighlightSpec {
  92    selection: bool,
  93    breakpoint: bool,
  94    _active_stack_frame: bool,
  95}
  96
  97struct SelectionLayout {
  98    head: DisplayPoint,
  99    cursor_shape: CursorShape,
 100    is_newest: bool,
 101    is_local: bool,
 102    range: Range<DisplayPoint>,
 103    active_rows: Range<DisplayRow>,
 104    user_name: Option<SharedString>,
 105}
 106
 107impl SelectionLayout {
 108    fn new<T: ToPoint + ToDisplayPoint + Clone>(
 109        selection: Selection<T>,
 110        line_mode: bool,
 111        cursor_shape: CursorShape,
 112        map: &DisplaySnapshot,
 113        is_newest: bool,
 114        is_local: bool,
 115        user_name: Option<SharedString>,
 116    ) -> Self {
 117        let point_selection = selection.map(|p| p.to_point(&map.buffer_snapshot));
 118        let display_selection = point_selection.map(|p| p.to_display_point(map));
 119        let mut range = display_selection.range();
 120        let mut head = display_selection.head();
 121        let mut active_rows = map.prev_line_boundary(point_selection.start).1.row()
 122            ..map.next_line_boundary(point_selection.end).1.row();
 123
 124        // vim visual line mode
 125        if line_mode {
 126            let point_range = map.expand_to_line(point_selection.range());
 127            range = point_range.start.to_display_point(map)..point_range.end.to_display_point(map);
 128        }
 129
 130        // any vim visual mode (including line mode)
 131        if (cursor_shape == CursorShape::Block || cursor_shape == CursorShape::Hollow)
 132            && !range.is_empty()
 133            && !selection.reversed
 134        {
 135            if head.column() > 0 {
 136                head = map.clip_point(DisplayPoint::new(head.row(), head.column() - 1), Bias::Left)
 137            } else if head.row().0 > 0 && head != map.max_point() {
 138                head = map.clip_point(
 139                    DisplayPoint::new(
 140                        head.row().previous_row(),
 141                        map.line_len(head.row().previous_row()),
 142                    ),
 143                    Bias::Left,
 144                );
 145                // updating range.end is a no-op unless you're cursor is
 146                // on the newline containing a multi-buffer divider
 147                // in which case the clip_point may have moved the head up
 148                // an additional row.
 149                range.end = DisplayPoint::new(head.row().next_row(), 0);
 150                active_rows.end = head.row();
 151            }
 152        }
 153
 154        Self {
 155            head,
 156            cursor_shape,
 157            is_newest,
 158            is_local,
 159            range,
 160            active_rows,
 161            user_name,
 162        }
 163    }
 164}
 165
 166pub struct EditorElement {
 167    editor: Entity<Editor>,
 168    style: EditorStyle,
 169}
 170
 171type DisplayRowDelta = u32;
 172
 173impl EditorElement {
 174    pub(crate) const SCROLLBAR_WIDTH: Pixels = px(15.);
 175
 176    pub fn new(editor: &Entity<Editor>, style: EditorStyle) -> Self {
 177        Self {
 178            editor: editor.clone(),
 179            style,
 180        }
 181    }
 182
 183    fn register_actions(&self, window: &mut Window, cx: &mut App) {
 184        let editor = &self.editor;
 185        editor.update(cx, |editor, cx| {
 186            for action in editor.editor_actions.borrow().values() {
 187                (action)(window, cx)
 188            }
 189        });
 190
 191        crate::rust_analyzer_ext::apply_related_actions(editor, window, cx);
 192        crate::clangd_ext::apply_related_actions(editor, window, cx);
 193        register_action(editor, window, Editor::open_context_menu);
 194        register_action(editor, window, Editor::move_left);
 195        register_action(editor, window, Editor::move_right);
 196        register_action(editor, window, Editor::move_down);
 197        register_action(editor, window, Editor::move_down_by_lines);
 198        register_action(editor, window, Editor::select_down_by_lines);
 199        register_action(editor, window, Editor::move_up);
 200        register_action(editor, window, Editor::move_up_by_lines);
 201        register_action(editor, window, Editor::select_up_by_lines);
 202        register_action(editor, window, Editor::select_page_down);
 203        register_action(editor, window, Editor::select_page_up);
 204        register_action(editor, window, Editor::cancel);
 205        register_action(editor, window, Editor::newline);
 206        register_action(editor, window, Editor::newline_above);
 207        register_action(editor, window, Editor::newline_below);
 208        register_action(editor, window, Editor::backspace);
 209        register_action(editor, window, Editor::delete);
 210        register_action(editor, window, Editor::tab);
 211        register_action(editor, window, Editor::backtab);
 212        register_action(editor, window, Editor::indent);
 213        register_action(editor, window, Editor::outdent);
 214        register_action(editor, window, Editor::autoindent);
 215        register_action(editor, window, Editor::delete_line);
 216        register_action(editor, window, Editor::join_lines);
 217        register_action(editor, window, Editor::sort_lines_case_sensitive);
 218        register_action(editor, window, Editor::sort_lines_case_insensitive);
 219        register_action(editor, window, Editor::reverse_lines);
 220        register_action(editor, window, Editor::shuffle_lines);
 221        register_action(editor, window, Editor::convert_to_upper_case);
 222        register_action(editor, window, Editor::convert_to_lower_case);
 223        register_action(editor, window, Editor::convert_to_title_case);
 224        register_action(editor, window, Editor::convert_to_snake_case);
 225        register_action(editor, window, Editor::convert_to_kebab_case);
 226        register_action(editor, window, Editor::convert_to_upper_camel_case);
 227        register_action(editor, window, Editor::convert_to_lower_camel_case);
 228        register_action(editor, window, Editor::convert_to_opposite_case);
 229        register_action(editor, window, Editor::delete_to_previous_word_start);
 230        register_action(editor, window, Editor::delete_to_previous_subword_start);
 231        register_action(editor, window, Editor::delete_to_next_word_end);
 232        register_action(editor, window, Editor::delete_to_next_subword_end);
 233        register_action(editor, window, Editor::delete_to_beginning_of_line);
 234        register_action(editor, window, Editor::delete_to_end_of_line);
 235        register_action(editor, window, Editor::cut_to_end_of_line);
 236        register_action(editor, window, Editor::duplicate_line_up);
 237        register_action(editor, window, Editor::duplicate_line_down);
 238        register_action(editor, window, Editor::duplicate_selection);
 239        register_action(editor, window, Editor::move_line_up);
 240        register_action(editor, window, Editor::move_line_down);
 241        register_action(editor, window, Editor::transpose);
 242        register_action(editor, window, Editor::rewrap);
 243        register_action(editor, window, Editor::cut);
 244        register_action(editor, window, Editor::kill_ring_cut);
 245        register_action(editor, window, Editor::kill_ring_yank);
 246        register_action(editor, window, Editor::copy);
 247        register_action(editor, window, Editor::copy_and_trim);
 248        register_action(editor, window, Editor::paste);
 249        register_action(editor, window, Editor::undo);
 250        register_action(editor, window, Editor::redo);
 251        register_action(editor, window, Editor::move_page_up);
 252        register_action(editor, window, Editor::move_page_down);
 253        register_action(editor, window, Editor::next_screen);
 254        register_action(editor, window, Editor::scroll_cursor_top);
 255        register_action(editor, window, Editor::scroll_cursor_center);
 256        register_action(editor, window, Editor::scroll_cursor_bottom);
 257        register_action(editor, window, Editor::scroll_cursor_center_top_bottom);
 258        register_action(editor, window, |editor, _: &LineDown, window, cx| {
 259            editor.scroll_screen(&ScrollAmount::Line(1.), window, cx)
 260        });
 261        register_action(editor, window, |editor, _: &LineUp, window, cx| {
 262            editor.scroll_screen(&ScrollAmount::Line(-1.), window, cx)
 263        });
 264        register_action(editor, window, |editor, _: &HalfPageDown, window, cx| {
 265            editor.scroll_screen(&ScrollAmount::Page(0.5), window, cx)
 266        });
 267        register_action(
 268            editor,
 269            window,
 270            |editor, HandleInput(text): &HandleInput, window, cx| {
 271                if text.is_empty() {
 272                    return;
 273                }
 274                editor.handle_input(text, window, cx);
 275            },
 276        );
 277        register_action(editor, window, |editor, _: &HalfPageUp, window, cx| {
 278            editor.scroll_screen(&ScrollAmount::Page(-0.5), window, cx)
 279        });
 280        register_action(editor, window, |editor, _: &PageDown, window, cx| {
 281            editor.scroll_screen(&ScrollAmount::Page(1.), window, cx)
 282        });
 283        register_action(editor, window, |editor, _: &PageUp, window, cx| {
 284            editor.scroll_screen(&ScrollAmount::Page(-1.), window, cx)
 285        });
 286        register_action(editor, window, Editor::move_to_previous_word_start);
 287        register_action(editor, window, Editor::move_to_previous_subword_start);
 288        register_action(editor, window, Editor::move_to_next_word_end);
 289        register_action(editor, window, Editor::move_to_next_subword_end);
 290        register_action(editor, window, Editor::move_to_beginning_of_line);
 291        register_action(editor, window, Editor::move_to_end_of_line);
 292        register_action(editor, window, Editor::move_to_start_of_paragraph);
 293        register_action(editor, window, Editor::move_to_end_of_paragraph);
 294        register_action(editor, window, Editor::move_to_beginning);
 295        register_action(editor, window, Editor::move_to_end);
 296        register_action(editor, window, Editor::move_to_start_of_excerpt);
 297        register_action(editor, window, Editor::move_to_start_of_next_excerpt);
 298        register_action(editor, window, Editor::move_to_end_of_excerpt);
 299        register_action(editor, window, Editor::move_to_end_of_previous_excerpt);
 300        register_action(editor, window, Editor::select_up);
 301        register_action(editor, window, Editor::select_down);
 302        register_action(editor, window, Editor::select_left);
 303        register_action(editor, window, Editor::select_right);
 304        register_action(editor, window, Editor::select_to_previous_word_start);
 305        register_action(editor, window, Editor::select_to_previous_subword_start);
 306        register_action(editor, window, Editor::select_to_next_word_end);
 307        register_action(editor, window, Editor::select_to_next_subword_end);
 308        register_action(editor, window, Editor::select_to_beginning_of_line);
 309        register_action(editor, window, Editor::select_to_end_of_line);
 310        register_action(editor, window, Editor::select_to_start_of_paragraph);
 311        register_action(editor, window, Editor::select_to_end_of_paragraph);
 312        register_action(editor, window, Editor::select_to_start_of_excerpt);
 313        register_action(editor, window, Editor::select_to_start_of_next_excerpt);
 314        register_action(editor, window, Editor::select_to_end_of_excerpt);
 315        register_action(editor, window, Editor::select_to_end_of_previous_excerpt);
 316        register_action(editor, window, Editor::select_to_beginning);
 317        register_action(editor, window, Editor::select_to_end);
 318        register_action(editor, window, Editor::select_all);
 319        register_action(editor, window, |editor, action, window, cx| {
 320            editor.select_all_matches(action, window, cx).log_err();
 321        });
 322        register_action(editor, window, Editor::select_line);
 323        register_action(editor, window, Editor::split_selection_into_lines);
 324        register_action(editor, window, Editor::add_selection_above);
 325        register_action(editor, window, Editor::add_selection_below);
 326        register_action(editor, window, |editor, action, window, cx| {
 327            editor.select_next(action, window, cx).log_err();
 328        });
 329        register_action(editor, window, |editor, action, window, cx| {
 330            editor.select_previous(action, window, cx).log_err();
 331        });
 332        register_action(editor, window, Editor::toggle_comments);
 333        register_action(editor, window, Editor::select_larger_syntax_node);
 334        register_action(editor, window, Editor::select_smaller_syntax_node);
 335        register_action(editor, window, Editor::select_enclosing_symbol);
 336        register_action(editor, window, Editor::move_to_enclosing_bracket);
 337        register_action(editor, window, Editor::undo_selection);
 338        register_action(editor, window, Editor::redo_selection);
 339        if !editor.read(cx).is_singleton(cx) {
 340            register_action(editor, window, Editor::expand_excerpts);
 341            register_action(editor, window, Editor::expand_excerpts_up);
 342            register_action(editor, window, Editor::expand_excerpts_down);
 343        }
 344        register_action(editor, window, Editor::go_to_diagnostic);
 345        register_action(editor, window, Editor::go_to_prev_diagnostic);
 346        register_action(editor, window, Editor::go_to_next_hunk);
 347        register_action(editor, window, Editor::go_to_prev_hunk);
 348        register_action(editor, window, |editor, action, window, cx| {
 349            editor
 350                .go_to_definition(action, window, cx)
 351                .detach_and_log_err(cx);
 352        });
 353        register_action(editor, window, |editor, action, window, cx| {
 354            editor
 355                .go_to_definition_split(action, window, cx)
 356                .detach_and_log_err(cx);
 357        });
 358        register_action(editor, window, |editor, action, window, cx| {
 359            editor
 360                .go_to_declaration(action, window, cx)
 361                .detach_and_log_err(cx);
 362        });
 363        register_action(editor, window, |editor, action, window, cx| {
 364            editor
 365                .go_to_declaration_split(action, window, cx)
 366                .detach_and_log_err(cx);
 367        });
 368        register_action(editor, window, |editor, action, window, cx| {
 369            editor
 370                .go_to_implementation(action, window, cx)
 371                .detach_and_log_err(cx);
 372        });
 373        register_action(editor, window, |editor, action, window, cx| {
 374            editor
 375                .go_to_implementation_split(action, window, cx)
 376                .detach_and_log_err(cx);
 377        });
 378        register_action(editor, window, |editor, action, window, cx| {
 379            editor
 380                .go_to_type_definition(action, window, cx)
 381                .detach_and_log_err(cx);
 382        });
 383        register_action(editor, window, |editor, action, window, cx| {
 384            editor
 385                .go_to_type_definition_split(action, window, cx)
 386                .detach_and_log_err(cx);
 387        });
 388        register_action(editor, window, Editor::open_url);
 389        register_action(editor, window, Editor::open_selected_filename);
 390        register_action(editor, window, Editor::fold);
 391        register_action(editor, window, Editor::fold_at_level);
 392        register_action(editor, window, Editor::fold_all);
 393        register_action(editor, window, Editor::fold_function_bodies);
 394        register_action(editor, window, Editor::fold_at);
 395        register_action(editor, window, Editor::fold_recursive);
 396        register_action(editor, window, Editor::toggle_fold);
 397        register_action(editor, window, Editor::toggle_fold_recursive);
 398        register_action(editor, window, Editor::unfold_lines);
 399        register_action(editor, window, Editor::unfold_recursive);
 400        register_action(editor, window, Editor::unfold_all);
 401        register_action(editor, window, Editor::unfold_at);
 402        register_action(editor, window, Editor::fold_selected_ranges);
 403        register_action(editor, window, Editor::set_mark);
 404        register_action(editor, window, Editor::swap_selection_ends);
 405        register_action(editor, window, Editor::show_completions);
 406        register_action(editor, window, Editor::show_word_completions);
 407        register_action(editor, window, Editor::toggle_code_actions);
 408        register_action(editor, window, Editor::open_excerpts);
 409        register_action(editor, window, Editor::open_excerpts_in_split);
 410        register_action(editor, window, Editor::open_proposed_changes_editor);
 411        register_action(editor, window, Editor::toggle_soft_wrap);
 412        register_action(editor, window, Editor::toggle_tab_bar);
 413        register_action(editor, window, Editor::toggle_line_numbers);
 414        register_action(editor, window, Editor::toggle_relative_line_numbers);
 415        register_action(editor, window, Editor::toggle_indent_guides);
 416        register_action(editor, window, Editor::toggle_inlay_hints);
 417        register_action(editor, window, Editor::toggle_edit_predictions);
 418        register_action(editor, window, Editor::toggle_inline_diagnostics);
 419        register_action(editor, window, hover_popover::hover);
 420        register_action(editor, window, Editor::reveal_in_finder);
 421        register_action(editor, window, Editor::copy_path);
 422        register_action(editor, window, Editor::copy_relative_path);
 423        register_action(editor, window, Editor::copy_file_name);
 424        register_action(editor, window, Editor::copy_file_name_without_extension);
 425        register_action(editor, window, Editor::copy_highlight_json);
 426        register_action(editor, window, Editor::copy_permalink_to_line);
 427        register_action(editor, window, Editor::open_permalink_to_line);
 428        register_action(editor, window, Editor::copy_file_location);
 429        register_action(editor, window, Editor::toggle_git_blame);
 430        register_action(editor, window, Editor::toggle_git_blame_inline);
 431        register_action(editor, window, Editor::toggle_selected_diff_hunks);
 432        register_action(editor, window, Editor::toggle_staged_selected_diff_hunks);
 433        register_action(editor, window, Editor::stage_and_next);
 434        register_action(editor, window, Editor::unstage_and_next);
 435        register_action(editor, window, Editor::expand_all_diff_hunks);
 436
 437        register_action(editor, window, |editor, action, window, cx| {
 438            if let Some(task) = editor.format(action, window, cx) {
 439                task.detach_and_notify_err(window, cx);
 440            } else {
 441                cx.propagate();
 442            }
 443        });
 444        register_action(editor, window, |editor, action, window, cx| {
 445            if let Some(task) = editor.format_selections(action, window, cx) {
 446                task.detach_and_notify_err(window, cx);
 447            } else {
 448                cx.propagate();
 449            }
 450        });
 451        register_action(editor, window, |editor, action, window, cx| {
 452            if let Some(task) = editor.organize_imports(action, window, cx) {
 453                task.detach_and_notify_err(window, cx);
 454            } else {
 455                cx.propagate();
 456            }
 457        });
 458        register_action(editor, window, Editor::restart_language_server);
 459        register_action(editor, window, Editor::show_character_palette);
 460        register_action(editor, window, |editor, action, window, cx| {
 461            if let Some(task) = editor.confirm_completion(action, window, cx) {
 462                task.detach_and_notify_err(window, cx);
 463            } else {
 464                cx.propagate();
 465            }
 466        });
 467        register_action(editor, window, |editor, action, window, cx| {
 468            if let Some(task) = editor.compose_completion(action, window, cx) {
 469                task.detach_and_notify_err(window, cx);
 470            } else {
 471                cx.propagate();
 472            }
 473        });
 474        register_action(editor, window, |editor, action, window, cx| {
 475            if let Some(task) = editor.confirm_code_action(action, window, cx) {
 476                task.detach_and_notify_err(window, cx);
 477            } else {
 478                cx.propagate();
 479            }
 480        });
 481        register_action(editor, window, |editor, action, window, cx| {
 482            if let Some(task) = editor.rename(action, window, cx) {
 483                task.detach_and_notify_err(window, cx);
 484            } else {
 485                cx.propagate();
 486            }
 487        });
 488        register_action(editor, window, |editor, action, window, cx| {
 489            if let Some(task) = editor.confirm_rename(action, window, cx) {
 490                task.detach_and_notify_err(window, cx);
 491            } else {
 492                cx.propagate();
 493            }
 494        });
 495        register_action(editor, window, |editor, action, window, cx| {
 496            if let Some(task) = editor.find_all_references(action, window, cx) {
 497                task.detach_and_log_err(cx);
 498            } else {
 499                cx.propagate();
 500            }
 501        });
 502        register_action(editor, window, Editor::show_signature_help);
 503        register_action(editor, window, Editor::next_edit_prediction);
 504        register_action(editor, window, Editor::previous_edit_prediction);
 505        register_action(editor, window, Editor::show_inline_completion);
 506        register_action(editor, window, Editor::context_menu_first);
 507        register_action(editor, window, Editor::context_menu_prev);
 508        register_action(editor, window, Editor::context_menu_next);
 509        register_action(editor, window, Editor::context_menu_last);
 510        register_action(editor, window, Editor::display_cursor_names);
 511        register_action(editor, window, Editor::unique_lines_case_insensitive);
 512        register_action(editor, window, Editor::unique_lines_case_sensitive);
 513        register_action(editor, window, Editor::accept_partial_inline_completion);
 514        register_action(editor, window, Editor::accept_edit_prediction);
 515        register_action(editor, window, Editor::restore_file);
 516        register_action(editor, window, Editor::git_restore);
 517        register_action(editor, window, Editor::apply_all_diff_hunks);
 518        register_action(editor, window, Editor::apply_selected_diff_hunks);
 519        register_action(editor, window, Editor::open_active_item_in_terminal);
 520        register_action(editor, window, Editor::reload_file);
 521        register_action(editor, window, Editor::spawn_nearest_task);
 522        register_action(editor, window, Editor::insert_uuid_v4);
 523        register_action(editor, window, Editor::insert_uuid_v7);
 524        register_action(editor, window, Editor::open_selections_in_multibuffer);
 525        if cx.has_flag::<Debugger>() {
 526            register_action(editor, window, Editor::toggle_breakpoint);
 527            register_action(editor, window, Editor::edit_log_breakpoint);
 528        }
 529    }
 530
 531    fn register_key_listeners(&self, window: &mut Window, _: &mut App, layout: &EditorLayout) {
 532        let position_map = layout.position_map.clone();
 533        window.on_key_event({
 534            let editor = self.editor.clone();
 535            move |event: &ModifiersChangedEvent, phase, window, cx| {
 536                if phase != DispatchPhase::Bubble {
 537                    return;
 538                }
 539                editor.update(cx, |editor, cx| {
 540                    let inlay_hint_settings = inlay_hint_settings(
 541                        editor.selections.newest_anchor().head(),
 542                        &editor.buffer.read(cx).snapshot(cx),
 543                        cx,
 544                    );
 545
 546                    if let Some(inlay_modifiers) = inlay_hint_settings
 547                        .toggle_on_modifiers_press
 548                        .as_ref()
 549                        .filter(|modifiers| modifiers.modified())
 550                    {
 551                        editor.refresh_inlay_hints(
 552                            InlayHintRefreshReason::ModifiersChanged(
 553                                inlay_modifiers == &event.modifiers,
 554                            ),
 555                            cx,
 556                        );
 557                    }
 558
 559                    if editor.hover_state.focused(window, cx) {
 560                        return;
 561                    }
 562
 563                    editor.handle_modifiers_changed(event.modifiers, &position_map, window, cx);
 564                })
 565            }
 566        });
 567    }
 568
 569    fn mouse_left_down(
 570        editor: &mut Editor,
 571        event: &MouseDownEvent,
 572        hovered_hunk: Option<Range<Anchor>>,
 573        position_map: &PositionMap,
 574        line_numbers: &HashMap<MultiBufferRow, LineNumberLayout>,
 575        window: &mut Window,
 576        cx: &mut Context<Editor>,
 577    ) {
 578        if window.default_prevented() {
 579            return;
 580        }
 581
 582        let text_hitbox = &position_map.text_hitbox;
 583        let gutter_hitbox = &position_map.gutter_hitbox;
 584        let mut click_count = event.click_count;
 585        let mut modifiers = event.modifiers;
 586
 587        if let Some(hovered_hunk) = hovered_hunk {
 588            editor.toggle_single_diff_hunk(hovered_hunk, cx);
 589            cx.notify();
 590            return;
 591        } else if gutter_hitbox.is_hovered(window) {
 592            click_count = 3; // Simulate triple-click when clicking the gutter to select lines
 593        } else if !text_hitbox.is_hovered(window) {
 594            return;
 595        }
 596
 597        let is_singleton = editor.buffer().read(cx).is_singleton();
 598
 599        if click_count == 2 && !is_singleton {
 600            match EditorSettings::get_global(cx).double_click_in_multibuffer {
 601                DoubleClickInMultibuffer::Select => {
 602                    // do nothing special on double click, all selection logic is below
 603                }
 604                DoubleClickInMultibuffer::Open => {
 605                    if modifiers.alt {
 606                        // if double click is made with alt, pretend it's a regular double click without opening and alt,
 607                        // and run the selection logic.
 608                        modifiers.alt = false;
 609                    } else {
 610                        let scroll_position_row =
 611                            position_map.scroll_pixel_position.y / position_map.line_height;
 612                        let display_row = (((event.position - gutter_hitbox.bounds.origin).y
 613                            + position_map.scroll_pixel_position.y)
 614                            / position_map.line_height)
 615                            as u32;
 616                        let multi_buffer_row = position_map
 617                            .snapshot
 618                            .display_point_to_point(
 619                                DisplayPoint::new(DisplayRow(display_row), 0),
 620                                Bias::Right,
 621                            )
 622                            .row;
 623                        let line_offset_from_top = display_row - scroll_position_row as u32;
 624                        // if double click is made without alt, open the corresponding excerp
 625                        editor.open_excerpts_common(
 626                            Some(JumpData::MultiBufferRow {
 627                                row: MultiBufferRow(multi_buffer_row),
 628                                line_offset_from_top,
 629                            }),
 630                            false,
 631                            window,
 632                            cx,
 633                        );
 634                        return;
 635                    }
 636                }
 637            }
 638        }
 639
 640        let point_for_position = position_map.point_for_position(event.position);
 641        let position = point_for_position.previous_valid;
 642        if modifiers == COLUMNAR_SELECTION_MODIFIERS {
 643            editor.select(
 644                SelectPhase::BeginColumnar {
 645                    position,
 646                    reset: false,
 647                    goal_column: point_for_position.exact_unclipped.column(),
 648                },
 649                window,
 650                cx,
 651            );
 652        } else if modifiers.shift && !modifiers.control && !modifiers.alt && !modifiers.secondary()
 653        {
 654            editor.select(
 655                SelectPhase::Extend {
 656                    position,
 657                    click_count,
 658                },
 659                window,
 660                cx,
 661            );
 662        } else {
 663            let multi_cursor_setting = EditorSettings::get_global(cx).multi_cursor_modifier;
 664            let multi_cursor_modifier = match multi_cursor_setting {
 665                MultiCursorModifier::Alt => modifiers.alt,
 666                MultiCursorModifier::CmdOrCtrl => modifiers.secondary(),
 667            };
 668            editor.select(
 669                SelectPhase::Begin {
 670                    position,
 671                    add: multi_cursor_modifier,
 672                    click_count,
 673                },
 674                window,
 675                cx,
 676            );
 677        }
 678        cx.stop_propagation();
 679
 680        if !is_singleton {
 681            let display_row = (((event.position - gutter_hitbox.bounds.origin).y
 682                + position_map.scroll_pixel_position.y)
 683                / position_map.line_height) as u32;
 684            let multi_buffer_row = position_map
 685                .snapshot
 686                .display_point_to_point(DisplayPoint::new(DisplayRow(display_row), 0), Bias::Right)
 687                .row;
 688            if line_numbers
 689                .get(&MultiBufferRow(multi_buffer_row))
 690                .and_then(|line_number| line_number.hitbox.as_ref())
 691                .is_some_and(|hitbox| hitbox.contains(&event.position))
 692            {
 693                let scroll_position_row =
 694                    position_map.scroll_pixel_position.y / position_map.line_height;
 695                let line_offset_from_top = display_row - scroll_position_row as u32;
 696
 697                editor.open_excerpts_common(
 698                    Some(JumpData::MultiBufferRow {
 699                        row: MultiBufferRow(multi_buffer_row),
 700                        line_offset_from_top,
 701                    }),
 702                    modifiers.alt,
 703                    window,
 704                    cx,
 705                );
 706                cx.stop_propagation();
 707            }
 708        }
 709    }
 710
 711    fn mouse_right_down(
 712        editor: &mut Editor,
 713        event: &MouseDownEvent,
 714        position_map: &PositionMap,
 715        window: &mut Window,
 716        cx: &mut Context<Editor>,
 717    ) {
 718        if !position_map.text_hitbox.is_hovered(window) {
 719            return;
 720        }
 721        let point_for_position = position_map.point_for_position(event.position);
 722        mouse_context_menu::deploy_context_menu(
 723            editor,
 724            Some(event.position),
 725            point_for_position.previous_valid,
 726            window,
 727            cx,
 728        );
 729        cx.stop_propagation();
 730    }
 731
 732    fn mouse_middle_down(
 733        editor: &mut Editor,
 734        event: &MouseDownEvent,
 735        position_map: &PositionMap,
 736        window: &mut Window,
 737        cx: &mut Context<Editor>,
 738    ) {
 739        if !position_map.text_hitbox.is_hovered(window) || window.default_prevented() {
 740            return;
 741        }
 742
 743        let point_for_position = position_map.point_for_position(event.position);
 744        let position = point_for_position.previous_valid;
 745
 746        editor.select(
 747            SelectPhase::BeginColumnar {
 748                position,
 749                reset: true,
 750                goal_column: point_for_position.exact_unclipped.column(),
 751            },
 752            window,
 753            cx,
 754        );
 755    }
 756
 757    fn mouse_up(
 758        editor: &mut Editor,
 759        event: &MouseUpEvent,
 760        position_map: &PositionMap,
 761        window: &mut Window,
 762        cx: &mut Context<Editor>,
 763    ) {
 764        let text_hitbox = &position_map.text_hitbox;
 765        let end_selection = editor.has_pending_selection();
 766        let pending_nonempty_selections = editor.has_pending_nonempty_selection();
 767
 768        if end_selection {
 769            editor.select(SelectPhase::End, window, cx);
 770        }
 771
 772        if end_selection && pending_nonempty_selections {
 773            cx.stop_propagation();
 774        } else if cfg!(any(target_os = "linux", target_os = "freebsd"))
 775            && event.button == MouseButton::Middle
 776        {
 777            if !text_hitbox.is_hovered(window) || editor.read_only(cx) {
 778                return;
 779            }
 780
 781            #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 782            if EditorSettings::get_global(cx).middle_click_paste {
 783                if let Some(text) = cx.read_from_primary().and_then(|item| item.text()) {
 784                    let point_for_position = position_map.point_for_position(event.position);
 785                    let position = point_for_position.previous_valid;
 786
 787                    editor.select(
 788                        SelectPhase::Begin {
 789                            position,
 790                            add: false,
 791                            click_count: 1,
 792                        },
 793                        window,
 794                        cx,
 795                    );
 796                    editor.insert(&text, window, cx);
 797                }
 798                cx.stop_propagation()
 799            }
 800        }
 801    }
 802
 803    fn click(
 804        editor: &mut Editor,
 805        event: &ClickEvent,
 806        position_map: &PositionMap,
 807        window: &mut Window,
 808        cx: &mut Context<Editor>,
 809    ) {
 810        let text_hitbox = &position_map.text_hitbox;
 811        let pending_nonempty_selections = editor.has_pending_nonempty_selection();
 812
 813        let multi_cursor_setting = EditorSettings::get_global(cx).multi_cursor_modifier;
 814        let multi_cursor_modifier = match multi_cursor_setting {
 815            MultiCursorModifier::Alt => event.modifiers().secondary(),
 816            MultiCursorModifier::CmdOrCtrl => event.modifiers().alt,
 817        };
 818
 819        if !pending_nonempty_selections && multi_cursor_modifier && text_hitbox.is_hovered(window) {
 820            let point = position_map.point_for_position(event.up.position);
 821            editor.handle_click_hovered_link(point, event.modifiers(), window, cx);
 822
 823            cx.stop_propagation();
 824        }
 825    }
 826
 827    fn mouse_dragged(
 828        editor: &mut Editor,
 829        event: &MouseMoveEvent,
 830        position_map: &PositionMap,
 831        window: &mut Window,
 832        cx: &mut Context<Editor>,
 833    ) {
 834        if !editor.has_pending_selection() {
 835            return;
 836        }
 837
 838        let text_bounds = position_map.text_hitbox.bounds;
 839        let point_for_position = position_map.point_for_position(event.position);
 840        let mut scroll_delta = gpui::Point::<f32>::default();
 841        let vertical_margin = position_map.line_height.min(text_bounds.size.height / 3.0);
 842        let top = text_bounds.origin.y + vertical_margin;
 843        let bottom = text_bounds.bottom_left().y - vertical_margin;
 844        if event.position.y < top {
 845            scroll_delta.y = -scale_vertical_mouse_autoscroll_delta(top - event.position.y);
 846        }
 847        if event.position.y > bottom {
 848            scroll_delta.y = scale_vertical_mouse_autoscroll_delta(event.position.y - bottom);
 849        }
 850
 851        // We need horizontal width of text
 852        let style = editor.style.clone().unwrap_or_default();
 853        let font_id = window.text_system().resolve_font(&style.text.font());
 854        let font_size = style.text.font_size.to_pixels(window.rem_size());
 855        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
 856
 857        let scroll_margin_x = EditorSettings::get_global(cx).horizontal_scroll_margin;
 858
 859        let scroll_space: Pixels = scroll_margin_x * em_width;
 860
 861        let left = text_bounds.origin.x + scroll_space;
 862        let right = text_bounds.top_right().x - scroll_space;
 863
 864        if event.position.x < left {
 865            scroll_delta.x = -scale_horizontal_mouse_autoscroll_delta(left - event.position.x);
 866        }
 867        if event.position.x > right {
 868            scroll_delta.x = scale_horizontal_mouse_autoscroll_delta(event.position.x - right);
 869        }
 870
 871        editor.select(
 872            SelectPhase::Update {
 873                position: point_for_position.previous_valid,
 874                goal_column: point_for_position.exact_unclipped.column(),
 875                scroll_delta,
 876            },
 877            window,
 878            cx,
 879        );
 880    }
 881
 882    fn mouse_moved(
 883        editor: &mut Editor,
 884        event: &MouseMoveEvent,
 885        position_map: &PositionMap,
 886        window: &mut Window,
 887        cx: &mut Context<Editor>,
 888    ) {
 889        let text_hitbox = &position_map.text_hitbox;
 890        let gutter_hitbox = &position_map.gutter_hitbox;
 891        let modifiers = event.modifiers;
 892        let gutter_hovered = gutter_hitbox.is_hovered(window);
 893        editor.set_gutter_hovered(gutter_hovered, cx);
 894        editor.gutter_breakpoint_indicator = None;
 895
 896        if gutter_hovered {
 897            let new_point = position_map
 898                .point_for_position(event.position)
 899                .previous_valid;
 900            let buffer_anchor = position_map
 901                .snapshot
 902                .display_point_to_anchor(new_point, Bias::Left);
 903
 904            if position_map
 905                .snapshot
 906                .buffer_snapshot
 907                .buffer_for_excerpt(buffer_anchor.excerpt_id)
 908                .is_some_and(|buffer| buffer.file().is_some())
 909            {
 910                editor.gutter_breakpoint_indicator = Some(new_point);
 911            }
 912        }
 913
 914        cx.notify();
 915
 916        // Don't trigger hover popover if mouse is hovering over context menu
 917        if text_hitbox.is_hovered(window) {
 918            let point_for_position = position_map.point_for_position(event.position);
 919
 920            editor.update_hovered_link(
 921                point_for_position,
 922                &position_map.snapshot,
 923                modifiers,
 924                window,
 925                cx,
 926            );
 927
 928            if let Some(point) = point_for_position.as_valid() {
 929                let anchor = position_map
 930                    .snapshot
 931                    .buffer_snapshot
 932                    .anchor_before(point.to_offset(&position_map.snapshot, Bias::Left));
 933                hover_at(editor, Some(anchor), window, cx);
 934                Self::update_visible_cursor(editor, point, position_map, window, cx);
 935            } else {
 936                hover_at(editor, None, window, cx);
 937            }
 938        } else {
 939            editor.hide_hovered_link(cx);
 940            hover_at(editor, None, window, cx);
 941            if gutter_hovered {
 942                cx.stop_propagation();
 943            }
 944        }
 945    }
 946
 947    fn update_visible_cursor(
 948        editor: &mut Editor,
 949        point: DisplayPoint,
 950        position_map: &PositionMap,
 951        window: &mut Window,
 952        cx: &mut Context<Editor>,
 953    ) {
 954        let snapshot = &position_map.snapshot;
 955        let Some(hub) = editor.collaboration_hub() else {
 956            return;
 957        };
 958        let start = snapshot.display_snapshot.clip_point(
 959            DisplayPoint::new(point.row(), point.column().saturating_sub(1)),
 960            Bias::Left,
 961        );
 962        let end = snapshot.display_snapshot.clip_point(
 963            DisplayPoint::new(
 964                point.row(),
 965                (point.column() + 1).min(snapshot.line_len(point.row())),
 966            ),
 967            Bias::Right,
 968        );
 969
 970        let range = snapshot
 971            .buffer_snapshot
 972            .anchor_at(start.to_point(&snapshot.display_snapshot), Bias::Left)
 973            ..snapshot
 974                .buffer_snapshot
 975                .anchor_at(end.to_point(&snapshot.display_snapshot), Bias::Right);
 976
 977        let Some(selection) = snapshot.remote_selections_in_range(&range, hub, cx).next() else {
 978            return;
 979        };
 980        let key = crate::HoveredCursor {
 981            replica_id: selection.replica_id,
 982            selection_id: selection.selection.id,
 983        };
 984        editor.hovered_cursors.insert(
 985            key.clone(),
 986            cx.spawn_in(window, async move |editor, cx| {
 987                cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 988                editor
 989                    .update(cx, |editor, cx| {
 990                        editor.hovered_cursors.remove(&key);
 991                        cx.notify();
 992                    })
 993                    .ok();
 994            }),
 995        );
 996        cx.notify()
 997    }
 998
 999    fn layout_selections(
1000        &self,
1001        start_anchor: Anchor,
1002        end_anchor: Anchor,
1003        local_selections: &[Selection<Point>],
1004        snapshot: &EditorSnapshot,
1005        start_row: DisplayRow,
1006        end_row: DisplayRow,
1007        window: &mut Window,
1008        cx: &mut App,
1009    ) -> (
1010        Vec<(PlayerColor, Vec<SelectionLayout>)>,
1011        BTreeMap<DisplayRow, LineHighlightSpec>,
1012        Option<DisplayPoint>,
1013    ) {
1014        let mut selections: Vec<(PlayerColor, Vec<SelectionLayout>)> = Vec::new();
1015        let mut active_rows = BTreeMap::new();
1016        let mut newest_selection_head = None;
1017        self.editor.update(cx, |editor, cx| {
1018            if editor.show_local_selections {
1019                let mut layouts = Vec::new();
1020                let newest = editor.selections.newest(cx);
1021                for selection in local_selections.iter().cloned() {
1022                    let is_empty = selection.start == selection.end;
1023                    let is_newest = selection == newest;
1024
1025                    let layout = SelectionLayout::new(
1026                        selection,
1027                        editor.selections.line_mode,
1028                        editor.cursor_shape,
1029                        &snapshot.display_snapshot,
1030                        is_newest,
1031                        editor.leader_peer_id.is_none(),
1032                        None,
1033                    );
1034                    if is_newest {
1035                        newest_selection_head = Some(layout.head);
1036                    }
1037
1038                    for row in cmp::max(layout.active_rows.start.0, start_row.0)
1039                        ..=cmp::min(layout.active_rows.end.0, end_row.0)
1040                    {
1041                        let contains_non_empty_selection = active_rows
1042                            .entry(DisplayRow(row))
1043                            .or_insert_with(LineHighlightSpec::default);
1044                        contains_non_empty_selection.selection |= !is_empty;
1045                    }
1046                    layouts.push(layout);
1047                }
1048
1049                let player = editor.current_user_player_color(cx);
1050                selections.push((player, layouts));
1051            }
1052
1053            if let Some(collaboration_hub) = &editor.collaboration_hub {
1054                // When following someone, render the local selections in their color.
1055                if let Some(leader_id) = editor.leader_peer_id {
1056                    if let Some(collaborator) = collaboration_hub.collaborators(cx).get(&leader_id)
1057                    {
1058                        if let Some(participant_index) = collaboration_hub
1059                            .user_participant_indices(cx)
1060                            .get(&collaborator.user_id)
1061                        {
1062                            if let Some((local_selection_style, _)) = selections.first_mut() {
1063                                *local_selection_style = cx
1064                                    .theme()
1065                                    .players()
1066                                    .color_for_participant(participant_index.0);
1067                            }
1068                        }
1069                    }
1070                }
1071
1072                let mut remote_selections = HashMap::default();
1073                for selection in snapshot.remote_selections_in_range(
1074                    &(start_anchor..end_anchor),
1075                    collaboration_hub.as_ref(),
1076                    cx,
1077                ) {
1078                    let selection_style =
1079                        Self::get_participant_color(selection.participant_index, cx);
1080
1081                    // Don't re-render the leader's selections, since the local selections
1082                    // match theirs.
1083                    if Some(selection.peer_id) == editor.leader_peer_id {
1084                        continue;
1085                    }
1086                    let key = HoveredCursor {
1087                        replica_id: selection.replica_id,
1088                        selection_id: selection.selection.id,
1089                    };
1090
1091                    let is_shown =
1092                        editor.show_cursor_names || editor.hovered_cursors.contains_key(&key);
1093
1094                    remote_selections
1095                        .entry(selection.replica_id)
1096                        .or_insert((selection_style, Vec::new()))
1097                        .1
1098                        .push(SelectionLayout::new(
1099                            selection.selection,
1100                            selection.line_mode,
1101                            selection.cursor_shape,
1102                            &snapshot.display_snapshot,
1103                            false,
1104                            false,
1105                            if is_shown { selection.user_name } else { None },
1106                        ));
1107                }
1108
1109                selections.extend(remote_selections.into_values());
1110            } else if !editor.is_focused(window) && editor.show_cursor_when_unfocused {
1111                let layouts = snapshot
1112                    .buffer_snapshot
1113                    .selections_in_range(&(start_anchor..end_anchor), true)
1114                    .map(move |(_, line_mode, cursor_shape, selection)| {
1115                        SelectionLayout::new(
1116                            selection,
1117                            line_mode,
1118                            cursor_shape,
1119                            &snapshot.display_snapshot,
1120                            false,
1121                            false,
1122                            None,
1123                        )
1124                    })
1125                    .collect::<Vec<_>>();
1126                let player = editor.current_user_player_color(cx);
1127                selections.push((player, layouts));
1128            }
1129        });
1130        (selections, active_rows, newest_selection_head)
1131    }
1132
1133    fn collect_cursors(
1134        &self,
1135        snapshot: &EditorSnapshot,
1136        cx: &mut App,
1137    ) -> Vec<(DisplayPoint, Hsla)> {
1138        let editor = self.editor.read(cx);
1139        let mut cursors = Vec::new();
1140        let mut skip_local = false;
1141        let mut add_cursor = |anchor: Anchor, color| {
1142            cursors.push((anchor.to_display_point(&snapshot.display_snapshot), color));
1143        };
1144        // Remote cursors
1145        if let Some(collaboration_hub) = &editor.collaboration_hub {
1146            for remote_selection in snapshot.remote_selections_in_range(
1147                &(Anchor::min()..Anchor::max()),
1148                collaboration_hub.deref(),
1149                cx,
1150            ) {
1151                let color = Self::get_participant_color(remote_selection.participant_index, cx);
1152                add_cursor(remote_selection.selection.head(), color.cursor);
1153                if Some(remote_selection.peer_id) == editor.leader_peer_id {
1154                    skip_local = true;
1155                }
1156            }
1157        }
1158        // Local cursors
1159        if !skip_local {
1160            let color = cx.theme().players().local().cursor;
1161            editor.selections.disjoint.iter().for_each(|selection| {
1162                add_cursor(selection.head(), color);
1163            });
1164            if let Some(ref selection) = editor.selections.pending_anchor() {
1165                add_cursor(selection.head(), color);
1166            }
1167        }
1168        cursors
1169    }
1170
1171    fn layout_visible_cursors(
1172        &self,
1173        snapshot: &EditorSnapshot,
1174        selections: &[(PlayerColor, Vec<SelectionLayout>)],
1175        block_start_rows: &HashSet<DisplayRow>,
1176        visible_display_row_range: Range<DisplayRow>,
1177        line_layouts: &[LineWithInvisibles],
1178        text_hitbox: &Hitbox,
1179        content_origin: gpui::Point<Pixels>,
1180        scroll_position: gpui::Point<f32>,
1181        scroll_pixel_position: gpui::Point<Pixels>,
1182        line_height: Pixels,
1183        em_width: Pixels,
1184        em_advance: Pixels,
1185        autoscroll_containing_element: bool,
1186        window: &mut Window,
1187        cx: &mut App,
1188    ) -> Vec<CursorLayout> {
1189        let mut autoscroll_bounds = None;
1190        let cursor_layouts = self.editor.update(cx, |editor, cx| {
1191            let mut cursors = Vec::new();
1192
1193            let show_local_cursors = editor.show_local_cursors(window, cx);
1194
1195            for (player_color, selections) in selections {
1196                for selection in selections {
1197                    let cursor_position = selection.head;
1198
1199                    let in_range = visible_display_row_range.contains(&cursor_position.row());
1200                    if (selection.is_local && !show_local_cursors)
1201                        || !in_range
1202                        || block_start_rows.contains(&cursor_position.row())
1203                    {
1204                        continue;
1205                    }
1206
1207                    let cursor_row_layout = &line_layouts
1208                        [cursor_position.row().minus(visible_display_row_range.start) as usize];
1209                    let cursor_column = cursor_position.column() as usize;
1210
1211                    let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
1212                    let mut block_width =
1213                        cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
1214                    if block_width == Pixels::ZERO {
1215                        block_width = em_advance;
1216                    }
1217                    let block_text = if let CursorShape::Block = selection.cursor_shape {
1218                        snapshot
1219                            .grapheme_at(cursor_position)
1220                            .or_else(|| {
1221                                if cursor_column == 0 {
1222                                    snapshot.placeholder_text().and_then(|s| {
1223                                        s.graphemes(true).next().map(|s| s.to_string().into())
1224                                    })
1225                                } else {
1226                                    None
1227                                }
1228                            })
1229                            .and_then(|text| {
1230                                let len = text.len();
1231
1232                                let font = cursor_row_layout
1233                                    .font_id_for_index(cursor_column)
1234                                    .and_then(|cursor_font_id| {
1235                                        window.text_system().get_font_for_id(cursor_font_id)
1236                                    })
1237                                    .unwrap_or(self.style.text.font());
1238
1239                                // Invert the text color for the block cursor. Ensure that the text
1240                                // color is opaque enough to be visible against the background color.
1241                                //
1242                                // 0.75 is an arbitrary threshold to determine if the background color is
1243                                // opaque enough to use as a text color.
1244                                //
1245                                // TODO: In the future we should ensure themes have a `text_inverse` color.
1246                                let color = if cx.theme().colors().editor_background.a < 0.75 {
1247                                    match cx.theme().appearance {
1248                                        Appearance::Dark => Hsla::black(),
1249                                        Appearance::Light => Hsla::white(),
1250                                    }
1251                                } else {
1252                                    cx.theme().colors().editor_background
1253                                };
1254
1255                                window
1256                                    .text_system()
1257                                    .shape_line(
1258                                        text,
1259                                        cursor_row_layout.font_size,
1260                                        &[TextRun {
1261                                            len,
1262                                            font,
1263                                            color,
1264                                            background_color: None,
1265                                            strikethrough: None,
1266                                            underline: None,
1267                                        }],
1268                                    )
1269                                    .log_err()
1270                            })
1271                    } else {
1272                        None
1273                    };
1274
1275                    let x = cursor_character_x - scroll_pixel_position.x;
1276                    let y = (cursor_position.row().as_f32()
1277                        - scroll_pixel_position.y / line_height)
1278                        * line_height;
1279                    if selection.is_newest {
1280                        editor.pixel_position_of_newest_cursor = Some(point(
1281                            text_hitbox.origin.x + x + block_width / 2.,
1282                            text_hitbox.origin.y + y + line_height / 2.,
1283                        ));
1284
1285                        if autoscroll_containing_element {
1286                            let top = text_hitbox.origin.y
1287                                + (cursor_position.row().as_f32() - scroll_position.y - 3.).max(0.)
1288                                    * line_height;
1289                            let left = text_hitbox.origin.x
1290                                + (cursor_position.column() as f32 - scroll_position.x - 3.)
1291                                    .max(0.)
1292                                    * em_width;
1293
1294                            let bottom = text_hitbox.origin.y
1295                                + (cursor_position.row().as_f32() - scroll_position.y + 4.)
1296                                    * line_height;
1297                            let right = text_hitbox.origin.x
1298                                + (cursor_position.column() as f32 - scroll_position.x + 4.)
1299                                    * em_width;
1300
1301                            autoscroll_bounds =
1302                                Some(Bounds::from_corners(point(left, top), point(right, bottom)))
1303                        }
1304                    }
1305
1306                    let mut cursor = CursorLayout {
1307                        color: player_color.cursor,
1308                        block_width,
1309                        origin: point(x, y),
1310                        line_height,
1311                        shape: selection.cursor_shape,
1312                        block_text,
1313                        cursor_name: None,
1314                    };
1315                    let cursor_name = selection.user_name.clone().map(|name| CursorName {
1316                        string: name,
1317                        color: self.style.background,
1318                        is_top_row: cursor_position.row().0 == 0,
1319                    });
1320                    cursor.layout(content_origin, cursor_name, window, cx);
1321                    cursors.push(cursor);
1322                }
1323            }
1324
1325            cursors
1326        });
1327
1328        if let Some(bounds) = autoscroll_bounds {
1329            window.request_autoscroll(bounds);
1330        }
1331
1332        cursor_layouts
1333    }
1334
1335    fn layout_scrollbars(
1336        &self,
1337        snapshot: &EditorSnapshot,
1338        scrollbar_range_data: ScrollbarRangeData,
1339        scroll_position: gpui::Point<f32>,
1340        non_visible_cursors: bool,
1341        window: &mut Window,
1342        cx: &mut App,
1343    ) -> AxisPair<Option<ScrollbarLayout>> {
1344        let letter_size = scrollbar_range_data.letter_size;
1345        let text_units_per_page = axis_pair(
1346            scrollbar_range_data.scrollbar_bounds.size.width / letter_size.width,
1347            scrollbar_range_data.scrollbar_bounds.size.height / letter_size.height,
1348        );
1349
1350        let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
1351        let show_scrollbars = self.editor.read(cx).show_scrollbars
1352            && match scrollbar_settings.show {
1353                ShowScrollbar::Auto => {
1354                    let editor = self.editor.read(cx);
1355                    let is_singleton = editor.is_singleton(cx);
1356                    // Git
1357                    (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_diff_hunks())
1358                    ||
1359                    // Buffer Search Results
1360                    (is_singleton && scrollbar_settings.search_results && editor.has_background_highlights::<BufferSearchHighlights>())
1361                    ||
1362                    // Selected Text Occurrences
1363                    (is_singleton && scrollbar_settings.selected_text && editor.has_background_highlights::<SelectedTextHighlight>())
1364                    ||
1365                    // Selected Symbol Occurrences
1366                    (is_singleton && scrollbar_settings.selected_symbol && (editor.has_background_highlights::<DocumentHighlightRead>() || editor.has_background_highlights::<DocumentHighlightWrite>()))
1367                    ||
1368                    // Diagnostics
1369                    (is_singleton && scrollbar_settings.diagnostics != ScrollbarDiagnostics::None && snapshot.buffer_snapshot.has_diagnostics())
1370                    ||
1371                    // Cursors out of sight
1372                    non_visible_cursors
1373                    ||
1374                    // Scrollmanager
1375                    editor.scroll_manager.scrollbars_visible()
1376                }
1377                ShowScrollbar::System => self.editor.read(cx).scroll_manager.scrollbars_visible(),
1378                ShowScrollbar::Always => true,
1379                ShowScrollbar::Never => false,
1380            };
1381
1382        let axes: AxisPair<bool> = scrollbar_settings.axes.into();
1383
1384        if snapshot.mode != EditorMode::Full {
1385            return axis_pair(None, None);
1386        }
1387
1388        let visible_range = axis_pair(
1389            axes.horizontal
1390                .then(|| scroll_position.x..scroll_position.x + text_units_per_page.horizontal),
1391            axes.vertical
1392                .then(|| scroll_position.y..scroll_position.y + text_units_per_page.vertical),
1393        );
1394
1395        // If a drag took place after we started dragging the scrollbar,
1396        // cancel the scrollbar drag.
1397        if cx.has_active_drag() {
1398            self.editor.update(cx, |editor, cx| {
1399                editor
1400                    .scroll_manager
1401                    .set_is_dragging_scrollbar(Axis::Horizontal, false, cx);
1402                editor
1403                    .scroll_manager
1404                    .set_is_dragging_scrollbar(Axis::Vertical, false, cx);
1405            });
1406        }
1407
1408        let text_bounds = scrollbar_range_data.scrollbar_bounds;
1409
1410        let track_bounds = axis_pair(
1411            axes.horizontal.then(|| {
1412                Bounds::from_corners(
1413                    point(
1414                        text_bounds.bottom_left().x,
1415                        text_bounds.bottom_left().y - self.style.scrollbar_width,
1416                    ),
1417                    point(
1418                        text_bounds.bottom_right().x
1419                            - if axes.vertical {
1420                                self.style.scrollbar_width
1421                            } else {
1422                                px(0.)
1423                            },
1424                        text_bounds.bottom_right().y,
1425                    ),
1426                )
1427            }),
1428            axes.vertical.then(|| {
1429                Bounds::from_corners(
1430                    point(self.scrollbar_left(&text_bounds), text_bounds.origin.y),
1431                    text_bounds.bottom_right(),
1432                )
1433            }),
1434        );
1435
1436        let scroll_range_size = scrollbar_range_data.scroll_range.size;
1437        let total_text_units = axis_pair(
1438            Some(scroll_range_size.width / letter_size.width),
1439            Some(scroll_range_size.height / letter_size.height),
1440        );
1441
1442        let thumb_size = axis_pair(
1443            total_text_units
1444                .horizontal
1445                .zip(track_bounds.horizontal)
1446                .and_then(|(total_text_units_x, track_bounds_x)| {
1447                    if text_units_per_page.horizontal >= total_text_units_x {
1448                        return None;
1449                    }
1450                    if track_bounds_x.size.width < px(MIN_SCROLL_THUMB_SIZE) {
1451                        return Some(track_bounds_x.size.width);
1452                    }
1453                    let thumb_size = track_bounds_x.size.width
1454                        * (text_units_per_page.horizontal / total_text_units_x);
1455                    Some(thumb_size.clamp(px(MIN_SCROLL_THUMB_SIZE), track_bounds_x.size.width))
1456                }),
1457            total_text_units.vertical.zip(track_bounds.vertical).map(
1458                |(total_text_units_y, track_bounds_y)| {
1459                    if track_bounds_y.size.height < px(MIN_SCROLL_THUMB_SIZE) {
1460                        return track_bounds_y.size.height;
1461                    }
1462                    let thumb_size = track_bounds_y.size.height
1463                        * (text_units_per_page.vertical / total_text_units_y);
1464                    thumb_size.clamp(px(MIN_SCROLL_THUMB_SIZE), track_bounds_y.size.height)
1465                },
1466            ),
1467        );
1468
1469        // NOTE: Space not taken by track bounds divided by text units not on screen
1470        let text_unit_size = axis_pair(
1471            thumb_size
1472                .horizontal
1473                .zip(track_bounds.horizontal)
1474                .zip(total_text_units.horizontal)
1475                .map(|((thumb_size, track_bounds), total_text_units)| {
1476                    (track_bounds.size.width - thumb_size)
1477                        / (total_text_units - text_units_per_page.horizontal).max(0.)
1478                }),
1479            thumb_size
1480                .vertical
1481                .zip(track_bounds.vertical)
1482                .zip(total_text_units.vertical)
1483                .map(|((thumb_size, track_bounds), total_text_units)| {
1484                    (track_bounds.size.height - thumb_size)
1485                        / (total_text_units - text_units_per_page.vertical).max(0.)
1486                }),
1487        );
1488
1489        let horizontal_scrollbar = track_bounds
1490            .horizontal
1491            .zip(visible_range.horizontal)
1492            .zip(text_unit_size.horizontal)
1493            .zip(thumb_size.horizontal)
1494            .map(
1495                |(((track_bounds, visible_range), text_unit_size), thumb_size)| ScrollbarLayout {
1496                    hitbox: window.insert_hitbox(track_bounds, false),
1497                    visible_range,
1498                    text_unit_size,
1499                    visible: show_scrollbars,
1500                    thumb_size,
1501                    axis: Axis::Horizontal,
1502                },
1503            );
1504
1505        let vertical_scrollbar = track_bounds
1506            .vertical
1507            .zip(visible_range.vertical)
1508            .zip(text_unit_size.vertical)
1509            .zip(thumb_size.vertical)
1510            .map(
1511                |(((track_bounds, visible_range), text_unit_size), thumb_size)| ScrollbarLayout {
1512                    hitbox: window.insert_hitbox(track_bounds, false),
1513                    visible_range,
1514                    text_unit_size,
1515                    visible: show_scrollbars,
1516                    thumb_size,
1517                    axis: Axis::Vertical,
1518                },
1519            );
1520
1521        axis_pair(horizontal_scrollbar, vertical_scrollbar)
1522    }
1523
1524    fn prepaint_crease_toggles(
1525        &self,
1526        crease_toggles: &mut [Option<AnyElement>],
1527        line_height: Pixels,
1528        gutter_dimensions: &GutterDimensions,
1529        gutter_settings: crate::editor_settings::Gutter,
1530        scroll_pixel_position: gpui::Point<Pixels>,
1531        gutter_hitbox: &Hitbox,
1532        window: &mut Window,
1533        cx: &mut App,
1534    ) {
1535        for (ix, crease_toggle) in crease_toggles.iter_mut().enumerate() {
1536            if let Some(crease_toggle) = crease_toggle {
1537                debug_assert!(gutter_settings.folds);
1538                let available_space = size(
1539                    AvailableSpace::MinContent,
1540                    AvailableSpace::Definite(line_height * 0.55),
1541                );
1542                let crease_toggle_size = crease_toggle.layout_as_root(available_space, window, cx);
1543
1544                let position = point(
1545                    gutter_dimensions.width - gutter_dimensions.right_padding,
1546                    ix as f32 * line_height - (scroll_pixel_position.y % line_height),
1547                );
1548                let centering_offset = point(
1549                    (gutter_dimensions.fold_area_width() - crease_toggle_size.width) / 2.,
1550                    (line_height - crease_toggle_size.height) / 2.,
1551                );
1552                let origin = gutter_hitbox.origin + position + centering_offset;
1553                crease_toggle.prepaint_as_root(origin, available_space, window, cx);
1554            }
1555        }
1556    }
1557
1558    fn prepaint_expand_toggles(
1559        &self,
1560        expand_toggles: &mut [Option<(AnyElement, gpui::Point<Pixels>)>],
1561        window: &mut Window,
1562        cx: &mut App,
1563    ) {
1564        for (expand_toggle, origin) in expand_toggles.iter_mut().flatten() {
1565            let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1566            expand_toggle.layout_as_root(available_space, window, cx);
1567            expand_toggle.prepaint_as_root(*origin, available_space, window, cx);
1568        }
1569    }
1570
1571    fn prepaint_crease_trailers(
1572        &self,
1573        trailers: Vec<Option<AnyElement>>,
1574        lines: &[LineWithInvisibles],
1575        line_height: Pixels,
1576        content_origin: gpui::Point<Pixels>,
1577        scroll_pixel_position: gpui::Point<Pixels>,
1578        em_width: Pixels,
1579        window: &mut Window,
1580        cx: &mut App,
1581    ) -> Vec<Option<CreaseTrailerLayout>> {
1582        trailers
1583            .into_iter()
1584            .enumerate()
1585            .map(|(ix, element)| {
1586                let mut element = element?;
1587                let available_space = size(
1588                    AvailableSpace::MinContent,
1589                    AvailableSpace::Definite(line_height),
1590                );
1591                let size = element.layout_as_root(available_space, window, cx);
1592
1593                let line = &lines[ix];
1594                let padding = if line.width == Pixels::ZERO {
1595                    Pixels::ZERO
1596                } else {
1597                    4. * em_width
1598                };
1599                let position = point(
1600                    scroll_pixel_position.x + line.width + padding,
1601                    ix as f32 * line_height - (scroll_pixel_position.y % line_height),
1602                );
1603                let centering_offset = point(px(0.), (line_height - size.height) / 2.);
1604                let origin = content_origin + position + centering_offset;
1605                element.prepaint_as_root(origin, available_space, window, cx);
1606                Some(CreaseTrailerLayout {
1607                    element,
1608                    bounds: Bounds::new(origin, size),
1609                })
1610            })
1611            .collect()
1612    }
1613
1614    // Folds contained in a hunk are ignored apart from shrinking visual size
1615    // If a fold contains any hunks then that fold line is marked as modified
1616    fn layout_gutter_diff_hunks(
1617        &self,
1618        line_height: Pixels,
1619        gutter_hitbox: &Hitbox,
1620        display_rows: Range<DisplayRow>,
1621        snapshot: &EditorSnapshot,
1622        window: &mut Window,
1623        cx: &mut App,
1624    ) -> Vec<(DisplayDiffHunk, Option<Hitbox>)> {
1625        let folded_buffers = self.editor.read(cx).folded_buffers(cx);
1626        let mut display_hunks = snapshot
1627            .display_diff_hunks_for_rows(display_rows, folded_buffers)
1628            .map(|hunk| (hunk, None))
1629            .collect::<Vec<_>>();
1630        let git_gutter_setting = ProjectSettings::get_global(cx)
1631            .git
1632            .git_gutter
1633            .unwrap_or_default();
1634        if let GitGutterSetting::TrackedFiles = git_gutter_setting {
1635            for (hunk, hitbox) in &mut display_hunks {
1636                if matches!(hunk, DisplayDiffHunk::Unfolded { .. }) {
1637                    let hunk_bounds =
1638                        Self::diff_hunk_bounds(snapshot, line_height, gutter_hitbox.bounds, hunk);
1639                    *hitbox = Some(window.insert_hitbox(hunk_bounds, true));
1640                }
1641            }
1642        }
1643
1644        display_hunks
1645    }
1646
1647    fn layout_inline_diagnostics(
1648        &self,
1649        line_layouts: &[LineWithInvisibles],
1650        crease_trailers: &[Option<CreaseTrailerLayout>],
1651        content_origin: gpui::Point<Pixels>,
1652        scroll_pixel_position: gpui::Point<Pixels>,
1653        inline_completion_popover_origin: Option<gpui::Point<Pixels>>,
1654        start_row: DisplayRow,
1655        end_row: DisplayRow,
1656        line_height: Pixels,
1657        em_width: Pixels,
1658        style: &EditorStyle,
1659        window: &mut Window,
1660        cx: &mut App,
1661    ) -> HashMap<DisplayRow, AnyElement> {
1662        let max_severity = ProjectSettings::get_global(cx)
1663            .diagnostics
1664            .inline
1665            .max_severity
1666            .map_or(DiagnosticSeverity::HINT, |severity| match severity {
1667                project_settings::DiagnosticSeverity::Error => DiagnosticSeverity::ERROR,
1668                project_settings::DiagnosticSeverity::Warning => DiagnosticSeverity::WARNING,
1669                project_settings::DiagnosticSeverity::Info => DiagnosticSeverity::INFORMATION,
1670                project_settings::DiagnosticSeverity::Hint => DiagnosticSeverity::HINT,
1671            });
1672
1673        let active_diagnostics_group = self
1674            .editor
1675            .read(cx)
1676            .active_diagnostics
1677            .as_ref()
1678            .map(|active_diagnostics| active_diagnostics.group_id);
1679
1680        let diagnostics_by_rows = self.editor.update(cx, |editor, cx| {
1681            let snapshot = editor.snapshot(window, cx);
1682            editor
1683                .inline_diagnostics
1684                .iter()
1685                .filter(|(_, diagnostic)| diagnostic.severity <= max_severity)
1686                .filter(|(_, diagnostic)| match active_diagnostics_group {
1687                    Some(active_diagnostics_group) => {
1688                        // Active diagnostics are all shown in the editor already, no need to display them inline
1689                        diagnostic.group_id != active_diagnostics_group
1690                    }
1691                    None => true,
1692                })
1693                .map(|(point, diag)| (point.to_display_point(&snapshot), diag.clone()))
1694                .skip_while(|(point, _)| point.row() < start_row)
1695                .take_while(|(point, _)| point.row() < end_row)
1696                .fold(HashMap::default(), |mut acc, (point, diagnostic)| {
1697                    acc.entry(point.row())
1698                        .or_insert_with(Vec::new)
1699                        .push(diagnostic);
1700                    acc
1701                })
1702        });
1703
1704        if diagnostics_by_rows.is_empty() {
1705            return HashMap::default();
1706        }
1707
1708        let severity_to_color = |sev: &DiagnosticSeverity| match sev {
1709            &DiagnosticSeverity::ERROR => Color::Error,
1710            &DiagnosticSeverity::WARNING => Color::Warning,
1711            &DiagnosticSeverity::INFORMATION => Color::Info,
1712            &DiagnosticSeverity::HINT => Color::Hint,
1713            _ => Color::Error,
1714        };
1715
1716        let padding = ProjectSettings::get_global(cx).diagnostics.inline.padding as f32 * em_width;
1717        let min_x = ProjectSettings::get_global(cx)
1718            .diagnostics
1719            .inline
1720            .min_column as f32
1721            * em_width;
1722
1723        let mut elements = HashMap::default();
1724        for (row, mut diagnostics) in diagnostics_by_rows {
1725            diagnostics.sort_by_key(|diagnostic| {
1726                (
1727                    diagnostic.severity,
1728                    std::cmp::Reverse(diagnostic.is_primary),
1729                    diagnostic.start.row,
1730                    diagnostic.start.column,
1731                )
1732            });
1733
1734            let Some(diagnostic_to_render) = diagnostics
1735                .iter()
1736                .find(|diagnostic| diagnostic.is_primary)
1737                .or_else(|| diagnostics.first())
1738            else {
1739                continue;
1740            };
1741
1742            let pos_y = content_origin.y
1743                + line_height * (row.0 as f32 - scroll_pixel_position.y / line_height);
1744
1745            let window_ix = row.0.saturating_sub(start_row.0) as usize;
1746            let pos_x = {
1747                let crease_trailer_layout = &crease_trailers[window_ix];
1748                let line_layout = &line_layouts[window_ix];
1749
1750                let line_end = if let Some(crease_trailer) = crease_trailer_layout {
1751                    crease_trailer.bounds.right()
1752                } else {
1753                    content_origin.x - scroll_pixel_position.x + line_layout.width
1754                };
1755
1756                let padded_line = line_end + padding;
1757                let min_start = content_origin.x - scroll_pixel_position.x + min_x;
1758
1759                cmp::max(padded_line, min_start)
1760            };
1761
1762            let behind_inline_completion_popover = inline_completion_popover_origin
1763                .as_ref()
1764                .map_or(false, |inline_completion_popover_origin| {
1765                    (pos_y..pos_y + line_height).contains(&inline_completion_popover_origin.y)
1766                });
1767            let opacity = if behind_inline_completion_popover {
1768                0.5
1769            } else {
1770                1.0
1771            };
1772
1773            let mut element = h_flex()
1774                .id(("diagnostic", row.0))
1775                .h(line_height)
1776                .w_full()
1777                .px_1()
1778                .rounded_xs()
1779                .opacity(opacity)
1780                .bg(severity_to_color(&diagnostic_to_render.severity)
1781                    .color(cx)
1782                    .opacity(0.05))
1783                .text_color(severity_to_color(&diagnostic_to_render.severity).color(cx))
1784                .text_sm()
1785                .font_family(style.text.font().family)
1786                .child(diagnostic_to_render.message.clone())
1787                .into_any();
1788
1789            element.prepaint_as_root(point(pos_x, pos_y), AvailableSpace::min_size(), window, cx);
1790
1791            elements.insert(row, element);
1792        }
1793
1794        elements
1795    }
1796
1797    fn layout_inline_blame(
1798        &self,
1799        display_row: DisplayRow,
1800        row_info: &RowInfo,
1801        line_layout: &LineWithInvisibles,
1802        crease_trailer: Option<&CreaseTrailerLayout>,
1803        em_width: Pixels,
1804        content_origin: gpui::Point<Pixels>,
1805        scroll_pixel_position: gpui::Point<Pixels>,
1806        line_height: Pixels,
1807        window: &mut Window,
1808        cx: &mut App,
1809    ) -> Option<AnyElement> {
1810        if !self
1811            .editor
1812            .update(cx, |editor, cx| editor.render_git_blame_inline(window, cx))
1813        {
1814            return None;
1815        }
1816
1817        let editor = self.editor.read(cx);
1818        let blame = editor.blame.clone()?;
1819        let padding = {
1820            const INLINE_BLAME_PADDING_EM_WIDTHS: f32 = 6.;
1821            const INLINE_ACCEPT_SUGGESTION_EM_WIDTHS: f32 = 14.;
1822
1823            let mut padding = INLINE_BLAME_PADDING_EM_WIDTHS;
1824
1825            if let Some(inline_completion) = editor.active_inline_completion.as_ref() {
1826                match &inline_completion.completion {
1827                    InlineCompletion::Edit {
1828                        display_mode: EditDisplayMode::TabAccept,
1829                        ..
1830                    } => padding += INLINE_ACCEPT_SUGGESTION_EM_WIDTHS,
1831                    _ => {}
1832                }
1833            }
1834
1835            padding * em_width
1836        };
1837
1838        let blame_entry = blame
1839            .update(cx, |blame, cx| {
1840                blame.blame_for_rows(&[*row_info], cx).next()
1841            })
1842            .flatten()?;
1843
1844        let mut element =
1845            render_inline_blame_entry(self.editor.clone(), &blame, blame_entry, &self.style, cx);
1846
1847        let start_y = content_origin.y
1848            + line_height * (display_row.as_f32() - scroll_pixel_position.y / line_height);
1849
1850        let start_x = {
1851            let line_end = if let Some(crease_trailer) = crease_trailer {
1852                crease_trailer.bounds.right()
1853            } else {
1854                content_origin.x - scroll_pixel_position.x + line_layout.width
1855            };
1856
1857            let padded_line_end = line_end + padding;
1858
1859            let min_column_in_pixels = ProjectSettings::get_global(cx)
1860                .git
1861                .inline_blame
1862                .and_then(|settings| settings.min_column)
1863                .map(|col| self.column_pixels(col as usize, window, cx))
1864                .unwrap_or(px(0.));
1865            let min_start = content_origin.x - scroll_pixel_position.x + min_column_in_pixels;
1866
1867            cmp::max(padded_line_end, min_start)
1868        };
1869
1870        let absolute_offset = point(start_x, start_y);
1871        element.prepaint_as_root(absolute_offset, AvailableSpace::min_size(), window, cx);
1872
1873        Some(element)
1874    }
1875
1876    fn layout_blame_entries(
1877        &self,
1878        buffer_rows: &[RowInfo],
1879        em_width: Pixels,
1880        scroll_position: gpui::Point<f32>,
1881        line_height: Pixels,
1882        gutter_hitbox: &Hitbox,
1883        max_width: Option<Pixels>,
1884        window: &mut Window,
1885        cx: &mut App,
1886    ) -> Option<Vec<AnyElement>> {
1887        if !self
1888            .editor
1889            .update(cx, |editor, cx| editor.render_git_blame_gutter(cx))
1890        {
1891            return None;
1892        }
1893
1894        let blame = self.editor.read(cx).blame.clone()?;
1895        let blamed_rows: Vec<_> = blame.update(cx, |blame, cx| {
1896            blame.blame_for_rows(buffer_rows, cx).collect()
1897        });
1898
1899        let width = if let Some(max_width) = max_width {
1900            AvailableSpace::Definite(max_width)
1901        } else {
1902            AvailableSpace::MaxContent
1903        };
1904        let scroll_top = scroll_position.y * line_height;
1905        let start_x = em_width;
1906
1907        let mut last_used_color: Option<(PlayerColor, Oid)> = None;
1908
1909        let shaped_lines = blamed_rows
1910            .into_iter()
1911            .enumerate()
1912            .flat_map(|(ix, blame_entry)| {
1913                if let Some(blame_entry) = blame_entry {
1914                    let mut element = render_blame_entry(
1915                        ix,
1916                        &blame,
1917                        blame_entry,
1918                        &self.style,
1919                        &mut last_used_color,
1920                        self.editor.clone(),
1921                        cx,
1922                    );
1923
1924                    let start_y = ix as f32 * line_height - (scroll_top % line_height);
1925                    let absolute_offset = gutter_hitbox.origin + point(start_x, start_y);
1926
1927                    element.prepaint_as_root(
1928                        absolute_offset,
1929                        size(width, AvailableSpace::MinContent),
1930                        window,
1931                        cx,
1932                    );
1933
1934                    Some(element)
1935                } else {
1936                    None
1937                }
1938            })
1939            .collect();
1940
1941        Some(shaped_lines)
1942    }
1943
1944    fn layout_indent_guides(
1945        &self,
1946        content_origin: gpui::Point<Pixels>,
1947        text_origin: gpui::Point<Pixels>,
1948        visible_buffer_range: Range<MultiBufferRow>,
1949        scroll_pixel_position: gpui::Point<Pixels>,
1950        line_height: Pixels,
1951        snapshot: &DisplaySnapshot,
1952        window: &mut Window,
1953        cx: &mut App,
1954    ) -> Option<Vec<IndentGuideLayout>> {
1955        let indent_guides = self.editor.update(cx, |editor, cx| {
1956            editor.indent_guides(visible_buffer_range, snapshot, cx)
1957        })?;
1958
1959        let active_indent_guide_indices = self.editor.update(cx, |editor, cx| {
1960            editor
1961                .find_active_indent_guide_indices(&indent_guides, snapshot, window, cx)
1962                .unwrap_or_default()
1963        });
1964
1965        Some(
1966            indent_guides
1967                .into_iter()
1968                .enumerate()
1969                .filter_map(|(i, indent_guide)| {
1970                    let single_indent_width =
1971                        self.column_pixels(indent_guide.tab_size as usize, window, cx);
1972                    let total_width = single_indent_width * indent_guide.depth as f32;
1973                    let start_x = content_origin.x + total_width - scroll_pixel_position.x;
1974                    if start_x >= text_origin.x {
1975                        let (offset_y, length) = Self::calculate_indent_guide_bounds(
1976                            indent_guide.start_row..indent_guide.end_row,
1977                            line_height,
1978                            snapshot,
1979                        );
1980
1981                        let start_y = content_origin.y + offset_y - scroll_pixel_position.y;
1982
1983                        Some(IndentGuideLayout {
1984                            origin: point(start_x, start_y),
1985                            length,
1986                            single_indent_width,
1987                            depth: indent_guide.depth,
1988                            active: active_indent_guide_indices.contains(&i),
1989                            settings: indent_guide.settings,
1990                        })
1991                    } else {
1992                        None
1993                    }
1994                })
1995                .collect(),
1996        )
1997    }
1998
1999    fn calculate_indent_guide_bounds(
2000        row_range: Range<MultiBufferRow>,
2001        line_height: Pixels,
2002        snapshot: &DisplaySnapshot,
2003    ) -> (gpui::Pixels, gpui::Pixels) {
2004        let start_point = Point::new(row_range.start.0, 0);
2005        let end_point = Point::new(row_range.end.0, 0);
2006
2007        let row_range = start_point.to_display_point(snapshot).row()
2008            ..end_point.to_display_point(snapshot).row();
2009
2010        let mut prev_line = start_point;
2011        prev_line.row = prev_line.row.saturating_sub(1);
2012        let prev_line = prev_line.to_display_point(snapshot).row();
2013
2014        let mut cons_line = end_point;
2015        cons_line.row += 1;
2016        let cons_line = cons_line.to_display_point(snapshot).row();
2017
2018        let mut offset_y = row_range.start.0 as f32 * line_height;
2019        let mut length = (cons_line.0.saturating_sub(row_range.start.0)) as f32 * line_height;
2020
2021        // If we are at the end of the buffer, ensure that the indent guide extends to the end of the line.
2022        if row_range.end == cons_line {
2023            length += line_height;
2024        }
2025
2026        // If there is a block (e.g. diagnostic) in between the start of the indent guide and the line above,
2027        // we want to extend the indent guide to the start of the block.
2028        let mut block_height = 0;
2029        let mut block_offset = 0;
2030        let mut found_excerpt_header = false;
2031        for (_, block) in snapshot.blocks_in_range(prev_line..row_range.start) {
2032            if matches!(block, Block::ExcerptBoundary { .. }) {
2033                found_excerpt_header = true;
2034                break;
2035            }
2036            block_offset += block.height();
2037            block_height += block.height();
2038        }
2039        if !found_excerpt_header {
2040            offset_y -= block_offset as f32 * line_height;
2041            length += block_height as f32 * line_height;
2042        }
2043
2044        // If there is a block (e.g. diagnostic) at the end of an multibuffer excerpt,
2045        // we want to ensure that the indent guide stops before the excerpt header.
2046        let mut block_height = 0;
2047        let mut found_excerpt_header = false;
2048        for (_, block) in snapshot.blocks_in_range(row_range.end..cons_line) {
2049            if matches!(block, Block::ExcerptBoundary { .. }) {
2050                found_excerpt_header = true;
2051            }
2052            block_height += block.height();
2053        }
2054        if found_excerpt_header {
2055            length -= block_height as f32 * line_height;
2056        }
2057
2058        (offset_y, length)
2059    }
2060
2061    fn layout_breakpoints(
2062        &self,
2063        line_height: Pixels,
2064        range: Range<DisplayRow>,
2065        scroll_pixel_position: gpui::Point<Pixels>,
2066        gutter_dimensions: &GutterDimensions,
2067        gutter_hitbox: &Hitbox,
2068        display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
2069        snapshot: &EditorSnapshot,
2070        breakpoints: HashMap<DisplayRow, (Anchor, Breakpoint)>,
2071        row_infos: &[RowInfo],
2072        window: &mut Window,
2073        cx: &mut App,
2074    ) -> Vec<AnyElement> {
2075        self.editor.update(cx, |editor, cx| {
2076            breakpoints
2077                .into_iter()
2078                .filter_map(|(display_row, (text_anchor, bp))| {
2079                    let row = MultiBufferRow { 0: display_row.0 };
2080
2081                    if row_infos
2082                        .get((display_row.0.saturating_sub(range.start.0)) as usize)
2083                        .is_some_and(|row_info| row_info.expand_info.is_some())
2084                    {
2085                        return None;
2086                    }
2087
2088                    if range.start > display_row || range.end < display_row {
2089                        return None;
2090                    }
2091
2092                    if snapshot.is_line_folded(row) {
2093                        return None;
2094                    }
2095
2096                    let button = editor.render_breakpoint(text_anchor, display_row, &bp.kind, cx);
2097
2098                    let button = prepaint_gutter_button(
2099                        button,
2100                        display_row,
2101                        line_height,
2102                        gutter_dimensions,
2103                        scroll_pixel_position,
2104                        gutter_hitbox,
2105                        display_hunks,
2106                        window,
2107                        cx,
2108                    );
2109                    Some(button)
2110                })
2111                .collect_vec()
2112        })
2113    }
2114
2115    #[allow(clippy::too_many_arguments)]
2116    fn layout_run_indicators(
2117        &self,
2118        line_height: Pixels,
2119        range: Range<DisplayRow>,
2120        row_infos: &[RowInfo],
2121        scroll_pixel_position: gpui::Point<Pixels>,
2122        gutter_dimensions: &GutterDimensions,
2123        gutter_hitbox: &Hitbox,
2124        display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
2125        snapshot: &EditorSnapshot,
2126        breakpoints: &mut HashMap<DisplayRow, (Anchor, Breakpoint)>,
2127        window: &mut Window,
2128        cx: &mut App,
2129    ) -> Vec<AnyElement> {
2130        self.editor.update(cx, |editor, cx| {
2131            let active_task_indicator_row =
2132                if let Some(crate::CodeContextMenu::CodeActions(CodeActionsMenu {
2133                    deployed_from_indicator,
2134                    actions,
2135                    ..
2136                })) = editor.context_menu.borrow().as_ref()
2137                {
2138                    actions
2139                        .tasks
2140                        .as_ref()
2141                        .map(|tasks| tasks.position.to_display_point(snapshot).row())
2142                        .or(*deployed_from_indicator)
2143                } else {
2144                    None
2145                };
2146
2147            let offset_range_start =
2148                snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left);
2149
2150            let offset_range_end =
2151                snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
2152
2153            editor
2154                .tasks
2155                .iter()
2156                .filter_map(|(_, tasks)| {
2157                    let multibuffer_point = tasks.offset.to_point(&snapshot.buffer_snapshot);
2158                    if multibuffer_point < offset_range_start
2159                        || multibuffer_point > offset_range_end
2160                    {
2161                        return None;
2162                    }
2163                    let multibuffer_row = MultiBufferRow(multibuffer_point.row);
2164                    let buffer_folded = snapshot
2165                        .buffer_snapshot
2166                        .buffer_line_for_row(multibuffer_row)
2167                        .map(|(buffer_snapshot, _)| buffer_snapshot.remote_id())
2168                        .map(|buffer_id| editor.is_buffer_folded(buffer_id, cx))
2169                        .unwrap_or(false);
2170                    if buffer_folded {
2171                        return None;
2172                    }
2173
2174                    if snapshot.is_line_folded(multibuffer_row) {
2175                        // Skip folded indicators, unless it's the starting line of a fold.
2176                        if multibuffer_row
2177                            .0
2178                            .checked_sub(1)
2179                            .map_or(false, |previous_row| {
2180                                snapshot.is_line_folded(MultiBufferRow(previous_row))
2181                            })
2182                        {
2183                            return None;
2184                        }
2185                    }
2186
2187                    let display_row = multibuffer_point.to_display_point(snapshot).row();
2188                    if row_infos
2189                        .get((display_row - range.start).0 as usize)
2190                        .is_some_and(|row_info| row_info.expand_info.is_some())
2191                    {
2192                        return None;
2193                    }
2194                    let button = editor.render_run_indicator(
2195                        &self.style,
2196                        Some(display_row) == active_task_indicator_row,
2197                        display_row,
2198                        breakpoints.remove(&display_row),
2199                        cx,
2200                    );
2201
2202                    let button = prepaint_gutter_button(
2203                        button,
2204                        display_row,
2205                        line_height,
2206                        gutter_dimensions,
2207                        scroll_pixel_position,
2208                        gutter_hitbox,
2209                        display_hunks,
2210                        window,
2211                        cx,
2212                    );
2213                    Some(button)
2214                })
2215                .collect_vec()
2216        })
2217    }
2218
2219    fn layout_expand_toggles(
2220        &self,
2221        gutter_hitbox: &Hitbox,
2222        gutter_dimensions: GutterDimensions,
2223        em_width: Pixels,
2224        line_height: Pixels,
2225        scroll_position: gpui::Point<f32>,
2226        buffer_rows: &[RowInfo],
2227        window: &mut Window,
2228        cx: &mut App,
2229    ) -> Vec<Option<(AnyElement, gpui::Point<Pixels>)>> {
2230        let editor_font_size = self.style.text.font_size.to_pixels(window.rem_size()) * 1.2;
2231
2232        let scroll_top = scroll_position.y * line_height;
2233
2234        let max_line_number_length = self
2235            .editor
2236            .read(cx)
2237            .buffer()
2238            .read(cx)
2239            .snapshot(cx)
2240            .widest_line_number()
2241            .ilog10()
2242            + 1;
2243
2244        let elements = buffer_rows
2245            .into_iter()
2246            .enumerate()
2247            .map(|(ix, row_info)| {
2248                let ExpandInfo {
2249                    excerpt_id,
2250                    direction,
2251                } = row_info.expand_info?;
2252
2253                let icon_name = match direction {
2254                    ExpandExcerptDirection::Up => IconName::ExpandUp,
2255                    ExpandExcerptDirection::Down => IconName::ExpandDown,
2256                    ExpandExcerptDirection::UpAndDown => IconName::ExpandVertical,
2257                };
2258
2259                let git_gutter_width = Self::gutter_strip_width(line_height);
2260                let available_width = gutter_dimensions.left_padding - git_gutter_width;
2261
2262                let editor = self.editor.clone();
2263                let is_wide = max_line_number_length >= MIN_LINE_NUMBER_DIGITS
2264                    && row_info
2265                        .buffer_row
2266                        .is_some_and(|row| (row + 1).ilog10() + 1 == max_line_number_length)
2267                    || gutter_dimensions.right_padding == px(0.);
2268
2269                let width = if is_wide {
2270                    available_width - px(2.)
2271                } else {
2272                    available_width + em_width - px(2.)
2273                };
2274
2275                let toggle = IconButton::new(("expand", ix), icon_name)
2276                    .icon_color(Color::Custom(cx.theme().colors().editor_line_number))
2277                    .selected_icon_color(Color::Custom(cx.theme().colors().editor_foreground))
2278                    .icon_size(IconSize::Custom(rems(editor_font_size / window.rem_size())))
2279                    .width(width.into())
2280                    .on_click(move |_, window, cx| {
2281                        editor.update(cx, |editor, cx| {
2282                            editor.expand_excerpt(excerpt_id, direction, window, cx);
2283                        });
2284                    })
2285                    .tooltip(Tooltip::for_action_title(
2286                        "Expand Excerpt",
2287                        &crate::actions::ExpandExcerpts::default(),
2288                    ))
2289                    .into_any_element();
2290
2291                let position = point(
2292                    git_gutter_width + px(1.),
2293                    ix as f32 * line_height - (scroll_top % line_height) + px(1.),
2294                );
2295                let origin = gutter_hitbox.origin + position;
2296
2297                Some((toggle, origin))
2298            })
2299            .collect();
2300
2301        elements
2302    }
2303
2304    fn layout_code_actions_indicator(
2305        &self,
2306        line_height: Pixels,
2307        newest_selection_head: DisplayPoint,
2308        scroll_pixel_position: gpui::Point<Pixels>,
2309        gutter_dimensions: &GutterDimensions,
2310        gutter_hitbox: &Hitbox,
2311        breakpoint_points: &mut HashMap<DisplayRow, (Anchor, Breakpoint)>,
2312        display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
2313        window: &mut Window,
2314        cx: &mut App,
2315    ) -> Option<AnyElement> {
2316        let mut active = false;
2317        let mut button = None;
2318        let row = newest_selection_head.row();
2319        self.editor.update(cx, |editor, cx| {
2320            if let Some(crate::CodeContextMenu::CodeActions(CodeActionsMenu {
2321                deployed_from_indicator,
2322                ..
2323            })) = editor.context_menu.borrow().as_ref()
2324            {
2325                active = deployed_from_indicator.map_or(true, |indicator_row| indicator_row == row);
2326            };
2327
2328            let breakpoint = breakpoint_points.get(&row);
2329            button = editor.render_code_actions_indicator(&self.style, row, active, breakpoint, cx);
2330        });
2331
2332        let button = button?;
2333        breakpoint_points.remove(&row);
2334
2335        let button = prepaint_gutter_button(
2336            button,
2337            row,
2338            line_height,
2339            gutter_dimensions,
2340            scroll_pixel_position,
2341            gutter_hitbox,
2342            display_hunks,
2343            window,
2344            cx,
2345        );
2346
2347        Some(button)
2348    }
2349
2350    fn get_participant_color(participant_index: Option<ParticipantIndex>, cx: &App) -> PlayerColor {
2351        if let Some(index) = participant_index {
2352            cx.theme().players().color_for_participant(index.0)
2353        } else {
2354            cx.theme().players().absent()
2355        }
2356    }
2357
2358    fn calculate_relative_line_numbers(
2359        &self,
2360        snapshot: &EditorSnapshot,
2361        rows: &Range<DisplayRow>,
2362        relative_to: Option<DisplayRow>,
2363    ) -> HashMap<DisplayRow, DisplayRowDelta> {
2364        let mut relative_rows: HashMap<DisplayRow, DisplayRowDelta> = Default::default();
2365        let Some(relative_to) = relative_to else {
2366            return relative_rows;
2367        };
2368
2369        let start = rows.start.min(relative_to);
2370        let end = rows.end.max(relative_to);
2371
2372        let buffer_rows = snapshot
2373            .row_infos(start)
2374            .take(1 + end.minus(start) as usize)
2375            .collect::<Vec<_>>();
2376
2377        let head_idx = relative_to.minus(start);
2378        let mut delta = 1;
2379        let mut i = head_idx + 1;
2380        while i < buffer_rows.len() as u32 {
2381            if buffer_rows[i as usize].buffer_row.is_some() {
2382                if rows.contains(&DisplayRow(i + start.0)) {
2383                    relative_rows.insert(DisplayRow(i + start.0), delta);
2384                }
2385                delta += 1;
2386            }
2387            i += 1;
2388        }
2389        delta = 1;
2390        i = head_idx.min(buffer_rows.len() as u32 - 1);
2391        while i > 0 && buffer_rows[i as usize].buffer_row.is_none() {
2392            i -= 1;
2393        }
2394
2395        while i > 0 {
2396            i -= 1;
2397            if buffer_rows[i as usize].buffer_row.is_some() {
2398                if rows.contains(&DisplayRow(i + start.0)) {
2399                    relative_rows.insert(DisplayRow(i + start.0), delta);
2400                }
2401                delta += 1;
2402            }
2403        }
2404
2405        relative_rows
2406    }
2407
2408    fn layout_line_numbers(
2409        &self,
2410        gutter_hitbox: Option<&Hitbox>,
2411        gutter_dimensions: GutterDimensions,
2412        line_height: Pixels,
2413        scroll_position: gpui::Point<f32>,
2414        rows: Range<DisplayRow>,
2415        buffer_rows: &[RowInfo],
2416        active_rows: &BTreeMap<DisplayRow, LineHighlightSpec>,
2417        newest_selection_head: Option<DisplayPoint>,
2418        snapshot: &EditorSnapshot,
2419        window: &mut Window,
2420        cx: &mut App,
2421    ) -> Arc<HashMap<MultiBufferRow, LineNumberLayout>> {
2422        let include_line_numbers = snapshot.show_line_numbers.unwrap_or_else(|| {
2423            EditorSettings::get_global(cx).gutter.line_numbers && snapshot.mode == EditorMode::Full
2424        });
2425        if !include_line_numbers {
2426            return Arc::default();
2427        }
2428
2429        let (newest_selection_head, is_relative) = self.editor.update(cx, |editor, cx| {
2430            let newest_selection_head = newest_selection_head.unwrap_or_else(|| {
2431                let newest = editor.selections.newest::<Point>(cx);
2432                SelectionLayout::new(
2433                    newest,
2434                    editor.selections.line_mode,
2435                    editor.cursor_shape,
2436                    &snapshot.display_snapshot,
2437                    true,
2438                    true,
2439                    None,
2440                )
2441                .head
2442            });
2443            let is_relative = editor.should_use_relative_line_numbers(cx);
2444            (newest_selection_head, is_relative)
2445        });
2446
2447        let relative_to = if is_relative {
2448            Some(newest_selection_head.row())
2449        } else {
2450            None
2451        };
2452        let relative_rows = self.calculate_relative_line_numbers(snapshot, &rows, relative_to);
2453        let mut line_number = String::new();
2454        let line_numbers = buffer_rows
2455            .into_iter()
2456            .enumerate()
2457            .flat_map(|(ix, row_info)| {
2458                let display_row = DisplayRow(rows.start.0 + ix as u32);
2459                line_number.clear();
2460                let non_relative_number = row_info.buffer_row? + 1;
2461                let number = relative_rows
2462                    .get(&display_row)
2463                    .unwrap_or(&non_relative_number);
2464                write!(&mut line_number, "{number}").unwrap();
2465                if row_info
2466                    .diff_status
2467                    .is_some_and(|status| status.is_deleted())
2468                {
2469                    return None;
2470                }
2471
2472                let color = active_rows
2473                    .get(&display_row)
2474                    .and_then(|spec| {
2475                        if spec.breakpoint {
2476                            Some(cx.theme().colors().debugger_accent)
2477                        } else if spec.selection {
2478                            Some(cx.theme().colors().editor_active_line_number)
2479                        } else {
2480                            None
2481                        }
2482                    })
2483                    .unwrap_or_else(|| cx.theme().colors().editor_line_number);
2484                let shaped_line = self
2485                    .shape_line_number(SharedString::from(&line_number), color, window)
2486                    .log_err()?;
2487                let scroll_top = scroll_position.y * line_height;
2488                let line_origin = gutter_hitbox.map(|hitbox| {
2489                    hitbox.origin
2490                        + point(
2491                            hitbox.size.width - shaped_line.width - gutter_dimensions.right_padding,
2492                            ix as f32 * line_height - (scroll_top % line_height),
2493                        )
2494                });
2495
2496                #[cfg(not(test))]
2497                let hitbox = line_origin.map(|line_origin| {
2498                    window.insert_hitbox(
2499                        Bounds::new(line_origin, size(shaped_line.width, line_height)),
2500                        false,
2501                    )
2502                });
2503                #[cfg(test)]
2504                let hitbox = {
2505                    let _ = line_origin;
2506                    None
2507                };
2508
2509                let multi_buffer_row = DisplayPoint::new(display_row, 0).to_point(snapshot).row;
2510                let multi_buffer_row = MultiBufferRow(multi_buffer_row);
2511                let line_number = LineNumberLayout {
2512                    shaped_line,
2513                    hitbox,
2514                };
2515                Some((multi_buffer_row, line_number))
2516            })
2517            .collect();
2518        Arc::new(line_numbers)
2519    }
2520
2521    fn layout_crease_toggles(
2522        &self,
2523        rows: Range<DisplayRow>,
2524        row_infos: &[RowInfo],
2525        active_rows: &BTreeMap<DisplayRow, LineHighlightSpec>,
2526        snapshot: &EditorSnapshot,
2527        window: &mut Window,
2528        cx: &mut App,
2529    ) -> Vec<Option<AnyElement>> {
2530        let include_fold_statuses = EditorSettings::get_global(cx).gutter.folds
2531            && snapshot.mode == EditorMode::Full
2532            && self.editor.read(cx).is_singleton(cx);
2533        if include_fold_statuses {
2534            row_infos
2535                .into_iter()
2536                .enumerate()
2537                .map(|(ix, info)| {
2538                    if info.expand_info.is_some() {
2539                        return None;
2540                    }
2541                    let row = info.multibuffer_row?;
2542                    let display_row = DisplayRow(rows.start.0 + ix as u32);
2543                    let active = active_rows.contains_key(&display_row);
2544
2545                    snapshot.render_crease_toggle(row, active, self.editor.clone(), window, cx)
2546                })
2547                .collect()
2548        } else {
2549            Vec::new()
2550        }
2551    }
2552
2553    fn layout_crease_trailers(
2554        &self,
2555        buffer_rows: impl IntoIterator<Item = RowInfo>,
2556        snapshot: &EditorSnapshot,
2557        window: &mut Window,
2558        cx: &mut App,
2559    ) -> Vec<Option<AnyElement>> {
2560        buffer_rows
2561            .into_iter()
2562            .map(|row_info| {
2563                if row_info.expand_info.is_some() {
2564                    return None;
2565                }
2566                if let Some(row) = row_info.multibuffer_row {
2567                    snapshot.render_crease_trailer(row, window, cx)
2568                } else {
2569                    None
2570                }
2571            })
2572            .collect()
2573    }
2574
2575    fn layout_lines(
2576        rows: Range<DisplayRow>,
2577        snapshot: &EditorSnapshot,
2578        style: &EditorStyle,
2579        editor_width: Pixels,
2580        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
2581        window: &mut Window,
2582        cx: &mut App,
2583    ) -> Vec<LineWithInvisibles> {
2584        if rows.start >= rows.end {
2585            return Vec::new();
2586        }
2587
2588        // Show the placeholder when the editor is empty
2589        if snapshot.is_empty() {
2590            let font_size = style.text.font_size.to_pixels(window.rem_size());
2591            let placeholder_color = cx.theme().colors().text_placeholder;
2592            let placeholder_text = snapshot.placeholder_text();
2593
2594            let placeholder_lines = placeholder_text
2595                .as_ref()
2596                .map_or("", AsRef::as_ref)
2597                .split('\n')
2598                .skip(rows.start.0 as usize)
2599                .chain(iter::repeat(""))
2600                .take(rows.len());
2601            placeholder_lines
2602                .filter_map(move |line| {
2603                    let run = TextRun {
2604                        len: line.len(),
2605                        font: style.text.font(),
2606                        color: placeholder_color,
2607                        background_color: None,
2608                        underline: Default::default(),
2609                        strikethrough: None,
2610                    };
2611                    window
2612                        .text_system()
2613                        .shape_line(line.to_string().into(), font_size, &[run])
2614                        .log_err()
2615                })
2616                .map(|line| LineWithInvisibles {
2617                    width: line.width,
2618                    len: line.len,
2619                    fragments: smallvec![LineFragment::Text(line)],
2620                    invisibles: Vec::new(),
2621                    font_size,
2622                })
2623                .collect()
2624        } else {
2625            let chunks = snapshot.highlighted_chunks(rows.clone(), true, style);
2626            LineWithInvisibles::from_chunks(
2627                chunks,
2628                &style,
2629                MAX_LINE_LEN,
2630                rows.len(),
2631                snapshot.mode,
2632                editor_width,
2633                is_row_soft_wrapped,
2634                window,
2635                cx,
2636            )
2637        }
2638    }
2639
2640    fn prepaint_lines(
2641        &self,
2642        start_row: DisplayRow,
2643        line_layouts: &mut [LineWithInvisibles],
2644        line_height: Pixels,
2645        scroll_pixel_position: gpui::Point<Pixels>,
2646        content_origin: gpui::Point<Pixels>,
2647        window: &mut Window,
2648        cx: &mut App,
2649    ) -> SmallVec<[AnyElement; 1]> {
2650        let mut line_elements = SmallVec::new();
2651        for (ix, line) in line_layouts.iter_mut().enumerate() {
2652            let row = start_row + DisplayRow(ix as u32);
2653            line.prepaint(
2654                line_height,
2655                scroll_pixel_position,
2656                row,
2657                content_origin,
2658                &mut line_elements,
2659                window,
2660                cx,
2661            );
2662        }
2663        line_elements
2664    }
2665
2666    fn render_block(
2667        &self,
2668        block: &Block,
2669        available_width: AvailableSpace,
2670        block_id: BlockId,
2671        block_row_start: DisplayRow,
2672        snapshot: &EditorSnapshot,
2673        text_x: Pixels,
2674        rows: &Range<DisplayRow>,
2675        line_layouts: &[LineWithInvisibles],
2676        gutter_dimensions: &GutterDimensions,
2677        line_height: Pixels,
2678        em_width: Pixels,
2679        text_hitbox: &Hitbox,
2680        editor_width: Pixels,
2681        scroll_width: &mut Pixels,
2682        resized_blocks: &mut HashMap<CustomBlockId, u32>,
2683        selections: &[Selection<Point>],
2684        selected_buffer_ids: &Vec<BufferId>,
2685        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
2686        sticky_header_excerpt_id: Option<ExcerptId>,
2687        window: &mut Window,
2688        cx: &mut App,
2689    ) -> (AnyElement, Size<Pixels>) {
2690        let mut element = match block {
2691            Block::Custom(block) => {
2692                let block_start = block.start().to_point(&snapshot.buffer_snapshot);
2693                let block_end = block.end().to_point(&snapshot.buffer_snapshot);
2694                let align_to = block_start.to_display_point(snapshot);
2695                let anchor_x = text_x
2696                    + if rows.contains(&align_to.row()) {
2697                        line_layouts[align_to.row().minus(rows.start) as usize]
2698                            .x_for_index(align_to.column() as usize)
2699                    } else {
2700                        layout_line(
2701                            align_to.row(),
2702                            snapshot,
2703                            &self.style,
2704                            editor_width,
2705                            is_row_soft_wrapped,
2706                            window,
2707                            cx,
2708                        )
2709                        .x_for_index(align_to.column() as usize)
2710                    };
2711
2712                let selected = selections
2713                    .binary_search_by(|selection| {
2714                        if selection.end <= block_start {
2715                            Ordering::Less
2716                        } else if selection.start >= block_end {
2717                            Ordering::Greater
2718                        } else {
2719                            Ordering::Equal
2720                        }
2721                    })
2722                    .is_ok();
2723
2724                div()
2725                    .size_full()
2726                    .child(block.render(&mut BlockContext {
2727                        window,
2728                        app: cx,
2729                        anchor_x,
2730                        gutter_dimensions,
2731                        line_height,
2732                        em_width,
2733                        block_id,
2734                        selected,
2735                        max_width: text_hitbox.size.width.max(*scroll_width),
2736                        editor_style: &self.style,
2737                    }))
2738                    .into_any()
2739            }
2740
2741            Block::FoldedBuffer {
2742                first_excerpt,
2743                height,
2744                ..
2745            } => {
2746                let selected = selected_buffer_ids.contains(&first_excerpt.buffer_id);
2747                let result = v_flex().id(block_id).w_full();
2748
2749                let jump_data = header_jump_data(snapshot, block_row_start, *height, first_excerpt);
2750                result
2751                    .child(self.render_buffer_header(
2752                        first_excerpt,
2753                        true,
2754                        selected,
2755                        false,
2756                        jump_data,
2757                        window,
2758                        cx,
2759                    ))
2760                    .into_any_element()
2761            }
2762
2763            Block::ExcerptBoundary {
2764                excerpt,
2765                height,
2766                starts_new_buffer,
2767                ..
2768            } => {
2769                let color = cx.theme().colors().clone();
2770                let mut result = v_flex().id(block_id).w_full();
2771
2772                let jump_data = header_jump_data(snapshot, block_row_start, *height, excerpt);
2773
2774                if *starts_new_buffer {
2775                    if sticky_header_excerpt_id != Some(excerpt.id) {
2776                        let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
2777
2778                        result = result.child(self.render_buffer_header(
2779                            excerpt, false, selected, false, jump_data, window, cx,
2780                        ));
2781                    } else {
2782                        result =
2783                            result.child(div().h(FILE_HEADER_HEIGHT as f32 * window.line_height()));
2784                    }
2785                } else {
2786                    result = result.child(
2787                        h_flex().relative().child(
2788                            div()
2789                                .top(line_height / 2.)
2790                                .absolute()
2791                                .w_full()
2792                                .h_px()
2793                                .bg(color.border_variant),
2794                        ),
2795                    );
2796                };
2797
2798                result.into_any()
2799            }
2800        };
2801
2802        // Discover the element's content height, then round up to the nearest multiple of line height.
2803        let preliminary_size = element.layout_as_root(
2804            size(available_width, AvailableSpace::MinContent),
2805            window,
2806            cx,
2807        );
2808        let quantized_height = (preliminary_size.height / line_height).ceil() * line_height;
2809        let final_size = if preliminary_size.height == quantized_height {
2810            preliminary_size
2811        } else {
2812            element.layout_as_root(size(available_width, quantized_height.into()), window, cx)
2813        };
2814
2815        if let BlockId::Custom(custom_block_id) = block_id {
2816            if block.height() > 0 {
2817                let element_height_in_lines =
2818                    ((final_size.height / line_height).ceil() as u32).max(1);
2819                if element_height_in_lines != block.height() {
2820                    resized_blocks.insert(custom_block_id, element_height_in_lines);
2821                }
2822            }
2823        }
2824
2825        (element, final_size)
2826    }
2827
2828    fn render_buffer_header(
2829        &self,
2830        for_excerpt: &ExcerptInfo,
2831        is_folded: bool,
2832        is_selected: bool,
2833        is_sticky: bool,
2834        jump_data: JumpData,
2835        window: &mut Window,
2836        cx: &mut App,
2837    ) -> Div {
2838        let editor = self.editor.read(cx);
2839        let file_status = editor
2840            .buffer
2841            .read(cx)
2842            .all_diff_hunks_expanded()
2843            .then(|| {
2844                editor
2845                    .project
2846                    .as_ref()?
2847                    .read(cx)
2848                    .status_for_buffer_id(for_excerpt.buffer_id, cx)
2849            })
2850            .flatten();
2851
2852        let include_root = editor
2853            .project
2854            .as_ref()
2855            .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
2856            .unwrap_or_default();
2857        let path = for_excerpt.buffer.resolve_file_path(cx, include_root);
2858        let filename = path
2859            .as_ref()
2860            .and_then(|path| Some(path.file_name()?.to_string_lossy().to_string()));
2861        let parent_path = path.as_ref().and_then(|path| {
2862            Some(path.parent()?.to_string_lossy().to_string() + std::path::MAIN_SEPARATOR_STR)
2863        });
2864        let focus_handle = editor.focus_handle(cx);
2865        let colors = cx.theme().colors();
2866
2867        div()
2868            .p_1()
2869            .w_full()
2870            .h(FILE_HEADER_HEIGHT as f32 * window.line_height())
2871            .child(
2872                h_flex()
2873                    .size_full()
2874                    .gap_2()
2875                    .flex_basis(Length::Definite(DefiniteLength::Fraction(0.667)))
2876                    .pl_0p5()
2877                    .pr_5()
2878                    .rounded_sm()
2879                    .when(is_sticky, |el| el.shadow_md())
2880                    .border_1()
2881                    .map(|div| {
2882                        let border_color = if is_selected
2883                            && is_folded
2884                            && focus_handle.contains_focused(window, cx)
2885                        {
2886                            colors.border_focused
2887                        } else {
2888                            colors.border
2889                        };
2890                        div.border_color(border_color)
2891                    })
2892                    .bg(colors.editor_subheader_background)
2893                    .hover(|style| style.bg(colors.element_hover))
2894                    .map(|header| {
2895                        let editor = self.editor.clone();
2896                        let buffer_id = for_excerpt.buffer_id;
2897                        let toggle_chevron_icon =
2898                            FileIcons::get_chevron_icon(!is_folded, cx).map(Icon::from_path);
2899                        header.child(
2900                            div()
2901                                .hover(|style| style.bg(colors.element_selected))
2902                                .rounded_xs()
2903                                .child(
2904                                    ButtonLike::new("toggle-buffer-fold")
2905                                        .style(ui::ButtonStyle::Transparent)
2906                                        .height(px(28.).into())
2907                                        .width(px(28.).into())
2908                                        .children(toggle_chevron_icon)
2909                                        .tooltip({
2910                                            let focus_handle = focus_handle.clone();
2911                                            move |window, cx| {
2912                                                Tooltip::for_action_in(
2913                                                    "Toggle Excerpt Fold",
2914                                                    &ToggleFold,
2915                                                    &focus_handle,
2916                                                    window,
2917                                                    cx,
2918                                                )
2919                                            }
2920                                        })
2921                                        .on_click(move |_, _, cx| {
2922                                            if is_folded {
2923                                                editor.update(cx, |editor, cx| {
2924                                                    editor.unfold_buffer(buffer_id, cx);
2925                                                });
2926                                            } else {
2927                                                editor.update(cx, |editor, cx| {
2928                                                    editor.fold_buffer(buffer_id, cx);
2929                                                });
2930                                            }
2931                                        }),
2932                                ),
2933                        )
2934                    })
2935                    .children(
2936                        editor
2937                            .addons
2938                            .values()
2939                            .filter_map(|addon| {
2940                                addon.render_buffer_header_controls(for_excerpt, window, cx)
2941                            })
2942                            .take(1),
2943                    )
2944                    .child(
2945                        h_flex()
2946                            .cursor_pointer()
2947                            .id("path header block")
2948                            .size_full()
2949                            .justify_between()
2950                            .child(
2951                                h_flex()
2952                                    .gap_2()
2953                                    .child(
2954                                        Label::new(
2955                                            filename
2956                                                .map(SharedString::from)
2957                                                .unwrap_or_else(|| "untitled".into()),
2958                                        )
2959                                        .single_line()
2960                                        .when_some(
2961                                            file_status,
2962                                            |el, status| {
2963                                                el.color(if status.is_conflicted() {
2964                                                    Color::Conflict
2965                                                } else if status.is_modified() {
2966                                                    Color::Modified
2967                                                } else if status.is_deleted() {
2968                                                    Color::Disabled
2969                                                } else {
2970                                                    Color::Created
2971                                                })
2972                                                .when(status.is_deleted(), |el| el.strikethrough())
2973                                            },
2974                                        ),
2975                                    )
2976                                    .when_some(parent_path, |then, path| {
2977                                        then.child(div().child(path).text_color(
2978                                            if file_status.is_some_and(FileStatus::is_deleted) {
2979                                                colors.text_disabled
2980                                            } else {
2981                                                colors.text_muted
2982                                            },
2983                                        ))
2984                                    }),
2985                            )
2986                            .when(is_selected, |el| {
2987                                el.child(
2988                                    h_flex()
2989                                        .id("jump-to-file-button")
2990                                        .gap_2p5()
2991                                        .child(Label::new("Jump To File"))
2992                                        .children(
2993                                            KeyBinding::for_action_in(
2994                                                &OpenExcerpts,
2995                                                &focus_handle,
2996                                                window,
2997                                                cx,
2998                                            )
2999                                            .map(|binding| binding.into_any_element()),
3000                                        ),
3001                                )
3002                            })
3003                            .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
3004                            .on_click(window.listener_for(&self.editor, {
3005                                move |editor, e: &ClickEvent, window, cx| {
3006                                    editor.open_excerpts_common(
3007                                        Some(jump_data.clone()),
3008                                        e.down.modifiers.secondary(),
3009                                        window,
3010                                        cx,
3011                                    );
3012                                }
3013                            })),
3014                    ),
3015            )
3016    }
3017
3018    fn render_blocks(
3019        &self,
3020        rows: Range<DisplayRow>,
3021        snapshot: &EditorSnapshot,
3022        hitbox: &Hitbox,
3023        text_hitbox: &Hitbox,
3024        editor_width: Pixels,
3025        scroll_width: &mut Pixels,
3026        gutter_dimensions: &GutterDimensions,
3027        em_width: Pixels,
3028        text_x: Pixels,
3029        line_height: Pixels,
3030        line_layouts: &[LineWithInvisibles],
3031        selections: &[Selection<Point>],
3032        selected_buffer_ids: &Vec<BufferId>,
3033        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
3034        sticky_header_excerpt_id: Option<ExcerptId>,
3035        window: &mut Window,
3036        cx: &mut App,
3037    ) -> Result<Vec<BlockLayout>, HashMap<CustomBlockId, u32>> {
3038        let (fixed_blocks, non_fixed_blocks) = snapshot
3039            .blocks_in_range(rows.clone())
3040            .partition::<Vec<_>, _>(|(_, block)| block.style() == BlockStyle::Fixed);
3041
3042        let mut focused_block = self
3043            .editor
3044            .update(cx, |editor, _| editor.take_focused_block());
3045        let mut fixed_block_max_width = Pixels::ZERO;
3046        let mut blocks = Vec::new();
3047        let mut resized_blocks = HashMap::default();
3048
3049        for (row, block) in fixed_blocks {
3050            let block_id = block.id();
3051
3052            if focused_block.as_ref().map_or(false, |b| b.id == block_id) {
3053                focused_block = None;
3054            }
3055
3056            let (element, element_size) = self.render_block(
3057                block,
3058                AvailableSpace::MinContent,
3059                block_id,
3060                row,
3061                snapshot,
3062                text_x,
3063                &rows,
3064                line_layouts,
3065                gutter_dimensions,
3066                line_height,
3067                em_width,
3068                text_hitbox,
3069                editor_width,
3070                scroll_width,
3071                &mut resized_blocks,
3072                selections,
3073                selected_buffer_ids,
3074                is_row_soft_wrapped,
3075                sticky_header_excerpt_id,
3076                window,
3077                cx,
3078            );
3079            fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
3080            blocks.push(BlockLayout {
3081                id: block_id,
3082                row: Some(row),
3083                element,
3084                available_space: size(AvailableSpace::MinContent, element_size.height.into()),
3085                style: BlockStyle::Fixed,
3086                is_buffer_header: block.is_buffer_header(),
3087            });
3088        }
3089
3090        for (row, block) in non_fixed_blocks {
3091            let style = block.style();
3092            let width = match style {
3093                BlockStyle::Sticky => hitbox.size.width,
3094                BlockStyle::Flex => hitbox
3095                    .size
3096                    .width
3097                    .max(fixed_block_max_width)
3098                    .max(gutter_dimensions.width + *scroll_width),
3099                BlockStyle::Fixed => unreachable!(),
3100            };
3101            let block_id = block.id();
3102
3103            if focused_block.as_ref().map_or(false, |b| b.id == block_id) {
3104                focused_block = None;
3105            }
3106
3107            let (element, element_size) = self.render_block(
3108                block,
3109                width.into(),
3110                block_id,
3111                row,
3112                snapshot,
3113                text_x,
3114                &rows,
3115                line_layouts,
3116                gutter_dimensions,
3117                line_height,
3118                em_width,
3119                text_hitbox,
3120                editor_width,
3121                scroll_width,
3122                &mut resized_blocks,
3123                selections,
3124                selected_buffer_ids,
3125                is_row_soft_wrapped,
3126                sticky_header_excerpt_id,
3127                window,
3128                cx,
3129            );
3130
3131            blocks.push(BlockLayout {
3132                id: block_id,
3133                row: Some(row),
3134                element,
3135                available_space: size(width.into(), element_size.height.into()),
3136                style,
3137                is_buffer_header: block.is_buffer_header(),
3138            });
3139        }
3140
3141        if let Some(focused_block) = focused_block {
3142            if let Some(focus_handle) = focused_block.focus_handle.upgrade() {
3143                if focus_handle.is_focused(window) {
3144                    if let Some(block) = snapshot.block_for_id(focused_block.id) {
3145                        let style = block.style();
3146                        let width = match style {
3147                            BlockStyle::Fixed => AvailableSpace::MinContent,
3148                            BlockStyle::Flex => AvailableSpace::Definite(
3149                                hitbox
3150                                    .size
3151                                    .width
3152                                    .max(fixed_block_max_width)
3153                                    .max(gutter_dimensions.width + *scroll_width),
3154                            ),
3155                            BlockStyle::Sticky => AvailableSpace::Definite(hitbox.size.width),
3156                        };
3157
3158                        let (element, element_size) = self.render_block(
3159                            &block,
3160                            width,
3161                            focused_block.id,
3162                            rows.end,
3163                            snapshot,
3164                            text_x,
3165                            &rows,
3166                            line_layouts,
3167                            gutter_dimensions,
3168                            line_height,
3169                            em_width,
3170                            text_hitbox,
3171                            editor_width,
3172                            scroll_width,
3173                            &mut resized_blocks,
3174                            selections,
3175                            selected_buffer_ids,
3176                            is_row_soft_wrapped,
3177                            sticky_header_excerpt_id,
3178                            window,
3179                            cx,
3180                        );
3181
3182                        blocks.push(BlockLayout {
3183                            id: block.id(),
3184                            row: None,
3185                            element,
3186                            available_space: size(width, element_size.height.into()),
3187                            style,
3188                            is_buffer_header: block.is_buffer_header(),
3189                        });
3190                    }
3191                }
3192            }
3193        }
3194
3195        if resized_blocks.is_empty() {
3196            *scroll_width = (*scroll_width).max(fixed_block_max_width - gutter_dimensions.width);
3197            Ok(blocks)
3198        } else {
3199            Err(resized_blocks)
3200        }
3201    }
3202
3203    /// Returns true if any of the blocks changed size since the previous frame. This will trigger
3204    /// a restart of rendering for the editor based on the new sizes.
3205    fn layout_blocks(
3206        &self,
3207        blocks: &mut Vec<BlockLayout>,
3208        block_starts: &mut HashSet<DisplayRow>,
3209        hitbox: &Hitbox,
3210        line_height: Pixels,
3211        scroll_pixel_position: gpui::Point<Pixels>,
3212        window: &mut Window,
3213        cx: &mut App,
3214    ) {
3215        for block in blocks {
3216            let mut origin = if let Some(row) = block.row {
3217                block_starts.insert(row);
3218                hitbox.origin
3219                    + point(
3220                        Pixels::ZERO,
3221                        row.as_f32() * line_height - scroll_pixel_position.y,
3222                    )
3223            } else {
3224                // Position the block outside the visible area
3225                hitbox.origin + point(Pixels::ZERO, hitbox.size.height)
3226            };
3227
3228            if !matches!(block.style, BlockStyle::Sticky) {
3229                origin += point(-scroll_pixel_position.x, Pixels::ZERO);
3230            }
3231
3232            let focus_handle =
3233                block
3234                    .element
3235                    .prepaint_as_root(origin, block.available_space, window, cx);
3236
3237            if let Some(focus_handle) = focus_handle {
3238                self.editor.update(cx, |editor, _cx| {
3239                    editor.set_focused_block(FocusedBlock {
3240                        id: block.id,
3241                        focus_handle: focus_handle.downgrade(),
3242                    });
3243                });
3244            }
3245        }
3246    }
3247
3248    fn layout_sticky_buffer_header(
3249        &self,
3250        StickyHeaderExcerpt { excerpt }: StickyHeaderExcerpt<'_>,
3251        scroll_position: f32,
3252        line_height: Pixels,
3253        snapshot: &EditorSnapshot,
3254        hitbox: &Hitbox,
3255        selected_buffer_ids: &Vec<BufferId>,
3256        blocks: &[BlockLayout],
3257        window: &mut Window,
3258        cx: &mut App,
3259    ) -> AnyElement {
3260        let jump_data = header_jump_data(
3261            snapshot,
3262            DisplayRow(scroll_position as u32),
3263            FILE_HEADER_HEIGHT + MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
3264            excerpt,
3265        );
3266
3267        let editor_bg_color = cx.theme().colors().editor_background;
3268
3269        let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
3270
3271        let mut header = v_flex()
3272            .relative()
3273            .child(
3274                div()
3275                    .w(hitbox.bounds.size.width)
3276                    .h(FILE_HEADER_HEIGHT as f32 * line_height)
3277                    .bg(linear_gradient(
3278                        0.,
3279                        linear_color_stop(editor_bg_color.opacity(0.), 0.),
3280                        linear_color_stop(editor_bg_color, 0.6),
3281                    ))
3282                    .absolute()
3283                    .top_0(),
3284            )
3285            .child(
3286                self.render_buffer_header(excerpt, false, selected, true, jump_data, window, cx)
3287                    .into_any_element(),
3288            )
3289            .into_any_element();
3290
3291        let mut origin = hitbox.origin;
3292        // Move floating header up to avoid colliding with the next buffer header.
3293        for block in blocks.iter() {
3294            if !block.is_buffer_header {
3295                continue;
3296            }
3297
3298            let Some(display_row) = block.row.filter(|row| row.0 > scroll_position as u32) else {
3299                continue;
3300            };
3301
3302            let max_row = display_row.0.saturating_sub(FILE_HEADER_HEIGHT);
3303            let offset = scroll_position - max_row as f32;
3304
3305            if offset > 0.0 {
3306                origin.y -= Pixels(offset) * line_height;
3307            }
3308            break;
3309        }
3310
3311        let size = size(
3312            AvailableSpace::Definite(hitbox.size.width),
3313            AvailableSpace::MinContent,
3314        );
3315
3316        header.prepaint_as_root(origin, size, window, cx);
3317
3318        header
3319    }
3320
3321    fn layout_cursor_popovers(
3322        &self,
3323        line_height: Pixels,
3324        text_hitbox: &Hitbox,
3325        content_origin: gpui::Point<Pixels>,
3326        start_row: DisplayRow,
3327        scroll_pixel_position: gpui::Point<Pixels>,
3328        line_layouts: &[LineWithInvisibles],
3329        cursor: DisplayPoint,
3330        cursor_point: Point,
3331        style: &EditorStyle,
3332        window: &mut Window,
3333        cx: &mut App,
3334    ) {
3335        let mut min_menu_height = Pixels::ZERO;
3336        let mut max_menu_height = Pixels::ZERO;
3337        let mut height_above_menu = Pixels::ZERO;
3338        let height_below_menu = Pixels::ZERO;
3339        let mut edit_prediction_popover_visible = false;
3340        let mut context_menu_visible = false;
3341        let context_menu_placement;
3342
3343        {
3344            let editor = self.editor.read(cx);
3345            if editor
3346                .edit_prediction_visible_in_cursor_popover(editor.has_active_inline_completion())
3347            {
3348                height_above_menu +=
3349                    editor.edit_prediction_cursor_popover_height() + POPOVER_Y_PADDING;
3350                edit_prediction_popover_visible = true;
3351            }
3352
3353            if editor.context_menu_visible() {
3354                if let Some(crate::ContextMenuOrigin::Cursor) = editor.context_menu_origin() {
3355                    let (min_height_in_lines, max_height_in_lines) = editor
3356                        .context_menu_options
3357                        .as_ref()
3358                        .map_or((3, 12), |options| {
3359                            (options.min_entries_visible, options.max_entries_visible)
3360                        });
3361
3362                    min_menu_height += line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
3363                    max_menu_height += line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
3364                    context_menu_visible = true;
3365                }
3366            }
3367            context_menu_placement = editor
3368                .context_menu_options
3369                .as_ref()
3370                .and_then(|options| options.placement.clone());
3371        }
3372
3373        let visible = edit_prediction_popover_visible || context_menu_visible;
3374        if !visible {
3375            return;
3376        }
3377
3378        let cursor_row_layout = &line_layouts[cursor.row().minus(start_row) as usize];
3379        let target_position = content_origin
3380            + gpui::Point {
3381                x: cmp::max(
3382                    px(0.),
3383                    cursor_row_layout.x_for_index(cursor.column() as usize)
3384                        - scroll_pixel_position.x,
3385                ),
3386                y: cmp::max(
3387                    px(0.),
3388                    cursor.row().next_row().as_f32() * line_height - scroll_pixel_position.y,
3389                ),
3390            };
3391
3392        let viewport_bounds =
3393            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
3394                right: -Self::SCROLLBAR_WIDTH - MENU_GAP,
3395                ..Default::default()
3396            });
3397
3398        let min_height = height_above_menu + min_menu_height + height_below_menu;
3399        let max_height = height_above_menu + max_menu_height + height_below_menu;
3400        let Some((laid_out_popovers, y_flipped)) = self.layout_popovers_above_or_below_line(
3401            target_position,
3402            line_height,
3403            min_height,
3404            max_height,
3405            context_menu_placement,
3406            text_hitbox,
3407            viewport_bounds,
3408            window,
3409            cx,
3410            |height, max_width_for_stable_x, y_flipped, window, cx| {
3411                // First layout the menu to get its size - others can be at least this wide.
3412                let context_menu = if context_menu_visible {
3413                    let menu_height = if y_flipped {
3414                        height - height_below_menu
3415                    } else {
3416                        height - height_above_menu
3417                    };
3418                    let mut element = self
3419                        .render_context_menu(line_height, menu_height, y_flipped, window, cx)
3420                        .expect("Visible context menu should always render.");
3421                    let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3422                    Some((CursorPopoverType::CodeContextMenu, element, size))
3423                } else {
3424                    None
3425                };
3426                let min_width = context_menu
3427                    .as_ref()
3428                    .map_or(px(0.), |(_, _, size)| size.width);
3429                let max_width = max_width_for_stable_x.max(
3430                    context_menu
3431                        .as_ref()
3432                        .map_or(px(0.), |(_, _, size)| size.width),
3433                );
3434
3435                let edit_prediction = if edit_prediction_popover_visible {
3436                    self.editor.update(cx, move |editor, cx| {
3437                        let accept_binding = editor.accept_edit_prediction_keybind(window, cx);
3438                        let mut element = editor.render_edit_prediction_cursor_popover(
3439                            min_width,
3440                            max_width,
3441                            cursor_point,
3442                            style,
3443                            accept_binding.keystroke(),
3444                            window,
3445                            cx,
3446                        )?;
3447                        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3448                        Some((CursorPopoverType::EditPrediction, element, size))
3449                    })
3450                } else {
3451                    None
3452                };
3453                vec![edit_prediction, context_menu]
3454                    .into_iter()
3455                    .flatten()
3456                    .collect::<Vec<_>>()
3457            },
3458        ) else {
3459            return;
3460        };
3461
3462        let Some((menu_ix, (_, menu_bounds))) = laid_out_popovers
3463            .iter()
3464            .find_position(|(x, _)| matches!(x, CursorPopoverType::CodeContextMenu))
3465        else {
3466            return;
3467        };
3468        let last_ix = laid_out_popovers.len() - 1;
3469        let menu_is_last = menu_ix == last_ix;
3470        let first_popover_bounds = laid_out_popovers[0].1;
3471        let last_popover_bounds = laid_out_popovers[last_ix].1;
3472
3473        // Bounds to layout the aside around. When y_flipped, the aside goes either above or to the
3474        // right, and otherwise it goes below or to the right.
3475        let mut target_bounds = Bounds::from_corners(
3476            first_popover_bounds.origin,
3477            last_popover_bounds.bottom_right(),
3478        );
3479        target_bounds.size.width = menu_bounds.size.width;
3480
3481        // Like `target_bounds`, but with the max height it could occupy. Choosing an aside position
3482        // based on this is preferred for layout stability.
3483        let mut max_target_bounds = target_bounds;
3484        max_target_bounds.size.height = max_height;
3485        if y_flipped {
3486            max_target_bounds.origin.y -= max_height - target_bounds.size.height;
3487        }
3488
3489        // Add spacing around `target_bounds` and `max_target_bounds`.
3490        let mut extend_amount = Edges::all(MENU_GAP);
3491        if y_flipped {
3492            extend_amount.bottom = line_height;
3493        } else {
3494            extend_amount.top = line_height;
3495        }
3496        let target_bounds = target_bounds.extend(extend_amount);
3497        let max_target_bounds = max_target_bounds.extend(extend_amount);
3498
3499        let must_place_above_or_below =
3500            if y_flipped && !menu_is_last && menu_bounds.size.height < max_menu_height {
3501                laid_out_popovers[menu_ix + 1..]
3502                    .iter()
3503                    .any(|(_, popover_bounds)| popover_bounds.size.width > menu_bounds.size.width)
3504            } else {
3505                false
3506            };
3507
3508        self.layout_context_menu_aside(
3509            y_flipped,
3510            *menu_bounds,
3511            target_bounds,
3512            max_target_bounds,
3513            max_menu_height,
3514            must_place_above_or_below,
3515            text_hitbox,
3516            viewport_bounds,
3517            window,
3518            cx,
3519        );
3520    }
3521
3522    fn layout_gutter_menu(
3523        &self,
3524        line_height: Pixels,
3525        text_hitbox: &Hitbox,
3526        content_origin: gpui::Point<Pixels>,
3527        scroll_pixel_position: gpui::Point<Pixels>,
3528        gutter_overshoot: Pixels,
3529        window: &mut Window,
3530        cx: &mut App,
3531    ) {
3532        let editor = self.editor.read(cx);
3533        if !editor.context_menu_visible() {
3534            return;
3535        }
3536        let Some(crate::ContextMenuOrigin::GutterIndicator(gutter_row)) =
3537            editor.context_menu_origin()
3538        else {
3539            return;
3540        };
3541        // Context menu was spawned via a click on a gutter. Ensure it's a bit closer to the
3542        // indicator than just a plain first column of the text field.
3543        let target_position = content_origin
3544            + gpui::Point {
3545                x: -gutter_overshoot,
3546                y: gutter_row.next_row().as_f32() * line_height - scroll_pixel_position.y,
3547            };
3548
3549        let (min_height_in_lines, max_height_in_lines) = editor
3550            .context_menu_options
3551            .as_ref()
3552            .map_or((3, 12), |options| {
3553                (options.min_entries_visible, options.max_entries_visible)
3554            });
3555
3556        let min_height = line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
3557        let max_height = line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
3558        let viewport_bounds =
3559            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
3560                right: -Self::SCROLLBAR_WIDTH - MENU_GAP,
3561                ..Default::default()
3562            });
3563        self.layout_popovers_above_or_below_line(
3564            target_position,
3565            line_height,
3566            min_height,
3567            max_height,
3568            editor
3569                .context_menu_options
3570                .as_ref()
3571                .and_then(|options| options.placement.clone()),
3572            text_hitbox,
3573            viewport_bounds,
3574            window,
3575            cx,
3576            move |height, _max_width_for_stable_x, y_flipped, window, cx| {
3577                let mut element = self
3578                    .render_context_menu(line_height, height, y_flipped, window, cx)
3579                    .expect("Visible context menu should always render.");
3580                let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3581                vec![(CursorPopoverType::CodeContextMenu, element, size)]
3582            },
3583        );
3584    }
3585
3586    fn layout_popovers_above_or_below_line(
3587        &self,
3588        target_position: gpui::Point<Pixels>,
3589        line_height: Pixels,
3590        min_height: Pixels,
3591        max_height: Pixels,
3592        placement: Option<ContextMenuPlacement>,
3593        text_hitbox: &Hitbox,
3594        viewport_bounds: Bounds<Pixels>,
3595        window: &mut Window,
3596        cx: &mut App,
3597        make_sized_popovers: impl FnOnce(
3598            Pixels,
3599            Pixels,
3600            bool,
3601            &mut Window,
3602            &mut App,
3603        ) -> Vec<(CursorPopoverType, AnyElement, Size<Pixels>)>,
3604    ) -> Option<(Vec<(CursorPopoverType, Bounds<Pixels>)>, bool)> {
3605        let text_style = TextStyleRefinement {
3606            line_height: Some(DefiniteLength::Fraction(
3607                BufferLineHeight::Comfortable.value(),
3608            )),
3609            ..Default::default()
3610        };
3611        window.with_text_style(Some(text_style), |window| {
3612            // If the max height won't fit below and there is more space above, put it above the line.
3613            let bottom_y_when_flipped = target_position.y - line_height;
3614            let available_above = bottom_y_when_flipped - text_hitbox.top();
3615            let available_below = text_hitbox.bottom() - target_position.y;
3616            let y_overflows_below = max_height > available_below;
3617            let mut y_flipped = match placement {
3618                Some(ContextMenuPlacement::Above) => true,
3619                Some(ContextMenuPlacement::Below) => false,
3620                None => y_overflows_below && available_above > available_below,
3621            };
3622            let mut height = cmp::min(
3623                max_height,
3624                if y_flipped {
3625                    available_above
3626                } else {
3627                    available_below
3628                },
3629            );
3630
3631            // If the min height doesn't fit within text bounds, instead fit within the window.
3632            if height < min_height {
3633                let available_above = bottom_y_when_flipped;
3634                let available_below = viewport_bounds.bottom() - target_position.y;
3635                let (y_flipped_override, height_override) = match placement {
3636                    Some(ContextMenuPlacement::Above) => {
3637                        (true, cmp::min(available_above, min_height))
3638                    }
3639                    Some(ContextMenuPlacement::Below) => {
3640                        (false, cmp::min(available_below, min_height))
3641                    }
3642                    None => {
3643                        if available_below > min_height {
3644                            (false, min_height)
3645                        } else if available_above > min_height {
3646                            (true, min_height)
3647                        } else if available_above > available_below {
3648                            (true, available_above)
3649                        } else {
3650                            (false, available_below)
3651                        }
3652                    }
3653                };
3654                y_flipped = y_flipped_override;
3655                height = height_override;
3656            }
3657
3658            let max_width_for_stable_x = viewport_bounds.right() - target_position.x;
3659
3660            // TODO: Use viewport_bounds.width as a max width so that it doesn't get clipped on the left
3661            // for very narrow windows.
3662            let popovers =
3663                make_sized_popovers(height, max_width_for_stable_x, y_flipped, window, cx);
3664            if popovers.is_empty() {
3665                return None;
3666            }
3667
3668            let max_width = popovers
3669                .iter()
3670                .map(|(_, _, size)| size.width)
3671                .max()
3672                .unwrap_or_default();
3673
3674            let mut current_position = gpui::Point {
3675                // Snap the right edge of the list to the right edge of the window if its horizontal bounds
3676                // overflow. Include space for the scrollbar.
3677                x: target_position
3678                    .x
3679                    .min((viewport_bounds.right() - max_width).max(Pixels::ZERO)),
3680                y: if y_flipped {
3681                    bottom_y_when_flipped
3682                } else {
3683                    target_position.y
3684                },
3685            };
3686
3687            let mut laid_out_popovers = popovers
3688                .into_iter()
3689                .map(|(popover_type, element, size)| {
3690                    if y_flipped {
3691                        current_position.y -= size.height;
3692                    }
3693                    let position = current_position;
3694                    window.defer_draw(element, current_position, 1);
3695                    if !y_flipped {
3696                        current_position.y += size.height + MENU_GAP;
3697                    } else {
3698                        current_position.y -= MENU_GAP;
3699                    }
3700                    (popover_type, Bounds::new(position, size))
3701                })
3702                .collect::<Vec<_>>();
3703
3704            if y_flipped {
3705                laid_out_popovers.reverse();
3706            }
3707
3708            Some((laid_out_popovers, y_flipped))
3709        })
3710    }
3711
3712    fn layout_context_menu_aside(
3713        &self,
3714        y_flipped: bool,
3715        menu_bounds: Bounds<Pixels>,
3716        target_bounds: Bounds<Pixels>,
3717        max_target_bounds: Bounds<Pixels>,
3718        max_height: Pixels,
3719        must_place_above_or_below: bool,
3720        text_hitbox: &Hitbox,
3721        viewport_bounds: Bounds<Pixels>,
3722        window: &mut Window,
3723        cx: &mut App,
3724    ) {
3725        let available_within_viewport = target_bounds.space_within(&viewport_bounds);
3726        let positioned_aside = if available_within_viewport.right >= MENU_ASIDE_MIN_WIDTH
3727            && !must_place_above_or_below
3728        {
3729            let max_width = cmp::min(
3730                available_within_viewport.right - px(1.),
3731                MENU_ASIDE_MAX_WIDTH,
3732            );
3733            let Some(mut aside) = self.render_context_menu_aside(
3734                size(max_width, max_height - POPOVER_Y_PADDING),
3735                window,
3736                cx,
3737            ) else {
3738                return;
3739            };
3740            aside.layout_as_root(AvailableSpace::min_size(), window, cx);
3741            let right_position = point(target_bounds.right(), menu_bounds.origin.y);
3742            Some((aside, right_position))
3743        } else {
3744            let max_size = size(
3745                // TODO(mgsloan): Once the menu is bounded by viewport width the bound on viewport
3746                // won't be needed here.
3747                cmp::min(
3748                    cmp::max(menu_bounds.size.width - px(2.), MENU_ASIDE_MIN_WIDTH),
3749                    viewport_bounds.right(),
3750                ),
3751                cmp::min(
3752                    max_height,
3753                    cmp::max(
3754                        available_within_viewport.top,
3755                        available_within_viewport.bottom,
3756                    ),
3757                ) - POPOVER_Y_PADDING,
3758            );
3759            let Some(mut aside) = self.render_context_menu_aside(max_size, window, cx) else {
3760                return;
3761            };
3762            let actual_size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
3763
3764            let top_position = point(
3765                menu_bounds.origin.x,
3766                target_bounds.top() - actual_size.height,
3767            );
3768            let bottom_position = point(menu_bounds.origin.x, target_bounds.bottom());
3769
3770            let fit_within = |available: Edges<Pixels>, wanted: Size<Pixels>| {
3771                // Prefer to fit on the same side of the line as the menu, then on the other side of
3772                // the line.
3773                if !y_flipped && wanted.height < available.bottom {
3774                    Some(bottom_position)
3775                } else if !y_flipped && wanted.height < available.top {
3776                    Some(top_position)
3777                } else if y_flipped && wanted.height < available.top {
3778                    Some(top_position)
3779                } else if y_flipped && wanted.height < available.bottom {
3780                    Some(bottom_position)
3781                } else {
3782                    None
3783                }
3784            };
3785
3786            // Prefer choosing a direction using max sizes rather than actual size for stability.
3787            let available_within_text = max_target_bounds.space_within(&text_hitbox.bounds);
3788            let wanted = size(MENU_ASIDE_MAX_WIDTH, max_height);
3789            let aside_position = fit_within(available_within_text, wanted)
3790                // Fallback: fit max size in window.
3791                .or_else(|| fit_within(max_target_bounds.space_within(&viewport_bounds), wanted))
3792                // Fallback: fit actual size in window.
3793                .or_else(|| fit_within(available_within_viewport, actual_size));
3794
3795            aside_position.map(|position| (aside, position))
3796        };
3797
3798        // Skip drawing if it doesn't fit anywhere.
3799        if let Some((aside, position)) = positioned_aside {
3800            window.defer_draw(aside, position, 2);
3801        }
3802    }
3803
3804    fn render_context_menu(
3805        &self,
3806        line_height: Pixels,
3807        height: Pixels,
3808        y_flipped: bool,
3809        window: &mut Window,
3810        cx: &mut App,
3811    ) -> Option<AnyElement> {
3812        let max_height_in_lines = ((height - POPOVER_Y_PADDING) / line_height).floor() as u32;
3813        self.editor.update(cx, |editor, cx| {
3814            editor.render_context_menu(&self.style, max_height_in_lines, y_flipped, window, cx)
3815        })
3816    }
3817
3818    fn render_context_menu_aside(
3819        &self,
3820        max_size: Size<Pixels>,
3821        window: &mut Window,
3822        cx: &mut App,
3823    ) -> Option<AnyElement> {
3824        if max_size.width < px(100.) || max_size.height < px(12.) {
3825            None
3826        } else {
3827            self.editor.update(cx, |editor, cx| {
3828                editor.render_context_menu_aside(max_size, window, cx)
3829            })
3830        }
3831    }
3832
3833    fn layout_mouse_context_menu(
3834        &self,
3835        editor_snapshot: &EditorSnapshot,
3836        visible_range: Range<DisplayRow>,
3837        content_origin: gpui::Point<Pixels>,
3838        window: &mut Window,
3839        cx: &mut App,
3840    ) -> Option<AnyElement> {
3841        let position = self.editor.update(cx, |editor, _cx| {
3842            let visible_start_point = editor.display_to_pixel_point(
3843                DisplayPoint::new(visible_range.start, 0),
3844                editor_snapshot,
3845                window,
3846            )?;
3847            let visible_end_point = editor.display_to_pixel_point(
3848                DisplayPoint::new(visible_range.end, 0),
3849                editor_snapshot,
3850                window,
3851            )?;
3852
3853            let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
3854            let (source_display_point, position) = match mouse_context_menu.position {
3855                MenuPosition::PinnedToScreen(point) => (None, point),
3856                MenuPosition::PinnedToEditor { source, offset } => {
3857                    let source_display_point = source.to_display_point(editor_snapshot);
3858                    let source_point = editor.to_pixel_point(source, editor_snapshot, window)?;
3859                    let position = content_origin + source_point + offset;
3860                    (Some(source_display_point), position)
3861                }
3862            };
3863
3864            let source_included = source_display_point.map_or(true, |source_display_point| {
3865                visible_range
3866                    .to_inclusive()
3867                    .contains(&source_display_point.row())
3868            });
3869            let position_included =
3870                visible_start_point.y <= position.y && position.y <= visible_end_point.y;
3871            if !source_included && !position_included {
3872                None
3873            } else {
3874                Some(position)
3875            }
3876        })?;
3877
3878        let text_style = TextStyleRefinement {
3879            line_height: Some(DefiniteLength::Fraction(
3880                BufferLineHeight::Comfortable.value(),
3881            )),
3882            ..Default::default()
3883        };
3884        window.with_text_style(Some(text_style), |window| {
3885            let mut element = self.editor.update(cx, |editor, _| {
3886                let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
3887                let context_menu = mouse_context_menu.context_menu.clone();
3888
3889                Some(
3890                    deferred(
3891                        anchored()
3892                            .position(position)
3893                            .child(context_menu)
3894                            .anchor(Corner::TopLeft)
3895                            .snap_to_window_with_margin(px(8.)),
3896                    )
3897                    .with_priority(1)
3898                    .into_any(),
3899                )
3900            })?;
3901
3902            element.prepaint_as_root(position, AvailableSpace::min_size(), window, cx);
3903            Some(element)
3904        })
3905    }
3906
3907    fn layout_hover_popovers(
3908        &self,
3909        snapshot: &EditorSnapshot,
3910        hitbox: &Hitbox,
3911        text_hitbox: &Hitbox,
3912        visible_display_row_range: Range<DisplayRow>,
3913        content_origin: gpui::Point<Pixels>,
3914        scroll_pixel_position: gpui::Point<Pixels>,
3915        line_layouts: &[LineWithInvisibles],
3916        line_height: Pixels,
3917        em_width: Pixels,
3918        window: &mut Window,
3919        cx: &mut App,
3920    ) {
3921        struct MeasuredHoverPopover {
3922            element: AnyElement,
3923            size: Size<Pixels>,
3924            horizontal_offset: Pixels,
3925        }
3926
3927        let max_size = size(
3928            (120. * em_width) // Default size
3929                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
3930                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
3931            (16. * line_height) // Default size
3932                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
3933                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
3934        );
3935
3936        let hover_popovers = self.editor.update(cx, |editor, cx| {
3937            editor
3938                .hover_state
3939                .render(snapshot, visible_display_row_range.clone(), max_size, cx)
3940        });
3941        let Some((position, hover_popovers)) = hover_popovers else {
3942            return;
3943        };
3944
3945        // This is safe because we check on layout whether the required row is available
3946        let hovered_row_layout =
3947            &line_layouts[position.row().minus(visible_display_row_range.start) as usize];
3948
3949        // Compute Hovered Point
3950        let x =
3951            hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
3952        let y = position.row().as_f32() * line_height - scroll_pixel_position.y;
3953        let hovered_point = content_origin + point(x, y);
3954
3955        let mut overall_height = Pixels::ZERO;
3956        let mut measured_hover_popovers = Vec::new();
3957        for mut hover_popover in hover_popovers {
3958            let size = hover_popover.layout_as_root(AvailableSpace::min_size(), window, cx);
3959            let horizontal_offset =
3960                (text_hitbox.top_right().x - (hovered_point.x + size.width)).min(Pixels::ZERO);
3961
3962            overall_height += HOVER_POPOVER_GAP + size.height;
3963
3964            measured_hover_popovers.push(MeasuredHoverPopover {
3965                element: hover_popover,
3966                size,
3967                horizontal_offset,
3968            });
3969        }
3970        overall_height += HOVER_POPOVER_GAP;
3971
3972        fn draw_occluder(
3973            width: Pixels,
3974            origin: gpui::Point<Pixels>,
3975            window: &mut Window,
3976            cx: &mut App,
3977        ) {
3978            let mut occlusion = div()
3979                .size_full()
3980                .occlude()
3981                .on_mouse_move(|_, _, cx| cx.stop_propagation())
3982                .into_any_element();
3983            occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), window, cx);
3984            window.defer_draw(occlusion, origin, 2);
3985        }
3986
3987        if hovered_point.y > overall_height {
3988            // There is enough space above. Render popovers above the hovered point
3989            let mut current_y = hovered_point.y;
3990            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
3991                let size = popover.size;
3992                let popover_origin = point(
3993                    hovered_point.x + popover.horizontal_offset,
3994                    current_y - size.height,
3995                );
3996
3997                window.defer_draw(popover.element, popover_origin, 2);
3998                if position != itertools::Position::Last {
3999                    let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
4000                    draw_occluder(size.width, origin, window, cx);
4001                }
4002
4003                current_y = popover_origin.y - HOVER_POPOVER_GAP;
4004            }
4005        } else {
4006            // There is not enough space above. Render popovers below the hovered point
4007            let mut current_y = hovered_point.y + line_height;
4008            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
4009                let size = popover.size;
4010                let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
4011
4012                window.defer_draw(popover.element, popover_origin, 2);
4013                if position != itertools::Position::Last {
4014                    let origin = point(popover_origin.x, popover_origin.y + size.height);
4015                    draw_occluder(size.width, origin, window, cx);
4016                }
4017
4018                current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
4019            }
4020        }
4021    }
4022
4023    fn layout_diff_hunk_controls(
4024        &self,
4025        row_range: Range<DisplayRow>,
4026        row_infos: &[RowInfo],
4027        text_hitbox: &Hitbox,
4028        position_map: &PositionMap,
4029        newest_cursor_position: Option<DisplayPoint>,
4030        line_height: Pixels,
4031        scroll_pixel_position: gpui::Point<Pixels>,
4032        display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
4033        editor: Entity<Editor>,
4034        window: &mut Window,
4035        cx: &mut App,
4036    ) -> Vec<AnyElement> {
4037        let point_for_position = position_map.point_for_position(window.mouse_position());
4038
4039        let mut controls = vec![];
4040
4041        let active_positions = [
4042            Some(point_for_position.previous_valid),
4043            newest_cursor_position,
4044        ];
4045
4046        for (hunk, _) in display_hunks {
4047            if let DisplayDiffHunk::Unfolded {
4048                display_row_range,
4049                multi_buffer_range,
4050                status,
4051                is_created_file,
4052                ..
4053            } = &hunk
4054            {
4055                if display_row_range.start < row_range.start
4056                    || display_row_range.start >= row_range.end
4057                {
4058                    continue;
4059                }
4060                let row_ix = (display_row_range.start - row_range.start).0 as usize;
4061                if row_infos[row_ix].diff_status.is_none() {
4062                    continue;
4063                }
4064                if row_infos[row_ix]
4065                    .diff_status
4066                    .is_some_and(|status| status.is_added())
4067                    && !status.is_added()
4068                {
4069                    continue;
4070                }
4071                if active_positions
4072                    .iter()
4073                    .any(|p| p.map_or(false, |p| display_row_range.contains(&p.row())))
4074                {
4075                    let y = display_row_range.start.as_f32() * line_height
4076                        + text_hitbox.bounds.top()
4077                        - scroll_pixel_position.y;
4078
4079                    let mut element = diff_hunk_controls(
4080                        display_row_range.start.0,
4081                        status,
4082                        multi_buffer_range.clone(),
4083                        *is_created_file,
4084                        line_height,
4085                        &editor,
4086                        cx,
4087                    );
4088                    let size =
4089                        element.layout_as_root(size(px(100.0), line_height).into(), window, cx);
4090
4091                    let x = text_hitbox.bounds.right()
4092                        - self.style.scrollbar_width
4093                        - px(10.)
4094                        - size.width;
4095
4096                    window.with_absolute_element_offset(gpui::Point::new(x, y), |window| {
4097                        element.prepaint(window, cx)
4098                    });
4099                    controls.push(element);
4100                }
4101            }
4102        }
4103
4104        controls
4105    }
4106
4107    fn layout_signature_help(
4108        &self,
4109        hitbox: &Hitbox,
4110        content_origin: gpui::Point<Pixels>,
4111        scroll_pixel_position: gpui::Point<Pixels>,
4112        newest_selection_head: Option<DisplayPoint>,
4113        start_row: DisplayRow,
4114        line_layouts: &[LineWithInvisibles],
4115        line_height: Pixels,
4116        em_width: Pixels,
4117        window: &mut Window,
4118        cx: &mut App,
4119    ) {
4120        if !self.editor.focus_handle(cx).is_focused(window) {
4121            return;
4122        }
4123        let Some(newest_selection_head) = newest_selection_head else {
4124            return;
4125        };
4126        let selection_row = newest_selection_head.row();
4127        if selection_row < start_row {
4128            return;
4129        }
4130        let Some(cursor_row_layout) = line_layouts.get(selection_row.minus(start_row) as usize)
4131        else {
4132            return;
4133        };
4134
4135        let start_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
4136            - scroll_pixel_position.x
4137            + content_origin.x;
4138        let start_y =
4139            selection_row.as_f32() * line_height + content_origin.y - scroll_pixel_position.y;
4140
4141        let max_size = size(
4142            (120. * em_width) // Default size
4143                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
4144                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
4145            (16. * line_height) // Default size
4146                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
4147                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
4148        );
4149
4150        let maybe_element = self.editor.update(cx, |editor, cx| {
4151            if let Some(popover) = editor.signature_help_state.popover_mut() {
4152                let element = popover.render(max_size, cx);
4153                Some(element)
4154            } else {
4155                None
4156            }
4157        });
4158        if let Some(mut element) = maybe_element {
4159            let window_size = window.viewport_size();
4160            let size = element.layout_as_root(Size::<AvailableSpace>::default(), window, cx);
4161            let mut point = point(start_x, start_y - size.height);
4162
4163            // Adjusting to ensure the popover does not overflow in the X-axis direction.
4164            if point.x + size.width >= window_size.width {
4165                point.x = window_size.width - size.width;
4166            }
4167
4168            window.defer_draw(element, point, 1)
4169        }
4170    }
4171
4172    fn paint_background(&self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
4173        window.paint_layer(layout.hitbox.bounds, |window| {
4174            let scroll_top = layout.position_map.snapshot.scroll_position().y;
4175            let gutter_bg = cx.theme().colors().editor_gutter_background;
4176            window.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
4177            window.paint_quad(fill(
4178                layout.position_map.text_hitbox.bounds,
4179                self.style.background,
4180            ));
4181
4182            if let EditorMode::Full = layout.mode {
4183                let mut active_rows = layout.active_rows.iter().peekable();
4184                while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
4185                    let mut end_row = start_row.0;
4186                    while active_rows
4187                        .peek()
4188                        .map_or(false, |(active_row, has_selection)| {
4189                            active_row.0 == end_row + 1
4190                                && has_selection.selection == contains_non_empty_selection.selection
4191                        })
4192                    {
4193                        active_rows.next().unwrap();
4194                        end_row += 1;
4195                    }
4196
4197                    if !contains_non_empty_selection.selection {
4198                        let highlight_h_range =
4199                            match layout.position_map.snapshot.current_line_highlight {
4200                                CurrentLineHighlight::Gutter => Some(Range {
4201                                    start: layout.hitbox.left(),
4202                                    end: layout.gutter_hitbox.right(),
4203                                }),
4204                                CurrentLineHighlight::Line => Some(Range {
4205                                    start: layout.position_map.text_hitbox.bounds.left(),
4206                                    end: layout.position_map.text_hitbox.bounds.right(),
4207                                }),
4208                                CurrentLineHighlight::All => Some(Range {
4209                                    start: layout.hitbox.left(),
4210                                    end: layout.hitbox.right(),
4211                                }),
4212                                CurrentLineHighlight::None => None,
4213                            };
4214                        if let Some(range) = highlight_h_range {
4215                            let active_line_bg = cx.theme().colors().editor_active_line_background;
4216                            let bounds = Bounds {
4217                                origin: point(
4218                                    range.start,
4219                                    layout.hitbox.origin.y
4220                                        + (start_row.as_f32() - scroll_top)
4221                                            * layout.position_map.line_height,
4222                                ),
4223                                size: size(
4224                                    range.end - range.start,
4225                                    layout.position_map.line_height
4226                                        * (end_row - start_row.0 + 1) as f32,
4227                                ),
4228                            };
4229                            window.paint_quad(fill(bounds, active_line_bg));
4230                        }
4231                    }
4232                }
4233
4234                let mut paint_highlight = |highlight_row_start: DisplayRow,
4235                                           highlight_row_end: DisplayRow,
4236                                           highlight: crate::LineHighlight,
4237                                           edges| {
4238                    let origin = point(
4239                        layout.hitbox.origin.x,
4240                        layout.hitbox.origin.y
4241                            + (highlight_row_start.as_f32() - scroll_top)
4242                                * layout.position_map.line_height,
4243                    );
4244                    let size = size(
4245                        layout.hitbox.size.width,
4246                        layout.position_map.line_height
4247                            * highlight_row_end.next_row().minus(highlight_row_start) as f32,
4248                    );
4249                    let mut quad = fill(Bounds { origin, size }, highlight.background);
4250                    if let Some(border_color) = highlight.border {
4251                        quad.border_color = border_color;
4252                        quad.border_widths = edges
4253                    }
4254                    window.paint_quad(quad);
4255                };
4256
4257                let mut current_paint: Option<(LineHighlight, Range<DisplayRow>, Edges<Pixels>)> =
4258                    None;
4259                for (&new_row, &new_background) in &layout.highlighted_rows {
4260                    match &mut current_paint {
4261                        Some((current_background, current_range, mut edges)) => {
4262                            let current_background = *current_background;
4263                            let new_range_started = current_background != new_background
4264                                || current_range.end.next_row() != new_row;
4265                            if new_range_started {
4266                                if current_range.end.next_row() == new_row {
4267                                    edges.bottom = px(0.);
4268                                };
4269                                paint_highlight(
4270                                    current_range.start,
4271                                    current_range.end,
4272                                    current_background,
4273                                    edges,
4274                                );
4275                                let edges = Edges {
4276                                    top: if current_range.end.next_row() != new_row {
4277                                        px(1.)
4278                                    } else {
4279                                        px(0.)
4280                                    },
4281                                    bottom: px(1.),
4282                                    ..Default::default()
4283                                };
4284                                current_paint = Some((new_background, new_row..new_row, edges));
4285                                continue;
4286                            } else {
4287                                current_range.end = current_range.end.next_row();
4288                            }
4289                        }
4290                        None => {
4291                            let edges = Edges {
4292                                top: px(1.),
4293                                bottom: px(1.),
4294                                ..Default::default()
4295                            };
4296                            current_paint = Some((new_background, new_row..new_row, edges))
4297                        }
4298                    };
4299                }
4300                if let Some((color, range, edges)) = current_paint {
4301                    paint_highlight(range.start, range.end, color, edges);
4302                }
4303
4304                let scroll_left =
4305                    layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
4306
4307                for (wrap_position, active) in layout.wrap_guides.iter() {
4308                    let x = (layout.position_map.text_hitbox.origin.x
4309                        + *wrap_position
4310                        + layout.position_map.em_width / 2.)
4311                        - scroll_left;
4312
4313                    let show_scrollbars = {
4314                        let (scrollbar_x, scrollbar_y) = &layout.scrollbars_layout.as_xy();
4315
4316                        scrollbar_x.as_ref().map_or(false, |sx| sx.visible)
4317                            || scrollbar_y.as_ref().map_or(false, |sy| sy.visible)
4318                    };
4319
4320                    if x < layout.position_map.text_hitbox.origin.x
4321                        || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
4322                    {
4323                        continue;
4324                    }
4325
4326                    let color = if *active {
4327                        cx.theme().colors().editor_active_wrap_guide
4328                    } else {
4329                        cx.theme().colors().editor_wrap_guide
4330                    };
4331                    window.paint_quad(fill(
4332                        Bounds {
4333                            origin: point(x, layout.position_map.text_hitbox.origin.y),
4334                            size: size(px(1.), layout.position_map.text_hitbox.size.height),
4335                        },
4336                        color,
4337                    ));
4338                }
4339            }
4340        })
4341    }
4342
4343    fn paint_indent_guides(
4344        &mut self,
4345        layout: &mut EditorLayout,
4346        window: &mut Window,
4347        cx: &mut App,
4348    ) {
4349        let Some(indent_guides) = &layout.indent_guides else {
4350            return;
4351        };
4352
4353        let faded_color = |color: Hsla, alpha: f32| {
4354            let mut faded = color;
4355            faded.a = alpha;
4356            faded
4357        };
4358
4359        for indent_guide in indent_guides {
4360            let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
4361            let settings = indent_guide.settings;
4362
4363            // TODO fixed for now, expose them through themes later
4364            const INDENT_AWARE_ALPHA: f32 = 0.2;
4365            const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
4366            const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
4367            const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
4368
4369            let line_color = match (settings.coloring, indent_guide.active) {
4370                (IndentGuideColoring::Disabled, _) => None,
4371                (IndentGuideColoring::Fixed, false) => {
4372                    Some(cx.theme().colors().editor_indent_guide)
4373                }
4374                (IndentGuideColoring::Fixed, true) => {
4375                    Some(cx.theme().colors().editor_indent_guide_active)
4376                }
4377                (IndentGuideColoring::IndentAware, false) => {
4378                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
4379                }
4380                (IndentGuideColoring::IndentAware, true) => {
4381                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
4382                }
4383            };
4384
4385            let background_color = match (settings.background_coloring, indent_guide.active) {
4386                (IndentGuideBackgroundColoring::Disabled, _) => None,
4387                (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
4388                    indent_accent_colors,
4389                    INDENT_AWARE_BACKGROUND_ALPHA,
4390                )),
4391                (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
4392                    indent_accent_colors,
4393                    INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
4394                )),
4395            };
4396
4397            let requested_line_width = if indent_guide.active {
4398                settings.active_line_width
4399            } else {
4400                settings.line_width
4401            }
4402            .clamp(1, 10);
4403            let mut line_indicator_width = 0.;
4404            if let Some(color) = line_color {
4405                window.paint_quad(fill(
4406                    Bounds {
4407                        origin: indent_guide.origin,
4408                        size: size(px(requested_line_width as f32), indent_guide.length),
4409                    },
4410                    color,
4411                ));
4412                line_indicator_width = requested_line_width as f32;
4413            }
4414
4415            if let Some(color) = background_color {
4416                let width = indent_guide.single_indent_width - px(line_indicator_width);
4417                window.paint_quad(fill(
4418                    Bounds {
4419                        origin: point(
4420                            indent_guide.origin.x + px(line_indicator_width),
4421                            indent_guide.origin.y,
4422                        ),
4423                        size: size(width, indent_guide.length),
4424                    },
4425                    color,
4426                ));
4427            }
4428        }
4429    }
4430
4431    fn paint_line_numbers(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4432        let is_singleton = self.editor.read(cx).is_singleton(cx);
4433
4434        let line_height = layout.position_map.line_height;
4435        window.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
4436
4437        for LineNumberLayout {
4438            shaped_line,
4439            hitbox,
4440        } in layout.line_numbers.values()
4441        {
4442            let Some(hitbox) = hitbox else {
4443                continue;
4444            };
4445
4446            let Some(()) = (if !is_singleton && hitbox.is_hovered(window) {
4447                let color = cx.theme().colors().editor_hover_line_number;
4448
4449                let Some(line) = self
4450                    .shape_line_number(shaped_line.text.clone(), color, window)
4451                    .log_err()
4452                else {
4453                    continue;
4454                };
4455
4456                line.paint(hitbox.origin, line_height, window, cx).log_err()
4457            } else {
4458                shaped_line
4459                    .paint(hitbox.origin, line_height, window, cx)
4460                    .log_err()
4461            }) else {
4462                continue;
4463            };
4464
4465            // In singleton buffers, we select corresponding lines on the line number click, so use | -like cursor.
4466            // In multi buffers, we open file at the line number clicked, so use a pointing hand cursor.
4467            if is_singleton {
4468                window.set_cursor_style(CursorStyle::IBeam, &hitbox);
4469            } else {
4470                window.set_cursor_style(CursorStyle::PointingHand, &hitbox);
4471            }
4472        }
4473    }
4474
4475    fn paint_gutter_diff_hunks(layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4476        if layout.display_hunks.is_empty() {
4477            return;
4478        }
4479
4480        let line_height = layout.position_map.line_height;
4481        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4482            for (hunk, hitbox) in &layout.display_hunks {
4483                let hunk_to_paint = match hunk {
4484                    DisplayDiffHunk::Folded { .. } => {
4485                        let hunk_bounds = Self::diff_hunk_bounds(
4486                            &layout.position_map.snapshot,
4487                            line_height,
4488                            layout.gutter_hitbox.bounds,
4489                            &hunk,
4490                        );
4491                        Some((
4492                            hunk_bounds,
4493                            cx.theme().colors().version_control_modified,
4494                            Corners::all(px(0.)),
4495                            DiffHunkStatus::modified_none(),
4496                        ))
4497                    }
4498                    DisplayDiffHunk::Unfolded {
4499                        status,
4500                        display_row_range,
4501                        ..
4502                    } => hitbox.as_ref().map(|hunk_hitbox| match status.kind {
4503                        DiffHunkStatusKind::Added => (
4504                            hunk_hitbox.bounds,
4505                            cx.theme().colors().version_control_added,
4506                            Corners::all(px(0.)),
4507                            *status,
4508                        ),
4509                        DiffHunkStatusKind::Modified => (
4510                            hunk_hitbox.bounds,
4511                            cx.theme().colors().version_control_modified,
4512                            Corners::all(px(0.)),
4513                            *status,
4514                        ),
4515                        DiffHunkStatusKind::Deleted if !display_row_range.is_empty() => (
4516                            hunk_hitbox.bounds,
4517                            cx.theme().colors().version_control_deleted,
4518                            Corners::all(px(0.)),
4519                            *status,
4520                        ),
4521                        DiffHunkStatusKind::Deleted => (
4522                            Bounds::new(
4523                                point(
4524                                    hunk_hitbox.origin.x - hunk_hitbox.size.width,
4525                                    hunk_hitbox.origin.y,
4526                                ),
4527                                size(hunk_hitbox.size.width * px(2.), hunk_hitbox.size.height),
4528                            ),
4529                            cx.theme().colors().version_control_deleted,
4530                            Corners::all(1. * line_height),
4531                            *status,
4532                        ),
4533                    }),
4534                };
4535
4536                if let Some((hunk_bounds, background_color, corner_radii, status)) = hunk_to_paint {
4537                    // Flatten the background color with the editor color to prevent
4538                    // elements below transparent hunks from showing through
4539                    let flattened_background_color = cx
4540                        .theme()
4541                        .colors()
4542                        .editor_background
4543                        .blend(background_color);
4544
4545                    if !Self::diff_hunk_hollow(status, cx) {
4546                        window.paint_quad(quad(
4547                            hunk_bounds,
4548                            corner_radii,
4549                            flattened_background_color,
4550                            Edges::default(),
4551                            transparent_black(),
4552                        ));
4553                    } else {
4554                        let flattened_unstaged_background_color = cx
4555                            .theme()
4556                            .colors()
4557                            .editor_background
4558                            .blend(background_color.opacity(0.3));
4559
4560                        window.paint_quad(quad(
4561                            hunk_bounds,
4562                            corner_radii,
4563                            flattened_unstaged_background_color,
4564                            Edges::all(Pixels(1.0)),
4565                            flattened_background_color,
4566                        ));
4567                    }
4568                }
4569            }
4570        });
4571    }
4572
4573    fn gutter_strip_width(line_height: Pixels) -> Pixels {
4574        (0.275 * line_height).floor()
4575    }
4576
4577    fn diff_hunk_bounds(
4578        snapshot: &EditorSnapshot,
4579        line_height: Pixels,
4580        gutter_bounds: Bounds<Pixels>,
4581        hunk: &DisplayDiffHunk,
4582    ) -> Bounds<Pixels> {
4583        let scroll_position = snapshot.scroll_position();
4584        let scroll_top = scroll_position.y * line_height;
4585        let gutter_strip_width = Self::gutter_strip_width(line_height);
4586
4587        match hunk {
4588            DisplayDiffHunk::Folded { display_row, .. } => {
4589                let start_y = display_row.as_f32() * line_height - scroll_top;
4590                let end_y = start_y + line_height;
4591                let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4592                let highlight_size = size(gutter_strip_width, end_y - start_y);
4593                Bounds::new(highlight_origin, highlight_size)
4594            }
4595            DisplayDiffHunk::Unfolded {
4596                display_row_range,
4597                status,
4598                ..
4599            } => {
4600                if status.is_deleted() && display_row_range.is_empty() {
4601                    let row = display_row_range.start;
4602
4603                    let offset = line_height / 2.;
4604                    let start_y = row.as_f32() * line_height - offset - scroll_top;
4605                    let end_y = start_y + line_height;
4606
4607                    let width = (0.35 * line_height).floor();
4608                    let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4609                    let highlight_size = size(width, end_y - start_y);
4610                    Bounds::new(highlight_origin, highlight_size)
4611                } else {
4612                    let start_row = display_row_range.start;
4613                    let end_row = display_row_range.end;
4614                    // If we're in a multibuffer, row range span might include an
4615                    // excerpt header, so if we were to draw the marker straight away,
4616                    // the hunk might include the rows of that header.
4617                    // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
4618                    // Instead, we simply check whether the range we're dealing with includes
4619                    // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
4620                    let end_row_in_current_excerpt = snapshot
4621                        .blocks_in_range(start_row..end_row)
4622                        .find_map(|(start_row, block)| {
4623                            if matches!(block, Block::ExcerptBoundary { .. }) {
4624                                Some(start_row)
4625                            } else {
4626                                None
4627                            }
4628                        })
4629                        .unwrap_or(end_row);
4630
4631                    let start_y = start_row.as_f32() * line_height - scroll_top;
4632                    let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
4633
4634                    let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4635                    let highlight_size = size(gutter_strip_width, end_y - start_y);
4636                    Bounds::new(highlight_origin, highlight_size)
4637                }
4638            }
4639        }
4640    }
4641
4642    fn paint_gutter_indicators(
4643        &self,
4644        layout: &mut EditorLayout,
4645        window: &mut Window,
4646        cx: &mut App,
4647    ) {
4648        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4649            window.with_element_namespace("crease_toggles", |window| {
4650                for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
4651                    crease_toggle.paint(window, cx);
4652                }
4653            });
4654
4655            window.with_element_namespace("expand_toggles", |window| {
4656                for (expand_toggle, _) in layout.expand_toggles.iter_mut().flatten() {
4657                    expand_toggle.paint(window, cx);
4658                }
4659            });
4660
4661            for breakpoint in layout.breakpoints.iter_mut() {
4662                breakpoint.paint(window, cx);
4663            }
4664
4665            for test_indicator in layout.test_indicators.iter_mut() {
4666                test_indicator.paint(window, cx);
4667            }
4668
4669            if let Some(indicator) = layout.code_actions_indicator.as_mut() {
4670                indicator.paint(window, cx);
4671            }
4672        });
4673    }
4674
4675    fn paint_gutter_highlights(
4676        &self,
4677        layout: &mut EditorLayout,
4678        window: &mut Window,
4679        cx: &mut App,
4680    ) {
4681        for (_, hunk_hitbox) in &layout.display_hunks {
4682            if let Some(hunk_hitbox) = hunk_hitbox {
4683                if !self
4684                    .editor
4685                    .read(cx)
4686                    .buffer()
4687                    .read(cx)
4688                    .all_diff_hunks_expanded()
4689                {
4690                    window.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
4691                }
4692            }
4693        }
4694
4695        let show_git_gutter = layout
4696            .position_map
4697            .snapshot
4698            .show_git_diff_gutter
4699            .unwrap_or_else(|| {
4700                matches!(
4701                    ProjectSettings::get_global(cx).git.git_gutter,
4702                    Some(GitGutterSetting::TrackedFiles)
4703                )
4704            });
4705        if show_git_gutter {
4706            Self::paint_gutter_diff_hunks(layout, window, cx)
4707        }
4708
4709        let highlight_width = 0.275 * layout.position_map.line_height;
4710        let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
4711        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4712            for (range, color) in &layout.highlighted_gutter_ranges {
4713                let start_row = if range.start.row() < layout.visible_display_row_range.start {
4714                    layout.visible_display_row_range.start - DisplayRow(1)
4715                } else {
4716                    range.start.row()
4717                };
4718                let end_row = if range.end.row() > layout.visible_display_row_range.end {
4719                    layout.visible_display_row_range.end + DisplayRow(1)
4720                } else {
4721                    range.end.row()
4722                };
4723
4724                let start_y = layout.gutter_hitbox.top()
4725                    + start_row.0 as f32 * layout.position_map.line_height
4726                    - layout.position_map.scroll_pixel_position.y;
4727                let end_y = layout.gutter_hitbox.top()
4728                    + (end_row.0 + 1) as f32 * layout.position_map.line_height
4729                    - layout.position_map.scroll_pixel_position.y;
4730                let bounds = Bounds::from_corners(
4731                    point(layout.gutter_hitbox.left(), start_y),
4732                    point(layout.gutter_hitbox.left() + highlight_width, end_y),
4733                );
4734                window.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
4735            }
4736        });
4737    }
4738
4739    fn paint_blamed_display_rows(
4740        &self,
4741        layout: &mut EditorLayout,
4742        window: &mut Window,
4743        cx: &mut App,
4744    ) {
4745        let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
4746            return;
4747        };
4748
4749        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4750            for mut blame_element in blamed_display_rows.into_iter() {
4751                blame_element.paint(window, cx);
4752            }
4753        })
4754    }
4755
4756    fn paint_text(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4757        window.with_content_mask(
4758            Some(ContentMask {
4759                bounds: layout.position_map.text_hitbox.bounds,
4760            }),
4761            |window| {
4762                let cursor_style = if self
4763                    .editor
4764                    .read(cx)
4765                    .hovered_link_state
4766                    .as_ref()
4767                    .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
4768                {
4769                    CursorStyle::PointingHand
4770                } else {
4771                    CursorStyle::IBeam
4772                };
4773                window.set_cursor_style(cursor_style, &layout.position_map.text_hitbox);
4774
4775                self.paint_lines_background(layout, window, cx);
4776                let invisible_display_ranges = self.paint_highlights(layout, window);
4777                self.paint_lines(&invisible_display_ranges, layout, window, cx);
4778                self.paint_redactions(layout, window);
4779                self.paint_cursors(layout, window, cx);
4780                self.paint_inline_diagnostics(layout, window, cx);
4781                self.paint_inline_blame(layout, window, cx);
4782                self.paint_diff_hunk_controls(layout, window, cx);
4783                window.with_element_namespace("crease_trailers", |window| {
4784                    for trailer in layout.crease_trailers.iter_mut().flatten() {
4785                        trailer.element.paint(window, cx);
4786                    }
4787                });
4788            },
4789        )
4790    }
4791
4792    fn paint_highlights(
4793        &mut self,
4794        layout: &mut EditorLayout,
4795        window: &mut Window,
4796    ) -> SmallVec<[Range<DisplayPoint>; 32]> {
4797        window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
4798            let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
4799            let line_end_overshoot = 0.15 * layout.position_map.line_height;
4800            for (range, color) in &layout.highlighted_ranges {
4801                self.paint_highlighted_range(
4802                    range.clone(),
4803                    *color,
4804                    Pixels::ZERO,
4805                    line_end_overshoot,
4806                    layout,
4807                    window,
4808                );
4809            }
4810
4811            let corner_radius = 0.15 * layout.position_map.line_height;
4812
4813            for (player_color, selections) in &layout.selections {
4814                for selection in selections.iter() {
4815                    self.paint_highlighted_range(
4816                        selection.range.clone(),
4817                        player_color.selection,
4818                        corner_radius,
4819                        corner_radius * 2.,
4820                        layout,
4821                        window,
4822                    );
4823
4824                    if selection.is_local && !selection.range.is_empty() {
4825                        invisible_display_ranges.push(selection.range.clone());
4826                    }
4827                }
4828            }
4829            invisible_display_ranges
4830        })
4831    }
4832
4833    fn paint_lines(
4834        &mut self,
4835        invisible_display_ranges: &[Range<DisplayPoint>],
4836        layout: &mut EditorLayout,
4837        window: &mut Window,
4838        cx: &mut App,
4839    ) {
4840        let whitespace_setting = self
4841            .editor
4842            .read(cx)
4843            .buffer
4844            .read(cx)
4845            .language_settings(cx)
4846            .show_whitespaces;
4847
4848        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
4849            let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
4850            line_with_invisibles.draw(
4851                layout,
4852                row,
4853                layout.content_origin,
4854                whitespace_setting,
4855                invisible_display_ranges,
4856                window,
4857                cx,
4858            )
4859        }
4860
4861        for line_element in &mut layout.line_elements {
4862            line_element.paint(window, cx);
4863        }
4864    }
4865
4866    fn paint_lines_background(
4867        &mut self,
4868        layout: &mut EditorLayout,
4869        window: &mut Window,
4870        cx: &mut App,
4871    ) {
4872        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
4873            let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
4874            line_with_invisibles.draw_background(layout, row, layout.content_origin, window, cx);
4875        }
4876    }
4877
4878    fn paint_redactions(&mut self, layout: &EditorLayout, window: &mut Window) {
4879        if layout.redacted_ranges.is_empty() {
4880            return;
4881        }
4882
4883        let line_end_overshoot = layout.line_end_overshoot();
4884
4885        // A softer than perfect black
4886        let redaction_color = gpui::rgb(0x0e1111);
4887
4888        window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
4889            for range in layout.redacted_ranges.iter() {
4890                self.paint_highlighted_range(
4891                    range.clone(),
4892                    redaction_color.into(),
4893                    Pixels::ZERO,
4894                    line_end_overshoot,
4895                    layout,
4896                    window,
4897                );
4898            }
4899        });
4900    }
4901
4902    fn paint_cursors(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4903        for cursor in &mut layout.visible_cursors {
4904            cursor.paint(layout.content_origin, window, cx);
4905        }
4906    }
4907
4908    fn paint_scrollbars(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4909        let (scrollbar_x, scrollbar_y) = layout.scrollbars_layout.as_xy();
4910
4911        if let Some(scrollbar_layout) = scrollbar_x {
4912            let hitbox = scrollbar_layout.hitbox.clone();
4913            let text_unit_size = scrollbar_layout.text_unit_size;
4914            let visible_range = scrollbar_layout.visible_range.clone();
4915            let thumb_bounds = scrollbar_layout.thumb_bounds();
4916
4917            if scrollbar_layout.visible {
4918                window.paint_layer(hitbox.bounds, |window| {
4919                    window.paint_quad(quad(
4920                        hitbox.bounds,
4921                        Corners::default(),
4922                        cx.theme().colors().scrollbar_track_background,
4923                        Edges {
4924                            top: Pixels::ZERO,
4925                            right: Pixels::ZERO,
4926                            bottom: Pixels::ZERO,
4927                            left: Pixels::ZERO,
4928                        },
4929                        cx.theme().colors().scrollbar_track_border,
4930                    ));
4931
4932                    window.paint_quad(quad(
4933                        thumb_bounds,
4934                        Corners::default(),
4935                        cx.theme().colors().scrollbar_thumb_background,
4936                        Edges {
4937                            top: Pixels::ZERO,
4938                            right: Pixels::ZERO,
4939                            bottom: Pixels::ZERO,
4940                            left: ScrollbarLayout::BORDER_WIDTH,
4941                        },
4942                        cx.theme().colors().scrollbar_thumb_border,
4943                    ));
4944                })
4945            }
4946
4947            window.set_cursor_style(CursorStyle::Arrow, &hitbox);
4948
4949            window.on_mouse_event({
4950                let editor = self.editor.clone();
4951
4952                // there may be a way to avoid this clone
4953                let hitbox = hitbox.clone();
4954
4955                let mut mouse_position = window.mouse_position();
4956                move |event: &MouseMoveEvent, phase, window, cx| {
4957                    if phase == DispatchPhase::Capture {
4958                        return;
4959                    }
4960
4961                    editor.update(cx, |editor, cx| {
4962                        if event.pressed_button == Some(MouseButton::Left)
4963                            && editor
4964                                .scroll_manager
4965                                .is_dragging_scrollbar(Axis::Horizontal)
4966                        {
4967                            let x = mouse_position.x;
4968                            let new_x = event.position.x;
4969                            if (hitbox.left()..hitbox.right()).contains(&x) {
4970                                let mut position = editor.scroll_position(cx);
4971
4972                                position.x += (new_x - x) / text_unit_size;
4973                                if position.x < 0.0 {
4974                                    position.x = 0.0;
4975                                }
4976                                editor.set_scroll_position(position, window, cx);
4977                            }
4978
4979                            cx.stop_propagation();
4980                        } else {
4981                            editor.scroll_manager.set_is_dragging_scrollbar(
4982                                Axis::Horizontal,
4983                                false,
4984                                cx,
4985                            );
4986
4987                            if hitbox.is_hovered(window) {
4988                                editor.scroll_manager.show_scrollbar(window, cx);
4989                            }
4990                        }
4991                        mouse_position = event.position;
4992                    })
4993                }
4994            });
4995
4996            if self
4997                .editor
4998                .read(cx)
4999                .scroll_manager
5000                .is_dragging_scrollbar(Axis::Horizontal)
5001            {
5002                window.on_mouse_event({
5003                    let editor = self.editor.clone();
5004                    move |_: &MouseUpEvent, phase, _, cx| {
5005                        if phase == DispatchPhase::Capture {
5006                            return;
5007                        }
5008
5009                        editor.update(cx, |editor, cx| {
5010                            editor.scroll_manager.set_is_dragging_scrollbar(
5011                                Axis::Horizontal,
5012                                false,
5013                                cx,
5014                            );
5015                            cx.stop_propagation();
5016                        });
5017                    }
5018                });
5019            } else {
5020                window.on_mouse_event({
5021                    let editor = self.editor.clone();
5022
5023                    move |event: &MouseDownEvent, phase, window, cx| {
5024                        if phase == DispatchPhase::Capture || !hitbox.is_hovered(window) {
5025                            return;
5026                        }
5027
5028                        editor.update(cx, |editor, cx| {
5029                            editor.scroll_manager.set_is_dragging_scrollbar(
5030                                Axis::Horizontal,
5031                                true,
5032                                cx,
5033                            );
5034
5035                            let x = event.position.x;
5036
5037                            if x < thumb_bounds.left() || thumb_bounds.right() < x {
5038                                let center_row =
5039                                    ((x - hitbox.left()) / text_unit_size).round() as u32;
5040                                let top_row = center_row.saturating_sub(
5041                                    (visible_range.end - visible_range.start) as u32 / 2,
5042                                );
5043
5044                                let mut position = editor.scroll_position(cx);
5045                                position.x = top_row as f32;
5046
5047                                editor.set_scroll_position(position, window, cx);
5048                            } else {
5049                                editor.scroll_manager.show_scrollbar(window, cx);
5050                            }
5051
5052                            cx.stop_propagation();
5053                        });
5054                    }
5055                });
5056            }
5057        }
5058
5059        if let Some(scrollbar_layout) = scrollbar_y {
5060            let hitbox = scrollbar_layout.hitbox.clone();
5061            let text_unit_size = scrollbar_layout.text_unit_size;
5062            let visible_range = scrollbar_layout.visible_range.clone();
5063            let thumb_bounds = scrollbar_layout.thumb_bounds();
5064
5065            if scrollbar_layout.visible {
5066                window.paint_layer(hitbox.bounds, |window| {
5067                    window.paint_quad(quad(
5068                        hitbox.bounds,
5069                        Corners::default(),
5070                        cx.theme().colors().scrollbar_track_background,
5071                        Edges {
5072                            top: Pixels::ZERO,
5073                            right: Pixels::ZERO,
5074                            bottom: Pixels::ZERO,
5075                            left: ScrollbarLayout::BORDER_WIDTH,
5076                        },
5077                        cx.theme().colors().scrollbar_track_border,
5078                    ));
5079
5080                    let fast_markers =
5081                        self.collect_fast_scrollbar_markers(layout, &scrollbar_layout, cx);
5082                    // Refresh slow scrollbar markers in the background. Below, we paint whatever markers have already been computed.
5083                    self.refresh_slow_scrollbar_markers(layout, &scrollbar_layout, window, cx);
5084
5085                    let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
5086                    for marker in markers.iter().chain(&fast_markers) {
5087                        let mut marker = marker.clone();
5088                        marker.bounds.origin += hitbox.origin;
5089                        window.paint_quad(marker);
5090                    }
5091
5092                    window.paint_quad(quad(
5093                        thumb_bounds,
5094                        Corners::default(),
5095                        cx.theme().colors().scrollbar_thumb_background,
5096                        Edges {
5097                            top: Pixels::ZERO,
5098                            right: Pixels::ZERO,
5099                            bottom: Pixels::ZERO,
5100                            left: ScrollbarLayout::BORDER_WIDTH,
5101                        },
5102                        cx.theme().colors().scrollbar_thumb_border,
5103                    ));
5104                });
5105            }
5106
5107            window.set_cursor_style(CursorStyle::Arrow, &hitbox);
5108
5109            window.on_mouse_event({
5110                let editor = self.editor.clone();
5111
5112                let hitbox = hitbox.clone();
5113
5114                let mut mouse_position = window.mouse_position();
5115                move |event: &MouseMoveEvent, phase, window, cx| {
5116                    if phase == DispatchPhase::Capture {
5117                        return;
5118                    }
5119
5120                    editor.update(cx, |editor, cx| {
5121                        if event.pressed_button == Some(MouseButton::Left)
5122                            && editor.scroll_manager.is_dragging_scrollbar(Axis::Vertical)
5123                        {
5124                            let y = mouse_position.y;
5125                            let new_y = event.position.y;
5126                            if (hitbox.top()..hitbox.bottom()).contains(&y) {
5127                                let mut position = editor.scroll_position(cx);
5128                                position.y += (new_y - y) / text_unit_size;
5129                                if position.y < 0.0 {
5130                                    position.y = 0.0;
5131                                }
5132                                editor.set_scroll_position(position, window, cx);
5133                            }
5134                        } else {
5135                            editor.scroll_manager.set_is_dragging_scrollbar(
5136                                Axis::Vertical,
5137                                false,
5138                                cx,
5139                            );
5140
5141                            if hitbox.is_hovered(window) {
5142                                editor.scroll_manager.show_scrollbar(window, cx);
5143                            }
5144                        }
5145                        mouse_position = event.position;
5146                    })
5147                }
5148            });
5149
5150            if self
5151                .editor
5152                .read(cx)
5153                .scroll_manager
5154                .is_dragging_scrollbar(Axis::Vertical)
5155            {
5156                window.on_mouse_event({
5157                    let editor = self.editor.clone();
5158                    move |_: &MouseUpEvent, phase, _, cx| {
5159                        if phase == DispatchPhase::Capture {
5160                            return;
5161                        }
5162
5163                        editor.update(cx, |editor, cx| {
5164                            editor.scroll_manager.set_is_dragging_scrollbar(
5165                                Axis::Vertical,
5166                                false,
5167                                cx,
5168                            );
5169                            cx.stop_propagation();
5170                        });
5171                    }
5172                });
5173            } else {
5174                window.on_mouse_event({
5175                    let editor = self.editor.clone();
5176
5177                    move |event: &MouseDownEvent, phase, window, cx| {
5178                        if phase == DispatchPhase::Capture || !hitbox.is_hovered(window) {
5179                            return;
5180                        }
5181
5182                        editor.update(cx, |editor, cx| {
5183                            editor.scroll_manager.set_is_dragging_scrollbar(
5184                                Axis::Vertical,
5185                                true,
5186                                cx,
5187                            );
5188
5189                            let y = event.position.y;
5190                            if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
5191                                let center_row =
5192                                    ((y - hitbox.top()) / text_unit_size).round() as u32;
5193                                let top_row = center_row.saturating_sub(
5194                                    (visible_range.end - visible_range.start) as u32 / 2,
5195                                );
5196                                let mut position = editor.scroll_position(cx);
5197                                position.y = top_row as f32;
5198                                editor.set_scroll_position(position, window, cx);
5199                            } else {
5200                                editor.scroll_manager.show_scrollbar(window, cx);
5201                            }
5202
5203                            cx.stop_propagation();
5204                        });
5205                    }
5206                });
5207            }
5208        }
5209    }
5210
5211    fn collect_fast_scrollbar_markers(
5212        &self,
5213        layout: &EditorLayout,
5214        scrollbar_layout: &ScrollbarLayout,
5215        cx: &mut App,
5216    ) -> Vec<PaintQuad> {
5217        const LIMIT: usize = 100;
5218        if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
5219            return vec![];
5220        }
5221        let cursor_ranges = layout
5222            .cursors
5223            .iter()
5224            .map(|(point, color)| ColoredRange {
5225                start: point.row(),
5226                end: point.row(),
5227                color: *color,
5228            })
5229            .collect_vec();
5230        scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
5231    }
5232
5233    fn refresh_slow_scrollbar_markers(
5234        &self,
5235        layout: &EditorLayout,
5236        scrollbar_layout: &ScrollbarLayout,
5237        window: &mut Window,
5238        cx: &mut App,
5239    ) {
5240        self.editor.update(cx, |editor, cx| {
5241            if !editor.is_singleton(cx)
5242                || !editor
5243                    .scrollbar_marker_state
5244                    .should_refresh(scrollbar_layout.hitbox.size)
5245            {
5246                return;
5247            }
5248
5249            let scrollbar_layout = scrollbar_layout.clone();
5250            let background_highlights = editor.background_highlights.clone();
5251            let snapshot = layout.position_map.snapshot.clone();
5252            let theme = cx.theme().clone();
5253            let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
5254
5255            editor.scrollbar_marker_state.dirty = false;
5256            editor.scrollbar_marker_state.pending_refresh =
5257                Some(cx.spawn_in(window, async move |editor, cx| {
5258                    let scrollbar_size = scrollbar_layout.hitbox.size;
5259                    let scrollbar_markers = cx
5260                        .background_spawn(async move {
5261                            let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
5262                            let mut marker_quads = Vec::new();
5263                            if scrollbar_settings.git_diff {
5264                                let marker_row_ranges =
5265                                    snapshot.buffer_snapshot.diff_hunks().map(|hunk| {
5266                                        let start_display_row =
5267                                            MultiBufferPoint::new(hunk.row_range.start.0, 0)
5268                                                .to_display_point(&snapshot.display_snapshot)
5269                                                .row();
5270                                        let mut end_display_row =
5271                                            MultiBufferPoint::new(hunk.row_range.end.0, 0)
5272                                                .to_display_point(&snapshot.display_snapshot)
5273                                                .row();
5274                                        if end_display_row != start_display_row {
5275                                            end_display_row.0 -= 1;
5276                                        }
5277                                        let color = match &hunk.status().kind {
5278                                            DiffHunkStatusKind::Added => {
5279                                                theme.colors().version_control_added
5280                                            }
5281                                            DiffHunkStatusKind::Modified => {
5282                                                theme.colors().version_control_modified
5283                                            }
5284                                            DiffHunkStatusKind::Deleted => {
5285                                                theme.colors().version_control_deleted
5286                                            }
5287                                        };
5288                                        ColoredRange {
5289                                            start: start_display_row,
5290                                            end: end_display_row,
5291                                            color,
5292                                        }
5293                                    });
5294
5295                                marker_quads.extend(
5296                                    scrollbar_layout
5297                                        .marker_quads_for_ranges(marker_row_ranges, Some(0)),
5298                                );
5299                            }
5300
5301                            for (background_highlight_id, (_, background_ranges)) in
5302                                background_highlights.iter()
5303                            {
5304                                let is_search_highlights = *background_highlight_id
5305                                    == TypeId::of::<BufferSearchHighlights>();
5306                                let is_text_highlights = *background_highlight_id
5307                                    == TypeId::of::<SelectedTextHighlight>();
5308                                let is_symbol_occurrences = *background_highlight_id
5309                                    == TypeId::of::<DocumentHighlightRead>()
5310                                    || *background_highlight_id
5311                                        == TypeId::of::<DocumentHighlightWrite>();
5312                                if (is_search_highlights && scrollbar_settings.search_results)
5313                                    || (is_text_highlights && scrollbar_settings.selected_text)
5314                                    || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
5315                                {
5316                                    let mut color = theme.status().info;
5317                                    if is_symbol_occurrences {
5318                                        color.fade_out(0.5);
5319                                    }
5320                                    let marker_row_ranges = background_ranges.iter().map(|range| {
5321                                        let display_start = range
5322                                            .start
5323                                            .to_display_point(&snapshot.display_snapshot);
5324                                        let display_end =
5325                                            range.end.to_display_point(&snapshot.display_snapshot);
5326                                        ColoredRange {
5327                                            start: display_start.row(),
5328                                            end: display_end.row(),
5329                                            color,
5330                                        }
5331                                    });
5332                                    marker_quads.extend(
5333                                        scrollbar_layout
5334                                            .marker_quads_for_ranges(marker_row_ranges, Some(1)),
5335                                    );
5336                                }
5337                            }
5338
5339                            if scrollbar_settings.diagnostics != ScrollbarDiagnostics::None {
5340                                let diagnostics = snapshot
5341                                    .buffer_snapshot
5342                                    .diagnostics_in_range::<Point>(Point::zero()..max_point)
5343                                    // Don't show diagnostics the user doesn't care about
5344                                    .filter(|diagnostic| {
5345                                        match (
5346                                            scrollbar_settings.diagnostics,
5347                                            diagnostic.diagnostic.severity,
5348                                        ) {
5349                                            (ScrollbarDiagnostics::All, _) => true,
5350                                            (
5351                                                ScrollbarDiagnostics::Error,
5352                                                DiagnosticSeverity::ERROR,
5353                                            ) => true,
5354                                            (
5355                                                ScrollbarDiagnostics::Warning,
5356                                                DiagnosticSeverity::ERROR
5357                                                | DiagnosticSeverity::WARNING,
5358                                            ) => true,
5359                                            (
5360                                                ScrollbarDiagnostics::Information,
5361                                                DiagnosticSeverity::ERROR
5362                                                | DiagnosticSeverity::WARNING
5363                                                | DiagnosticSeverity::INFORMATION,
5364                                            ) => true,
5365                                            (_, _) => false,
5366                                        }
5367                                    })
5368                                    // We want to sort by severity, in order to paint the most severe diagnostics last.
5369                                    .sorted_by_key(|diagnostic| {
5370                                        std::cmp::Reverse(diagnostic.diagnostic.severity)
5371                                    });
5372
5373                                let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
5374                                    let start_display = diagnostic
5375                                        .range
5376                                        .start
5377                                        .to_display_point(&snapshot.display_snapshot);
5378                                    let end_display = diagnostic
5379                                        .range
5380                                        .end
5381                                        .to_display_point(&snapshot.display_snapshot);
5382                                    let color = match diagnostic.diagnostic.severity {
5383                                        DiagnosticSeverity::ERROR => theme.status().error,
5384                                        DiagnosticSeverity::WARNING => theme.status().warning,
5385                                        DiagnosticSeverity::INFORMATION => theme.status().info,
5386                                        _ => theme.status().hint,
5387                                    };
5388                                    ColoredRange {
5389                                        start: start_display.row(),
5390                                        end: end_display.row(),
5391                                        color,
5392                                    }
5393                                });
5394                                marker_quads.extend(
5395                                    scrollbar_layout
5396                                        .marker_quads_for_ranges(marker_row_ranges, Some(2)),
5397                                );
5398                            }
5399
5400                            Arc::from(marker_quads)
5401                        })
5402                        .await;
5403
5404                    editor.update(cx, |editor, cx| {
5405                        editor.scrollbar_marker_state.markers = scrollbar_markers;
5406                        editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
5407                        editor.scrollbar_marker_state.pending_refresh = None;
5408                        cx.notify();
5409                    })?;
5410
5411                    Ok(())
5412                }));
5413        });
5414    }
5415
5416    fn paint_highlighted_range(
5417        &self,
5418        range: Range<DisplayPoint>,
5419        color: Hsla,
5420        corner_radius: Pixels,
5421        line_end_overshoot: Pixels,
5422        layout: &EditorLayout,
5423        window: &mut Window,
5424    ) {
5425        let start_row = layout.visible_display_row_range.start;
5426        let end_row = layout.visible_display_row_range.end;
5427        if range.start != range.end {
5428            let row_range = if range.end.column() == 0 {
5429                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
5430            } else {
5431                cmp::max(range.start.row(), start_row)
5432                    ..cmp::min(range.end.row().next_row(), end_row)
5433            };
5434
5435            let highlighted_range = HighlightedRange {
5436                color,
5437                line_height: layout.position_map.line_height,
5438                corner_radius,
5439                start_y: layout.content_origin.y
5440                    + row_range.start.as_f32() * layout.position_map.line_height
5441                    - layout.position_map.scroll_pixel_position.y,
5442                lines: row_range
5443                    .iter_rows()
5444                    .map(|row| {
5445                        let line_layout =
5446                            &layout.position_map.line_layouts[row.minus(start_row) as usize];
5447                        HighlightedRangeLine {
5448                            start_x: if row == range.start.row() {
5449                                layout.content_origin.x
5450                                    + line_layout.x_for_index(range.start.column() as usize)
5451                                    - layout.position_map.scroll_pixel_position.x
5452                            } else {
5453                                layout.content_origin.x
5454                                    - layout.position_map.scroll_pixel_position.x
5455                            },
5456                            end_x: if row == range.end.row() {
5457                                layout.content_origin.x
5458                                    + line_layout.x_for_index(range.end.column() as usize)
5459                                    - layout.position_map.scroll_pixel_position.x
5460                            } else {
5461                                layout.content_origin.x + line_layout.width + line_end_overshoot
5462                                    - layout.position_map.scroll_pixel_position.x
5463                            },
5464                        }
5465                    })
5466                    .collect(),
5467            };
5468
5469            highlighted_range.paint(layout.position_map.text_hitbox.bounds, window);
5470        }
5471    }
5472
5473    fn paint_inline_diagnostics(
5474        &mut self,
5475        layout: &mut EditorLayout,
5476        window: &mut Window,
5477        cx: &mut App,
5478    ) {
5479        for mut inline_diagnostic in layout.inline_diagnostics.drain() {
5480            inline_diagnostic.1.paint(window, cx);
5481        }
5482    }
5483
5484    fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5485        if let Some(mut inline_blame) = layout.inline_blame.take() {
5486            window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
5487                inline_blame.paint(window, cx);
5488            })
5489        }
5490    }
5491
5492    fn paint_diff_hunk_controls(
5493        &mut self,
5494        layout: &mut EditorLayout,
5495        window: &mut Window,
5496        cx: &mut App,
5497    ) {
5498        for mut diff_hunk_control in layout.diff_hunk_controls.drain(..) {
5499            diff_hunk_control.paint(window, cx);
5500        }
5501    }
5502
5503    fn paint_blocks(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5504        for mut block in layout.blocks.drain(..) {
5505            block.element.paint(window, cx);
5506        }
5507    }
5508
5509    fn paint_inline_completion_popover(
5510        &mut self,
5511        layout: &mut EditorLayout,
5512        window: &mut Window,
5513        cx: &mut App,
5514    ) {
5515        if let Some(inline_completion_popover) = layout.inline_completion_popover.as_mut() {
5516            inline_completion_popover.paint(window, cx);
5517        }
5518    }
5519
5520    fn paint_mouse_context_menu(
5521        &mut self,
5522        layout: &mut EditorLayout,
5523        window: &mut Window,
5524        cx: &mut App,
5525    ) {
5526        if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
5527            mouse_context_menu.paint(window, cx);
5528        }
5529    }
5530
5531    fn paint_scroll_wheel_listener(
5532        &mut self,
5533        layout: &EditorLayout,
5534        window: &mut Window,
5535        cx: &mut App,
5536    ) {
5537        window.on_mouse_event({
5538            let position_map = layout.position_map.clone();
5539            let editor = self.editor.clone();
5540            let hitbox = layout.hitbox.clone();
5541            let mut delta = ScrollDelta::default();
5542
5543            // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
5544            // accidentally turn off their scrolling.
5545            let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
5546
5547            move |event: &ScrollWheelEvent, phase, window, cx| {
5548                if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
5549                    delta = delta.coalesce(event.delta);
5550                    editor.update(cx, |editor, cx| {
5551                        let position_map: &PositionMap = &position_map;
5552
5553                        let line_height = position_map.line_height;
5554                        let max_glyph_width = position_map.em_width;
5555                        let (delta, axis) = match delta {
5556                            gpui::ScrollDelta::Pixels(mut pixels) => {
5557                                //Trackpad
5558                                let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
5559                                (pixels, axis)
5560                            }
5561
5562                            gpui::ScrollDelta::Lines(lines) => {
5563                                //Not trackpad
5564                                let pixels =
5565                                    point(lines.x * max_glyph_width, lines.y * line_height);
5566                                (pixels, None)
5567                            }
5568                        };
5569
5570                        let current_scroll_position = position_map.snapshot.scroll_position();
5571                        let x = (current_scroll_position.x * max_glyph_width
5572                            - (delta.x * scroll_sensitivity))
5573                            / max_glyph_width;
5574                        let y = (current_scroll_position.y * line_height
5575                            - (delta.y * scroll_sensitivity))
5576                            / line_height;
5577                        let mut scroll_position =
5578                            point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
5579                        let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
5580                        if forbid_vertical_scroll {
5581                            scroll_position.y = current_scroll_position.y;
5582                        }
5583
5584                        if scroll_position != current_scroll_position {
5585                            editor.scroll(scroll_position, axis, window, cx);
5586                            cx.stop_propagation();
5587                        } else if y < 0. {
5588                            // Due to clamping, we may fail to detect cases of overscroll to the top;
5589                            // We want the scroll manager to get an update in such cases and detect the change of direction
5590                            // on the next frame.
5591                            cx.notify();
5592                        }
5593                    });
5594                }
5595            }
5596        });
5597    }
5598
5599    fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
5600        self.paint_scroll_wheel_listener(layout, window, cx);
5601
5602        window.on_mouse_event({
5603            let position_map = layout.position_map.clone();
5604            let editor = self.editor.clone();
5605            let diff_hunk_range =
5606                layout
5607                    .display_hunks
5608                    .iter()
5609                    .find_map(|(hunk, hunk_hitbox)| match hunk {
5610                        DisplayDiffHunk::Folded { .. } => None,
5611                        DisplayDiffHunk::Unfolded {
5612                            multi_buffer_range, ..
5613                        } => {
5614                            if hunk_hitbox
5615                                .as_ref()
5616                                .map(|hitbox| hitbox.is_hovered(window))
5617                                .unwrap_or(false)
5618                            {
5619                                Some(multi_buffer_range.clone())
5620                            } else {
5621                                None
5622                            }
5623                        }
5624                    });
5625            let line_numbers = layout.line_numbers.clone();
5626
5627            move |event: &MouseDownEvent, phase, window, cx| {
5628                if phase == DispatchPhase::Bubble {
5629                    match event.button {
5630                        MouseButton::Left => editor.update(cx, |editor, cx| {
5631                            let pending_mouse_down = editor
5632                                .pending_mouse_down
5633                                .get_or_insert_with(Default::default)
5634                                .clone();
5635
5636                            *pending_mouse_down.borrow_mut() = Some(event.clone());
5637
5638                            Self::mouse_left_down(
5639                                editor,
5640                                event,
5641                                diff_hunk_range.clone(),
5642                                &position_map,
5643                                line_numbers.as_ref(),
5644                                window,
5645                                cx,
5646                            );
5647                        }),
5648                        MouseButton::Right => editor.update(cx, |editor, cx| {
5649                            Self::mouse_right_down(editor, event, &position_map, window, cx);
5650                        }),
5651                        MouseButton::Middle => editor.update(cx, |editor, cx| {
5652                            Self::mouse_middle_down(editor, event, &position_map, window, cx);
5653                        }),
5654                        _ => {}
5655                    };
5656                }
5657            }
5658        });
5659
5660        window.on_mouse_event({
5661            let editor = self.editor.clone();
5662            let position_map = layout.position_map.clone();
5663
5664            move |event: &MouseUpEvent, phase, window, cx| {
5665                if phase == DispatchPhase::Bubble {
5666                    editor.update(cx, |editor, cx| {
5667                        Self::mouse_up(editor, event, &position_map, window, cx)
5668                    });
5669                }
5670            }
5671        });
5672
5673        window.on_mouse_event({
5674            let editor = self.editor.clone();
5675            let position_map = layout.position_map.clone();
5676            let mut captured_mouse_down = None;
5677
5678            move |event: &MouseUpEvent, phase, window, cx| match phase {
5679                // Clear the pending mouse down during the capture phase,
5680                // so that it happens even if another event handler stops
5681                // propagation.
5682                DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
5683                    let pending_mouse_down = editor
5684                        .pending_mouse_down
5685                        .get_or_insert_with(Default::default)
5686                        .clone();
5687
5688                    let mut pending_mouse_down = pending_mouse_down.borrow_mut();
5689                    if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
5690                        captured_mouse_down = pending_mouse_down.take();
5691                        window.refresh();
5692                    }
5693                }),
5694                // Fire click handlers during the bubble phase.
5695                DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
5696                    if let Some(mouse_down) = captured_mouse_down.take() {
5697                        let event = ClickEvent {
5698                            down: mouse_down,
5699                            up: event.clone(),
5700                        };
5701                        Self::click(editor, &event, &position_map, window, cx);
5702                    }
5703                }),
5704            }
5705        });
5706
5707        window.on_mouse_event({
5708            let position_map = layout.position_map.clone();
5709            let editor = self.editor.clone();
5710
5711            move |event: &MouseMoveEvent, phase, window, cx| {
5712                if phase == DispatchPhase::Bubble {
5713                    editor.update(cx, |editor, cx| {
5714                        if editor.hover_state.focused(window, cx) {
5715                            return;
5716                        }
5717                        if event.pressed_button == Some(MouseButton::Left)
5718                            || event.pressed_button == Some(MouseButton::Middle)
5719                        {
5720                            Self::mouse_dragged(editor, event, &position_map, window, cx)
5721                        }
5722
5723                        Self::mouse_moved(editor, event, &position_map, window, cx)
5724                    });
5725                }
5726            }
5727        });
5728    }
5729
5730    fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
5731        bounds.top_right().x - self.style.scrollbar_width
5732    }
5733
5734    fn column_pixels(&self, column: usize, window: &mut Window, _: &mut App) -> Pixels {
5735        let style = &self.style;
5736        let font_size = style.text.font_size.to_pixels(window.rem_size());
5737        let layout = window
5738            .text_system()
5739            .shape_line(
5740                SharedString::from(" ".repeat(column)),
5741                font_size,
5742                &[TextRun {
5743                    len: column,
5744                    font: style.text.font(),
5745                    color: Hsla::default(),
5746                    background_color: None,
5747                    underline: None,
5748                    strikethrough: None,
5749                }],
5750            )
5751            .unwrap();
5752
5753        layout.width
5754    }
5755
5756    fn max_line_number_width(
5757        &self,
5758        snapshot: &EditorSnapshot,
5759        window: &mut Window,
5760        cx: &mut App,
5761    ) -> Pixels {
5762        let digit_count = snapshot.widest_line_number().ilog10() + 1;
5763        self.column_pixels(digit_count as usize, window, cx)
5764    }
5765
5766    fn shape_line_number(
5767        &self,
5768        text: SharedString,
5769        color: Hsla,
5770        window: &mut Window,
5771    ) -> anyhow::Result<ShapedLine> {
5772        let run = TextRun {
5773            len: text.len(),
5774            font: self.style.text.font(),
5775            color,
5776            background_color: None,
5777            underline: None,
5778            strikethrough: None,
5779        };
5780        window.text_system().shape_line(
5781            text,
5782            self.style.text.font_size.to_pixels(window.rem_size()),
5783            &[run],
5784        )
5785    }
5786
5787    fn diff_hunk_hollow(status: DiffHunkStatus, cx: &mut App) -> bool {
5788        let unstaged = status.has_secondary_hunk();
5789        let unstaged_hollow = ProjectSettings::get_global(cx)
5790            .git
5791            .hunk_style
5792            .map_or(false, |style| {
5793                matches!(style, GitHunkStyleSetting::UnstagedHollow)
5794            });
5795
5796        unstaged == unstaged_hollow
5797    }
5798}
5799
5800fn header_jump_data(
5801    snapshot: &EditorSnapshot,
5802    block_row_start: DisplayRow,
5803    height: u32,
5804    for_excerpt: &ExcerptInfo,
5805) -> JumpData {
5806    let range = &for_excerpt.range;
5807    let buffer = &for_excerpt.buffer;
5808    let jump_anchor = range
5809        .primary
5810        .as_ref()
5811        .map_or(range.context.start, |primary| primary.start);
5812
5813    let excerpt_start = range.context.start;
5814    let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
5815    let rows_from_excerpt_start = if jump_anchor == excerpt_start {
5816        0
5817    } else {
5818        let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
5819        jump_position.row.saturating_sub(excerpt_start_point.row)
5820    };
5821
5822    let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
5823        .saturating_sub(
5824            snapshot
5825                .scroll_anchor
5826                .scroll_position(&snapshot.display_snapshot)
5827                .y as u32,
5828        );
5829
5830    JumpData::MultiBufferPoint {
5831        excerpt_id: for_excerpt.id,
5832        anchor: jump_anchor,
5833        position: jump_position,
5834        line_offset_from_top,
5835    }
5836}
5837
5838pub struct AcceptEditPredictionBinding(pub(crate) Option<gpui::KeyBinding>);
5839
5840impl AcceptEditPredictionBinding {
5841    pub fn keystroke(&self) -> Option<&Keystroke> {
5842        if let Some(binding) = self.0.as_ref() {
5843            match &binding.keystrokes() {
5844                [keystroke] => Some(keystroke),
5845                _ => None,
5846            }
5847        } else {
5848            None
5849        }
5850    }
5851}
5852
5853fn prepaint_gutter_button(
5854    button: IconButton,
5855    row: DisplayRow,
5856    line_height: Pixels,
5857    gutter_dimensions: &GutterDimensions,
5858    scroll_pixel_position: gpui::Point<Pixels>,
5859    gutter_hitbox: &Hitbox,
5860    display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
5861    window: &mut Window,
5862    cx: &mut App,
5863) -> AnyElement {
5864    let mut button = button.into_any_element();
5865
5866    let available_space = size(
5867        AvailableSpace::MinContent,
5868        AvailableSpace::Definite(line_height),
5869    );
5870    let indicator_size = button.layout_as_root(available_space, window, cx);
5871
5872    let blame_width = gutter_dimensions.git_blame_entries_width;
5873    let gutter_width = display_hunks
5874        .binary_search_by(|(hunk, _)| match hunk {
5875            DisplayDiffHunk::Folded { display_row } => display_row.cmp(&row),
5876            DisplayDiffHunk::Unfolded {
5877                display_row_range, ..
5878            } => {
5879                if display_row_range.end <= row {
5880                    Ordering::Less
5881                } else if display_row_range.start > row {
5882                    Ordering::Greater
5883                } else {
5884                    Ordering::Equal
5885                }
5886            }
5887        })
5888        .ok()
5889        .and_then(|ix| Some(display_hunks[ix].1.as_ref()?.size.width));
5890    let left_offset = blame_width.max(gutter_width).unwrap_or_default();
5891
5892    let mut x = left_offset;
5893    let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
5894        - indicator_size.width
5895        - left_offset;
5896    x += available_width / 2.;
5897
5898    let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
5899    y += (line_height - indicator_size.height) / 2.;
5900
5901    button.prepaint_as_root(
5902        gutter_hitbox.origin + point(x, y),
5903        available_space,
5904        window,
5905        cx,
5906    );
5907    button
5908}
5909
5910fn render_inline_blame_entry(
5911    editor: Entity<Editor>,
5912    blame: &gpui::Entity<GitBlame>,
5913    blame_entry: BlameEntry,
5914    style: &EditorStyle,
5915    cx: &mut App,
5916) -> AnyElement {
5917    let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
5918
5919    let author = blame_entry.author.as_deref().unwrap_or_default();
5920    let summary_enabled = ProjectSettings::get_global(cx)
5921        .git
5922        .show_inline_commit_summary();
5923
5924    let text = match blame_entry.summary.as_ref() {
5925        Some(summary) if summary_enabled => {
5926            format!("{}, {} - {}", author, relative_timestamp, summary)
5927        }
5928        _ => format!("{}, {}", author, relative_timestamp),
5929    };
5930    let blame = blame.clone();
5931    let blame_entry = blame_entry.clone();
5932
5933    h_flex()
5934        .id("inline-blame")
5935        .w_full()
5936        .font_family(style.text.font().family)
5937        .text_color(cx.theme().status().hint)
5938        .line_height(style.text.line_height)
5939        .child(Icon::new(IconName::FileGit).color(Color::Hint))
5940        .child(text)
5941        .gap_2()
5942        .hoverable_tooltip(move |window, cx| {
5943            let details = blame.read(cx).details_for_entry(&blame_entry);
5944            let tooltip =
5945                cx.new(|cx| CommitTooltip::blame_entry(&blame_entry, details, window, cx));
5946            editor.update(cx, |editor, _| {
5947                editor.git_blame_inline_tooltip = Some(tooltip.downgrade())
5948            });
5949            tooltip.into()
5950        })
5951        .into_any()
5952}
5953
5954fn render_blame_entry(
5955    ix: usize,
5956    blame: &gpui::Entity<GitBlame>,
5957    blame_entry: BlameEntry,
5958    style: &EditorStyle,
5959    last_used_color: &mut Option<(PlayerColor, Oid)>,
5960    editor: Entity<Editor>,
5961    cx: &mut App,
5962) -> AnyElement {
5963    let mut sha_color = cx
5964        .theme()
5965        .players()
5966        .color_for_participant(blame_entry.sha.into());
5967    // If the last color we used is the same as the one we get for this line, but
5968    // the commit SHAs are different, then we try again to get a different color.
5969    match *last_used_color {
5970        Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
5971            let index: u32 = blame_entry.sha.into();
5972            sha_color = cx.theme().players().color_for_participant(index + 1);
5973        }
5974        _ => {}
5975    };
5976    last_used_color.replace((sha_color, blame_entry.sha));
5977
5978    let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
5979
5980    let short_commit_id = blame_entry.sha.display_short();
5981
5982    let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
5983    let name = util::truncate_and_trailoff(author_name, GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED);
5984    let details = blame.read(cx).details_for_entry(&blame_entry);
5985
5986    h_flex()
5987        .w_full()
5988        .justify_between()
5989        .font_family(style.text.font().family)
5990        .line_height(style.text.line_height)
5991        .id(("blame", ix))
5992        .text_color(cx.theme().status().hint)
5993        .pr_2()
5994        .gap_2()
5995        .child(
5996            h_flex()
5997                .items_center()
5998                .gap_2()
5999                .child(div().text_color(sha_color.cursor).child(short_commit_id))
6000                .child(name),
6001        )
6002        .child(relative_timestamp)
6003        .on_mouse_down(MouseButton::Right, {
6004            let blame_entry = blame_entry.clone();
6005            let details = details.clone();
6006            move |event, window, cx| {
6007                deploy_blame_entry_context_menu(
6008                    &blame_entry,
6009                    details.as_ref(),
6010                    editor.clone(),
6011                    event.position,
6012                    window,
6013                    cx,
6014                );
6015            }
6016        })
6017        .hover(|style| style.bg(cx.theme().colors().element_hover))
6018        .when_some(
6019            details
6020                .as_ref()
6021                .and_then(|details| details.permalink.clone()),
6022            |this, url| {
6023                this.cursor_pointer().on_click(move |_, _, cx| {
6024                    cx.stop_propagation();
6025                    cx.open_url(url.as_str())
6026                })
6027            },
6028        )
6029        .hoverable_tooltip(move |window, cx| {
6030            cx.new(|cx| CommitTooltip::blame_entry(&blame_entry, details.clone(), window, cx))
6031                .into()
6032        })
6033        .into_any()
6034}
6035
6036fn deploy_blame_entry_context_menu(
6037    blame_entry: &BlameEntry,
6038    details: Option<&ParsedCommitMessage>,
6039    editor: Entity<Editor>,
6040    position: gpui::Point<Pixels>,
6041    window: &mut Window,
6042    cx: &mut App,
6043) {
6044    let context_menu = ContextMenu::build(window, cx, move |menu, _, _| {
6045        let sha = format!("{}", blame_entry.sha);
6046        menu.on_blur_subscription(Subscription::new(|| {}))
6047            .entry("Copy commit SHA", None, move |_, cx| {
6048                cx.write_to_clipboard(ClipboardItem::new_string(sha.clone()));
6049            })
6050            .when_some(
6051                details.and_then(|details| details.permalink.clone()),
6052                |this, url| {
6053                    this.entry("Open permalink", None, move |_, cx| {
6054                        cx.open_url(url.as_str())
6055                    })
6056                },
6057            )
6058    });
6059
6060    editor.update(cx, move |editor, cx| {
6061        editor.mouse_context_menu = Some(MouseContextMenu::new(
6062            MenuPosition::PinnedToScreen(position),
6063            context_menu,
6064            window,
6065            cx,
6066        ));
6067        cx.notify();
6068    });
6069}
6070
6071#[derive(Debug)]
6072pub(crate) struct LineWithInvisibles {
6073    fragments: SmallVec<[LineFragment; 1]>,
6074    invisibles: Vec<Invisible>,
6075    len: usize,
6076    pub(crate) width: Pixels,
6077    font_size: Pixels,
6078}
6079
6080#[allow(clippy::large_enum_variant)]
6081enum LineFragment {
6082    Text(ShapedLine),
6083    Element {
6084        element: Option<AnyElement>,
6085        size: Size<Pixels>,
6086        len: usize,
6087    },
6088}
6089
6090impl fmt::Debug for LineFragment {
6091    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6092        match self {
6093            LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
6094            LineFragment::Element { size, len, .. } => f
6095                .debug_struct("Element")
6096                .field("size", size)
6097                .field("len", len)
6098                .finish(),
6099        }
6100    }
6101}
6102
6103impl LineWithInvisibles {
6104    fn from_chunks<'a>(
6105        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
6106        editor_style: &EditorStyle,
6107        max_line_len: usize,
6108        max_line_count: usize,
6109        editor_mode: EditorMode,
6110        text_width: Pixels,
6111        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
6112        window: &mut Window,
6113        cx: &mut App,
6114    ) -> Vec<Self> {
6115        let text_style = &editor_style.text;
6116        let mut layouts = Vec::with_capacity(max_line_count);
6117        let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
6118        let mut line = String::new();
6119        let mut invisibles = Vec::new();
6120        let mut width = Pixels::ZERO;
6121        let mut len = 0;
6122        let mut styles = Vec::new();
6123        let mut non_whitespace_added = false;
6124        let mut row = 0;
6125        let mut line_exceeded_max_len = false;
6126        let font_size = text_style.font_size.to_pixels(window.rem_size());
6127
6128        let ellipsis = SharedString::from("");
6129
6130        for highlighted_chunk in chunks.chain([HighlightedChunk {
6131            text: "\n",
6132            style: None,
6133            is_tab: false,
6134            replacement: None,
6135        }]) {
6136            if let Some(replacement) = highlighted_chunk.replacement {
6137                if !line.is_empty() {
6138                    let shaped_line = window
6139                        .text_system()
6140                        .shape_line(line.clone().into(), font_size, &styles)
6141                        .unwrap();
6142                    width += shaped_line.width;
6143                    len += shaped_line.len;
6144                    fragments.push(LineFragment::Text(shaped_line));
6145                    line.clear();
6146                    styles.clear();
6147                }
6148
6149                match replacement {
6150                    ChunkReplacement::Renderer(renderer) => {
6151                        let available_width = if renderer.constrain_width {
6152                            let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
6153                                ellipsis.clone()
6154                            } else {
6155                                SharedString::from(Arc::from(highlighted_chunk.text))
6156                            };
6157                            let shaped_line = window
6158                                .text_system()
6159                                .shape_line(
6160                                    chunk,
6161                                    font_size,
6162                                    &[text_style.to_run(highlighted_chunk.text.len())],
6163                                )
6164                                .unwrap();
6165                            AvailableSpace::Definite(shaped_line.width)
6166                        } else {
6167                            AvailableSpace::MinContent
6168                        };
6169
6170                        let mut element = (renderer.render)(&mut ChunkRendererContext {
6171                            context: cx,
6172                            window,
6173                            max_width: text_width,
6174                        });
6175                        let line_height = text_style.line_height_in_pixels(window.rem_size());
6176                        let size = element.layout_as_root(
6177                            size(available_width, AvailableSpace::Definite(line_height)),
6178                            window,
6179                            cx,
6180                        );
6181
6182                        width += size.width;
6183                        len += highlighted_chunk.text.len();
6184                        fragments.push(LineFragment::Element {
6185                            element: Some(element),
6186                            size,
6187                            len: highlighted_chunk.text.len(),
6188                        });
6189                    }
6190                    ChunkReplacement::Str(x) => {
6191                        let text_style = if let Some(style) = highlighted_chunk.style {
6192                            Cow::Owned(text_style.clone().highlight(style))
6193                        } else {
6194                            Cow::Borrowed(text_style)
6195                        };
6196
6197                        let run = TextRun {
6198                            len: x.len(),
6199                            font: text_style.font(),
6200                            color: text_style.color,
6201                            background_color: text_style.background_color,
6202                            underline: text_style.underline,
6203                            strikethrough: text_style.strikethrough,
6204                        };
6205                        let line_layout = window
6206                            .text_system()
6207                            .shape_line(x, font_size, &[run])
6208                            .unwrap()
6209                            .with_len(highlighted_chunk.text.len());
6210
6211                        width += line_layout.width;
6212                        len += highlighted_chunk.text.len();
6213                        fragments.push(LineFragment::Text(line_layout))
6214                    }
6215                }
6216            } else {
6217                for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
6218                    if ix > 0 {
6219                        let shaped_line = window
6220                            .text_system()
6221                            .shape_line(line.clone().into(), font_size, &styles)
6222                            .unwrap();
6223                        width += shaped_line.width;
6224                        len += shaped_line.len;
6225                        fragments.push(LineFragment::Text(shaped_line));
6226                        layouts.push(Self {
6227                            width: mem::take(&mut width),
6228                            len: mem::take(&mut len),
6229                            fragments: mem::take(&mut fragments),
6230                            invisibles: std::mem::take(&mut invisibles),
6231                            font_size,
6232                        });
6233
6234                        line.clear();
6235                        styles.clear();
6236                        row += 1;
6237                        line_exceeded_max_len = false;
6238                        non_whitespace_added = false;
6239                        if row == max_line_count {
6240                            return layouts;
6241                        }
6242                    }
6243
6244                    if !line_chunk.is_empty() && !line_exceeded_max_len {
6245                        let text_style = if let Some(style) = highlighted_chunk.style {
6246                            Cow::Owned(text_style.clone().highlight(style))
6247                        } else {
6248                            Cow::Borrowed(text_style)
6249                        };
6250
6251                        if line.len() + line_chunk.len() > max_line_len {
6252                            let mut chunk_len = max_line_len - line.len();
6253                            while !line_chunk.is_char_boundary(chunk_len) {
6254                                chunk_len -= 1;
6255                            }
6256                            line_chunk = &line_chunk[..chunk_len];
6257                            line_exceeded_max_len = true;
6258                        }
6259
6260                        styles.push(TextRun {
6261                            len: line_chunk.len(),
6262                            font: text_style.font(),
6263                            color: text_style.color,
6264                            background_color: text_style.background_color,
6265                            underline: text_style.underline,
6266                            strikethrough: text_style.strikethrough,
6267                        });
6268
6269                        if editor_mode == EditorMode::Full {
6270                            // Line wrap pads its contents with fake whitespaces,
6271                            // avoid printing them
6272                            let is_soft_wrapped = is_row_soft_wrapped(row);
6273                            if highlighted_chunk.is_tab {
6274                                if non_whitespace_added || !is_soft_wrapped {
6275                                    invisibles.push(Invisible::Tab {
6276                                        line_start_offset: line.len(),
6277                                        line_end_offset: line.len() + line_chunk.len(),
6278                                    });
6279                                }
6280                            } else {
6281                                invisibles.extend(line_chunk.char_indices().filter_map(
6282                                    |(index, c)| {
6283                                        let is_whitespace = c.is_whitespace();
6284                                        non_whitespace_added |= !is_whitespace;
6285                                        if is_whitespace
6286                                            && (non_whitespace_added || !is_soft_wrapped)
6287                                        {
6288                                            Some(Invisible::Whitespace {
6289                                                line_offset: line.len() + index,
6290                                            })
6291                                        } else {
6292                                            None
6293                                        }
6294                                    },
6295                                ))
6296                            }
6297                        }
6298
6299                        line.push_str(line_chunk);
6300                    }
6301                }
6302            }
6303        }
6304
6305        layouts
6306    }
6307
6308    fn prepaint(
6309        &mut self,
6310        line_height: Pixels,
6311        scroll_pixel_position: gpui::Point<Pixels>,
6312        row: DisplayRow,
6313        content_origin: gpui::Point<Pixels>,
6314        line_elements: &mut SmallVec<[AnyElement; 1]>,
6315        window: &mut Window,
6316        cx: &mut App,
6317    ) {
6318        let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
6319        let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
6320        for fragment in &mut self.fragments {
6321            match fragment {
6322                LineFragment::Text(line) => {
6323                    fragment_origin.x += line.width;
6324                }
6325                LineFragment::Element { element, size, .. } => {
6326                    let mut element = element
6327                        .take()
6328                        .expect("you can't prepaint LineWithInvisibles twice");
6329
6330                    // Center the element vertically within the line.
6331                    let mut element_origin = fragment_origin;
6332                    element_origin.y += (line_height - size.height) / 2.;
6333                    element.prepaint_at(element_origin, window, cx);
6334                    line_elements.push(element);
6335
6336                    fragment_origin.x += size.width;
6337                }
6338            }
6339        }
6340    }
6341
6342    fn draw(
6343        &self,
6344        layout: &EditorLayout,
6345        row: DisplayRow,
6346        content_origin: gpui::Point<Pixels>,
6347        whitespace_setting: ShowWhitespaceSetting,
6348        selection_ranges: &[Range<DisplayPoint>],
6349        window: &mut Window,
6350        cx: &mut App,
6351    ) {
6352        let line_height = layout.position_map.line_height;
6353        let line_y = line_height
6354            * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
6355
6356        let mut fragment_origin =
6357            content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
6358
6359        for fragment in &self.fragments {
6360            match fragment {
6361                LineFragment::Text(line) => {
6362                    line.paint(fragment_origin, line_height, window, cx)
6363                        .log_err();
6364                    fragment_origin.x += line.width;
6365                }
6366                LineFragment::Element { size, .. } => {
6367                    fragment_origin.x += size.width;
6368                }
6369            }
6370        }
6371
6372        self.draw_invisibles(
6373            selection_ranges,
6374            layout,
6375            content_origin,
6376            line_y,
6377            row,
6378            line_height,
6379            whitespace_setting,
6380            window,
6381            cx,
6382        );
6383    }
6384
6385    fn draw_background(
6386        &self,
6387        layout: &EditorLayout,
6388        row: DisplayRow,
6389        content_origin: gpui::Point<Pixels>,
6390        window: &mut Window,
6391        cx: &mut App,
6392    ) {
6393        let line_height = layout.position_map.line_height;
6394        let line_y = line_height
6395            * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
6396
6397        let mut fragment_origin =
6398            content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
6399
6400        for fragment in &self.fragments {
6401            match fragment {
6402                LineFragment::Text(line) => {
6403                    line.paint_background(fragment_origin, line_height, window, cx)
6404                        .log_err();
6405                    fragment_origin.x += line.width;
6406                }
6407                LineFragment::Element { size, .. } => {
6408                    fragment_origin.x += size.width;
6409                }
6410            }
6411        }
6412    }
6413
6414    fn draw_invisibles(
6415        &self,
6416        selection_ranges: &[Range<DisplayPoint>],
6417        layout: &EditorLayout,
6418        content_origin: gpui::Point<Pixels>,
6419        line_y: Pixels,
6420        row: DisplayRow,
6421        line_height: Pixels,
6422        whitespace_setting: ShowWhitespaceSetting,
6423        window: &mut Window,
6424        cx: &mut App,
6425    ) {
6426        let extract_whitespace_info = |invisible: &Invisible| {
6427            let (token_offset, token_end_offset, invisible_symbol) = match invisible {
6428                Invisible::Tab {
6429                    line_start_offset,
6430                    line_end_offset,
6431                } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
6432                Invisible::Whitespace { line_offset } => {
6433                    (*line_offset, line_offset + 1, &layout.space_invisible)
6434                }
6435            };
6436
6437            let x_offset = self.x_for_index(token_offset);
6438            let invisible_offset =
6439                (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
6440            let origin = content_origin
6441                + gpui::point(
6442                    x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
6443                    line_y,
6444                );
6445
6446            (
6447                [token_offset, token_end_offset],
6448                Box::new(move |window: &mut Window, cx: &mut App| {
6449                    invisible_symbol
6450                        .paint(origin, line_height, window, cx)
6451                        .log_err();
6452                }),
6453            )
6454        };
6455
6456        let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
6457        match whitespace_setting {
6458            ShowWhitespaceSetting::None => (),
6459            ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
6460            ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
6461                let invisible_point = DisplayPoint::new(row, start as u32);
6462                if !selection_ranges
6463                    .iter()
6464                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
6465                {
6466                    return;
6467                }
6468
6469                paint(window, cx);
6470            }),
6471
6472            // For a whitespace to be on a boundary, any of the following conditions need to be met:
6473            // - It is a tab
6474            // - It is adjacent to an edge (start or end)
6475            // - It is adjacent to a whitespace (left or right)
6476            ShowWhitespaceSetting::Boundary => {
6477                // 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
6478                // the above cases.
6479                // Note: We zip in the original `invisibles` to check for tab equality
6480                let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
6481                for (([start, end], paint), invisible) in
6482                    invisible_iter.zip_eq(self.invisibles.iter())
6483                {
6484                    let should_render = match (&last_seen, invisible) {
6485                        (_, Invisible::Tab { .. }) => true,
6486                        (Some((_, last_end, _)), _) => *last_end == start,
6487                        _ => false,
6488                    };
6489
6490                    if should_render || start == 0 || end == self.len {
6491                        paint(window, cx);
6492
6493                        // Since we are scanning from the left, we will skip over the first available whitespace that is part
6494                        // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
6495                        if let Some((should_render_last, last_end, paint_last)) = last_seen {
6496                            // Note that we need to make sure that the last one is actually adjacent
6497                            if !should_render_last && last_end == start {
6498                                paint_last(window, cx);
6499                            }
6500                        }
6501                    }
6502
6503                    // Manually render anything within a selection
6504                    let invisible_point = DisplayPoint::new(row, start as u32);
6505                    if selection_ranges.iter().any(|region| {
6506                        region.start <= invisible_point && invisible_point < region.end
6507                    }) {
6508                        paint(window, cx);
6509                    }
6510
6511                    last_seen = Some((should_render, end, paint));
6512                }
6513            }
6514        }
6515    }
6516
6517    pub fn x_for_index(&self, index: usize) -> Pixels {
6518        let mut fragment_start_x = Pixels::ZERO;
6519        let mut fragment_start_index = 0;
6520
6521        for fragment in &self.fragments {
6522            match fragment {
6523                LineFragment::Text(shaped_line) => {
6524                    let fragment_end_index = fragment_start_index + shaped_line.len;
6525                    if index < fragment_end_index {
6526                        return fragment_start_x
6527                            + shaped_line.x_for_index(index - fragment_start_index);
6528                    }
6529                    fragment_start_x += shaped_line.width;
6530                    fragment_start_index = fragment_end_index;
6531                }
6532                LineFragment::Element { len, size, .. } => {
6533                    let fragment_end_index = fragment_start_index + len;
6534                    if index < fragment_end_index {
6535                        return fragment_start_x;
6536                    }
6537                    fragment_start_x += size.width;
6538                    fragment_start_index = fragment_end_index;
6539                }
6540            }
6541        }
6542
6543        fragment_start_x
6544    }
6545
6546    pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
6547        let mut fragment_start_x = Pixels::ZERO;
6548        let mut fragment_start_index = 0;
6549
6550        for fragment in &self.fragments {
6551            match fragment {
6552                LineFragment::Text(shaped_line) => {
6553                    let fragment_end_x = fragment_start_x + shaped_line.width;
6554                    if x < fragment_end_x {
6555                        return Some(
6556                            fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
6557                        );
6558                    }
6559                    fragment_start_x = fragment_end_x;
6560                    fragment_start_index += shaped_line.len;
6561                }
6562                LineFragment::Element { len, size, .. } => {
6563                    let fragment_end_x = fragment_start_x + size.width;
6564                    if x < fragment_end_x {
6565                        return Some(fragment_start_index);
6566                    }
6567                    fragment_start_index += len;
6568                    fragment_start_x = fragment_end_x;
6569                }
6570            }
6571        }
6572
6573        None
6574    }
6575
6576    pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
6577        let mut fragment_start_index = 0;
6578
6579        for fragment in &self.fragments {
6580            match fragment {
6581                LineFragment::Text(shaped_line) => {
6582                    let fragment_end_index = fragment_start_index + shaped_line.len;
6583                    if index < fragment_end_index {
6584                        return shaped_line.font_id_for_index(index - fragment_start_index);
6585                    }
6586                    fragment_start_index = fragment_end_index;
6587                }
6588                LineFragment::Element { len, .. } => {
6589                    let fragment_end_index = fragment_start_index + len;
6590                    if index < fragment_end_index {
6591                        return None;
6592                    }
6593                    fragment_start_index = fragment_end_index;
6594                }
6595            }
6596        }
6597
6598        None
6599    }
6600}
6601
6602#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6603enum Invisible {
6604    /// A tab character
6605    ///
6606    /// A tab character is internally represented by spaces (configured by the user's tab width)
6607    /// aligned to the nearest column, so it's necessary to store the start and end offset for
6608    /// adjacency checks.
6609    Tab {
6610        line_start_offset: usize,
6611        line_end_offset: usize,
6612    },
6613    Whitespace {
6614        line_offset: usize,
6615    },
6616}
6617
6618impl EditorElement {
6619    /// Returns the rem size to use when rendering the [`EditorElement`].
6620    ///
6621    /// This allows UI elements to scale based on the `buffer_font_size`.
6622    fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
6623        match self.editor.read(cx).mode {
6624            EditorMode::Full => {
6625                let buffer_font_size = self.style.text.font_size;
6626                match buffer_font_size {
6627                    AbsoluteLength::Pixels(pixels) => {
6628                        let rem_size_scale = {
6629                            // Our default UI font size is 14px on a 16px base scale.
6630                            // This means the default UI font size is 0.875rems.
6631                            let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
6632
6633                            // We then determine the delta between a single rem and the default font
6634                            // size scale.
6635                            let default_font_size_delta = 1. - default_font_size_scale;
6636
6637                            // Finally, we add this delta to 1rem to get the scale factor that
6638                            // should be used to scale up the UI.
6639                            1. + default_font_size_delta
6640                        };
6641
6642                        Some(pixels * rem_size_scale)
6643                    }
6644                    AbsoluteLength::Rems(rems) => {
6645                        Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
6646                    }
6647                }
6648            }
6649            // We currently use single-line and auto-height editors in UI contexts,
6650            // so we don't want to scale everything with the buffer font size, as it
6651            // ends up looking off.
6652            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => None,
6653        }
6654    }
6655}
6656
6657impl Element for EditorElement {
6658    type RequestLayoutState = ();
6659    type PrepaintState = EditorLayout;
6660
6661    fn id(&self) -> Option<ElementId> {
6662        None
6663    }
6664
6665    fn request_layout(
6666        &mut self,
6667        _: Option<&GlobalElementId>,
6668        window: &mut Window,
6669        cx: &mut App,
6670    ) -> (gpui::LayoutId, ()) {
6671        let rem_size = self.rem_size(cx);
6672        window.with_rem_size(rem_size, |window| {
6673            self.editor.update(cx, |editor, cx| {
6674                editor.set_style(self.style.clone(), window, cx);
6675
6676                let layout_id = match editor.mode {
6677                    EditorMode::SingleLine { auto_width } => {
6678                        let rem_size = window.rem_size();
6679
6680                        let height = self.style.text.line_height_in_pixels(rem_size);
6681                        if auto_width {
6682                            let editor_handle = cx.entity().clone();
6683                            let style = self.style.clone();
6684                            window.request_measured_layout(
6685                                Style::default(),
6686                                move |_, _, window, cx| {
6687                                    let editor_snapshot = editor_handle
6688                                        .update(cx, |editor, cx| editor.snapshot(window, cx));
6689                                    let line = Self::layout_lines(
6690                                        DisplayRow(0)..DisplayRow(1),
6691                                        &editor_snapshot,
6692                                        &style,
6693                                        px(f32::MAX),
6694                                        |_| false, // Single lines never soft wrap
6695                                        window,
6696                                        cx,
6697                                    )
6698                                    .pop()
6699                                    .unwrap();
6700
6701                                    let font_id =
6702                                        window.text_system().resolve_font(&style.text.font());
6703                                    let font_size =
6704                                        style.text.font_size.to_pixels(window.rem_size());
6705                                    let em_width =
6706                                        window.text_system().em_width(font_id, font_size).unwrap();
6707
6708                                    size(line.width + em_width, height)
6709                                },
6710                            )
6711                        } else {
6712                            let mut style = Style::default();
6713                            style.size.height = height.into();
6714                            style.size.width = relative(1.).into();
6715                            window.request_layout(style, None, cx)
6716                        }
6717                    }
6718                    EditorMode::AutoHeight { max_lines } => {
6719                        let editor_handle = cx.entity().clone();
6720                        let max_line_number_width =
6721                            self.max_line_number_width(&editor.snapshot(window, cx), window, cx);
6722                        window.request_measured_layout(
6723                            Style::default(),
6724                            move |known_dimensions, available_space, window, cx| {
6725                                editor_handle
6726                                    .update(cx, |editor, cx| {
6727                                        compute_auto_height_layout(
6728                                            editor,
6729                                            max_lines,
6730                                            max_line_number_width,
6731                                            known_dimensions,
6732                                            available_space.width,
6733                                            window,
6734                                            cx,
6735                                        )
6736                                    })
6737                                    .unwrap_or_default()
6738                            },
6739                        )
6740                    }
6741                    EditorMode::Full => {
6742                        let mut style = Style::default();
6743                        style.size.width = relative(1.).into();
6744                        style.size.height = relative(1.).into();
6745                        window.request_layout(style, None, cx)
6746                    }
6747                };
6748
6749                (layout_id, ())
6750            })
6751        })
6752    }
6753
6754    fn prepaint(
6755        &mut self,
6756        _: Option<&GlobalElementId>,
6757        bounds: Bounds<Pixels>,
6758        _: &mut Self::RequestLayoutState,
6759        window: &mut Window,
6760        cx: &mut App,
6761    ) -> Self::PrepaintState {
6762        let text_style = TextStyleRefinement {
6763            font_size: Some(self.style.text.font_size),
6764            line_height: Some(self.style.text.line_height),
6765            ..Default::default()
6766        };
6767        let focus_handle = self.editor.focus_handle(cx);
6768        window.set_view_id(self.editor.entity_id());
6769        window.set_focus_handle(&focus_handle, cx);
6770
6771        let rem_size = self.rem_size(cx);
6772        window.with_rem_size(rem_size, |window| {
6773            window.with_text_style(Some(text_style), |window| {
6774                window.with_content_mask(Some(ContentMask { bounds }), |window| {
6775                    let mut snapshot = self
6776                        .editor
6777                        .update(cx, |editor, cx| editor.snapshot(window, cx));
6778                    let style = self.style.clone();
6779
6780                    let font_id = window.text_system().resolve_font(&style.text.font());
6781                    let font_size = style.text.font_size.to_pixels(window.rem_size());
6782                    let line_height = style.text.line_height_in_pixels(window.rem_size());
6783                    let em_width = window.text_system().em_width(font_id, font_size).unwrap();
6784                    let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
6785
6786                    let letter_size = size(em_width, line_height);
6787
6788                    let gutter_dimensions = snapshot
6789                        .gutter_dimensions(
6790                            font_id,
6791                            font_size,
6792                            self.max_line_number_width(&snapshot, window, cx),
6793                            cx,
6794                        )
6795                        .unwrap_or_default();
6796                    let text_width = bounds.size.width - gutter_dimensions.width;
6797
6798                    let editor_width =
6799                        text_width - gutter_dimensions.margin - em_width - style.scrollbar_width;
6800
6801                    snapshot = self.editor.update(cx, |editor, cx| {
6802                        editor.last_bounds = Some(bounds);
6803                        editor.gutter_dimensions = gutter_dimensions;
6804                        editor.set_visible_line_count(bounds.size.height / line_height, window, cx);
6805
6806                        if matches!(editor.mode, EditorMode::AutoHeight { .. }) {
6807                            snapshot
6808                        } else {
6809                            let wrap_width = match editor.soft_wrap_mode(cx) {
6810                                SoftWrap::GitDiff => None,
6811                                SoftWrap::None => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
6812                                SoftWrap::EditorWidth => Some(editor_width),
6813                                SoftWrap::Column(column) => Some(column as f32 * em_advance),
6814                                SoftWrap::Bounded(column) => {
6815                                    Some(editor_width.min(column as f32 * em_advance))
6816                                }
6817                            };
6818
6819                            if editor.set_wrap_width(wrap_width, cx) {
6820                                editor.snapshot(window, cx)
6821                            } else {
6822                                snapshot
6823                            }
6824                        }
6825                    });
6826
6827                    let wrap_guides = self
6828                        .editor
6829                        .read(cx)
6830                        .wrap_guides(cx)
6831                        .iter()
6832                        .map(|(guide, active)| (self.column_pixels(*guide, window, cx), *active))
6833                        .collect::<SmallVec<[_; 2]>>();
6834
6835                    let hitbox = window.insert_hitbox(bounds, false);
6836                    let gutter_hitbox =
6837                        window.insert_hitbox(gutter_bounds(bounds, gutter_dimensions), false);
6838                    let text_hitbox = window.insert_hitbox(
6839                        Bounds {
6840                            origin: gutter_hitbox.top_right(),
6841                            size: size(text_width, bounds.size.height),
6842                        },
6843                        false,
6844                    );
6845                    // Offset the content_bounds from the text_bounds by the gutter margin (which
6846                    // is roughly half a character wide) to make hit testing work more like how we want.
6847                    let content_origin =
6848                        text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
6849
6850                    let scrollbar_bounds =
6851                        Bounds::from_corners(content_origin, bounds.bottom_right());
6852
6853                    let height_in_lines = scrollbar_bounds.size.height / line_height;
6854
6855                    // NOTE: The max row number in the current file, minus one
6856                    let max_row = snapshot.max_point().row().as_f32();
6857
6858                    // NOTE: The max scroll position for the top of the window
6859                    let max_scroll_top = if matches!(snapshot.mode, EditorMode::AutoHeight { .. }) {
6860                        (max_row - height_in_lines + 1.).max(0.)
6861                    } else {
6862                        let settings = EditorSettings::get_global(cx);
6863                        match settings.scroll_beyond_last_line {
6864                            ScrollBeyondLastLine::OnePage => max_row,
6865                            ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
6866                            ScrollBeyondLastLine::VerticalScrollMargin => {
6867                                (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
6868                                    .max(0.)
6869                            }
6870                        }
6871                    };
6872
6873                    // TODO: Autoscrolling for both axes
6874                    let mut autoscroll_request = None;
6875                    let mut autoscroll_containing_element = false;
6876                    let mut autoscroll_horizontally = false;
6877                    self.editor.update(cx, |editor, cx| {
6878                        autoscroll_request = editor.autoscroll_request();
6879                        autoscroll_containing_element =
6880                            autoscroll_request.is_some() || editor.has_pending_selection();
6881                        // TODO: Is this horizontal or vertical?!
6882                        autoscroll_horizontally = editor.autoscroll_vertically(
6883                            bounds,
6884                            line_height,
6885                            max_scroll_top,
6886                            window,
6887                            cx,
6888                        );
6889                        snapshot = editor.snapshot(window, cx);
6890                    });
6891
6892                    let mut scroll_position = snapshot.scroll_position();
6893                    // The scroll position is a fractional point, the whole number of which represents
6894                    // the top of the window in terms of display rows.
6895                    let start_row = DisplayRow(scroll_position.y as u32);
6896                    let max_row = snapshot.max_point().row();
6897                    let end_row = cmp::min(
6898                        (scroll_position.y + height_in_lines).ceil() as u32,
6899                        max_row.next_row().0,
6900                    );
6901                    let end_row = DisplayRow(end_row);
6902
6903                    let row_infos = snapshot
6904                        .row_infos(start_row)
6905                        .take((start_row..end_row).len())
6906                        .collect::<Vec<RowInfo>>();
6907                    let is_row_soft_wrapped = |row: usize| {
6908                        row_infos
6909                            .get(row)
6910                            .map_or(true, |info| info.buffer_row.is_none())
6911                    };
6912
6913                    let start_anchor = if start_row == Default::default() {
6914                        Anchor::min()
6915                    } else {
6916                        snapshot.buffer_snapshot.anchor_before(
6917                            DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
6918                        )
6919                    };
6920                    let end_anchor = if end_row > max_row {
6921                        Anchor::max()
6922                    } else {
6923                        snapshot.buffer_snapshot.anchor_before(
6924                            DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
6925                        )
6926                    };
6927
6928                    let mut highlighted_rows = self
6929                        .editor
6930                        .update(cx, |editor, cx| editor.highlighted_display_rows(window, cx));
6931
6932                    let is_light = cx.theme().appearance().is_light();
6933
6934                    for (ix, row_info) in row_infos.iter().enumerate() {
6935                        let Some(diff_status) = row_info.diff_status else {
6936                            continue;
6937                        };
6938
6939                        let background_color = match diff_status.kind {
6940                            DiffHunkStatusKind::Added => cx.theme().colors().version_control_added,
6941                            DiffHunkStatusKind::Deleted => {
6942                                cx.theme().colors().version_control_deleted
6943                            }
6944                            DiffHunkStatusKind::Modified => {
6945                                debug_panic!("modified diff status for row info");
6946                                continue;
6947                            }
6948                        };
6949
6950                        let hunk_opacity = if is_light { 0.16 } else { 0.12 };
6951
6952                        let hollow_highlight = LineHighlight {
6953                            background: (background_color.opacity(if is_light {
6954                                0.08
6955                            } else {
6956                                0.06
6957                            }))
6958                            .into(),
6959                            border: Some(if is_light {
6960                                background_color.opacity(0.48)
6961                            } else {
6962                                background_color.opacity(0.36)
6963                            }),
6964                        };
6965
6966                        let filled_highlight =
6967                            solid_background(background_color.opacity(hunk_opacity)).into();
6968
6969                        let background = if Self::diff_hunk_hollow(diff_status, cx) {
6970                            hollow_highlight
6971                        } else {
6972                            filled_highlight
6973                        };
6974
6975                        highlighted_rows
6976                            .entry(start_row + DisplayRow(ix as u32))
6977                            .or_insert(background);
6978                    }
6979
6980                    let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
6981                        start_anchor..end_anchor,
6982                        &snapshot.display_snapshot,
6983                        cx.theme().colors(),
6984                    );
6985                    let highlighted_gutter_ranges =
6986                        self.editor.read(cx).gutter_highlights_in_range(
6987                            start_anchor..end_anchor,
6988                            &snapshot.display_snapshot,
6989                            cx,
6990                        );
6991
6992                    let redacted_ranges = self.editor.read(cx).redacted_ranges(
6993                        start_anchor..end_anchor,
6994                        &snapshot.display_snapshot,
6995                        cx,
6996                    );
6997
6998                    let (local_selections, selected_buffer_ids): (
6999                        Vec<Selection<Point>>,
7000                        Vec<BufferId>,
7001                    ) = self.editor.update(cx, |editor, cx| {
7002                        let all_selections = editor.selections.all::<Point>(cx);
7003                        let selected_buffer_ids = if editor.is_singleton(cx) {
7004                            Vec::new()
7005                        } else {
7006                            let mut selected_buffer_ids = Vec::with_capacity(all_selections.len());
7007
7008                            for selection in all_selections {
7009                                for buffer_id in snapshot
7010                                    .buffer_snapshot
7011                                    .buffer_ids_for_range(selection.range())
7012                                {
7013                                    if selected_buffer_ids.last() != Some(&buffer_id) {
7014                                        selected_buffer_ids.push(buffer_id);
7015                                    }
7016                                }
7017                            }
7018
7019                            selected_buffer_ids
7020                        };
7021
7022                        let mut selections = editor
7023                            .selections
7024                            .disjoint_in_range(start_anchor..end_anchor, cx);
7025                        selections.extend(editor.selections.pending(cx));
7026
7027                        (selections, selected_buffer_ids)
7028                    });
7029
7030                    let (selections, mut active_rows, newest_selection_head) = self
7031                        .layout_selections(
7032                            start_anchor,
7033                            end_anchor,
7034                            &local_selections,
7035                            &snapshot,
7036                            start_row,
7037                            end_row,
7038                            window,
7039                            cx,
7040                        );
7041                    let mut breakpoint_rows = self.editor.update(cx, |editor, cx| {
7042                        editor.active_breakpoints(start_row..end_row, window, cx)
7043                    });
7044                    if cx.has_flag::<Debugger>() {
7045                        for display_row in breakpoint_rows.keys() {
7046                            active_rows.entry(*display_row).or_default().breakpoint = true;
7047                        }
7048                    }
7049
7050                    let line_numbers = self.layout_line_numbers(
7051                        Some(&gutter_hitbox),
7052                        gutter_dimensions,
7053                        line_height,
7054                        scroll_position,
7055                        start_row..end_row,
7056                        &row_infos,
7057                        &active_rows,
7058                        newest_selection_head,
7059                        &snapshot,
7060                        window,
7061                        cx,
7062                    );
7063
7064                    // We add the gutter breakpoint indicator to breakpoint_rows after painting
7065                    // line numbers so we don't paint a line number debug accent color if a user
7066                    // has their mouse over that line when a breakpoint isn't there
7067                    if cx.has_flag::<Debugger>() {
7068                        let gutter_breakpoint_indicator =
7069                            self.editor.read(cx).gutter_breakpoint_indicator;
7070                        if let Some(gutter_breakpoint_point) = gutter_breakpoint_indicator {
7071                            breakpoint_rows
7072                                .entry(gutter_breakpoint_point.row())
7073                                .or_insert_with(|| {
7074                                    let position = snapshot.display_point_to_anchor(
7075                                        gutter_breakpoint_point,
7076                                        Bias::Left,
7077                                    );
7078                                    let breakpoint = Breakpoint {
7079                                        kind: BreakpointKind::Standard,
7080                                    };
7081
7082                                    (position, breakpoint)
7083                                });
7084                        }
7085                    }
7086
7087                    let mut expand_toggles =
7088                        window.with_element_namespace("expand_toggles", |window| {
7089                            self.layout_expand_toggles(
7090                                &gutter_hitbox,
7091                                gutter_dimensions,
7092                                em_width,
7093                                line_height,
7094                                scroll_position,
7095                                &row_infos,
7096                                window,
7097                                cx,
7098                            )
7099                        });
7100
7101                    let mut crease_toggles =
7102                        window.with_element_namespace("crease_toggles", |window| {
7103                            self.layout_crease_toggles(
7104                                start_row..end_row,
7105                                &row_infos,
7106                                &active_rows,
7107                                &snapshot,
7108                                window,
7109                                cx,
7110                            )
7111                        });
7112                    let crease_trailers =
7113                        window.with_element_namespace("crease_trailers", |window| {
7114                            self.layout_crease_trailers(
7115                                row_infos.iter().copied(),
7116                                &snapshot,
7117                                window,
7118                                cx,
7119                            )
7120                        });
7121
7122                    let display_hunks = self.layout_gutter_diff_hunks(
7123                        line_height,
7124                        &gutter_hitbox,
7125                        start_row..end_row,
7126                        &snapshot,
7127                        window,
7128                        cx,
7129                    );
7130
7131                    let mut line_layouts = Self::layout_lines(
7132                        start_row..end_row,
7133                        &snapshot,
7134                        &self.style,
7135                        editor_width,
7136                        is_row_soft_wrapped,
7137                        window,
7138                        cx,
7139                    );
7140
7141                    let longest_line_blame_width = self
7142                        .editor
7143                        .update(cx, |editor, cx| {
7144                            if !editor.show_git_blame_inline {
7145                                return None;
7146                            }
7147                            let blame = editor.blame.as_ref()?;
7148                            let blame_entry = blame
7149                                .update(cx, |blame, cx| {
7150                                    let row_infos =
7151                                        snapshot.row_infos(snapshot.longest_row()).next()?;
7152                                    blame.blame_for_rows(&[row_infos], cx).next()
7153                                })
7154                                .flatten()?;
7155                            let mut element = render_inline_blame_entry(
7156                                self.editor.clone(),
7157                                blame,
7158                                blame_entry,
7159                                &style,
7160                                cx,
7161                            );
7162                            let inline_blame_padding = INLINE_BLAME_PADDING_EM_WIDTHS * em_advance;
7163                            Some(
7164                                element
7165                                    .layout_as_root(AvailableSpace::min_size(), window, cx)
7166                                    .width
7167                                    + inline_blame_padding,
7168                            )
7169                        })
7170                        .unwrap_or(Pixels::ZERO);
7171
7172                    let longest_line_width = layout_line(
7173                        snapshot.longest_row(),
7174                        &snapshot,
7175                        &style,
7176                        editor_width,
7177                        is_row_soft_wrapped,
7178                        window,
7179                        cx,
7180                    )
7181                    .width;
7182
7183                    let scrollbar_range_data = ScrollbarRangeData::new(
7184                        scrollbar_bounds,
7185                        letter_size,
7186                        &snapshot,
7187                        longest_line_width,
7188                        longest_line_blame_width,
7189                        &style,
7190                        editor_width,
7191                        cx,
7192                    );
7193
7194                    let scroll_range_bounds = scrollbar_range_data.scroll_range;
7195                    let mut scroll_width = scroll_range_bounds.size.width;
7196
7197                    let sticky_header_excerpt = if snapshot.buffer_snapshot.show_headers() {
7198                        snapshot.sticky_header_excerpt(scroll_position.y)
7199                    } else {
7200                        None
7201                    };
7202                    let sticky_header_excerpt_id =
7203                        sticky_header_excerpt.as_ref().map(|top| top.excerpt.id);
7204
7205                    let blocks = window.with_element_namespace("blocks", |window| {
7206                        self.render_blocks(
7207                            start_row..end_row,
7208                            &snapshot,
7209                            &hitbox,
7210                            &text_hitbox,
7211                            editor_width,
7212                            &mut scroll_width,
7213                            &gutter_dimensions,
7214                            em_width,
7215                            gutter_dimensions.full_width(),
7216                            line_height,
7217                            &line_layouts,
7218                            &local_selections,
7219                            &selected_buffer_ids,
7220                            is_row_soft_wrapped,
7221                            sticky_header_excerpt_id,
7222                            window,
7223                            cx,
7224                        )
7225                    });
7226                    let mut blocks = match blocks {
7227                        Ok(blocks) => blocks,
7228                        Err(resized_blocks) => {
7229                            self.editor.update(cx, |editor, cx| {
7230                                editor.resize_blocks(resized_blocks, autoscroll_request, cx)
7231                            });
7232                            return self.prepaint(None, bounds, &mut (), window, cx);
7233                        }
7234                    };
7235
7236                    let sticky_buffer_header = sticky_header_excerpt.map(|sticky_header_excerpt| {
7237                        window.with_element_namespace("blocks", |window| {
7238                            self.layout_sticky_buffer_header(
7239                                sticky_header_excerpt,
7240                                scroll_position.y,
7241                                line_height,
7242                                &snapshot,
7243                                &hitbox,
7244                                &selected_buffer_ids,
7245                                &blocks,
7246                                window,
7247                                cx,
7248                            )
7249                        })
7250                    });
7251
7252                    let start_buffer_row =
7253                        MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
7254                    let end_buffer_row =
7255                        MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
7256
7257                    let scroll_max = point(
7258                        ((scroll_width - scrollbar_bounds.size.width) / em_width).max(0.0),
7259                        max_row.as_f32(),
7260                    );
7261
7262                    self.editor.update(cx, |editor, cx| {
7263                        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
7264
7265                        let autoscrolled = if autoscroll_horizontally {
7266                            editor.autoscroll_horizontally(
7267                                start_row,
7268                                editor_width - (letter_size.width / 2.0) + style.scrollbar_width,
7269                                scroll_width,
7270                                em_width,
7271                                &line_layouts,
7272                                cx,
7273                            )
7274                        } else {
7275                            false
7276                        };
7277
7278                        if clamped || autoscrolled {
7279                            snapshot = editor.snapshot(window, cx);
7280                            scroll_position = snapshot.scroll_position();
7281                        }
7282                    });
7283
7284                    let scroll_pixel_position = point(
7285                        scroll_position.x * em_width,
7286                        scroll_position.y * line_height,
7287                    );
7288
7289                    let indent_guides = self.layout_indent_guides(
7290                        content_origin,
7291                        text_hitbox.origin,
7292                        start_buffer_row..end_buffer_row,
7293                        scroll_pixel_position,
7294                        line_height,
7295                        &snapshot,
7296                        window,
7297                        cx,
7298                    );
7299
7300                    let crease_trailers =
7301                        window.with_element_namespace("crease_trailers", |window| {
7302                            self.prepaint_crease_trailers(
7303                                crease_trailers,
7304                                &line_layouts,
7305                                line_height,
7306                                content_origin,
7307                                scroll_pixel_position,
7308                                em_width,
7309                                window,
7310                                cx,
7311                            )
7312                        });
7313
7314                    let (inline_completion_popover, inline_completion_popover_origin) = self
7315                        .editor
7316                        .update(cx, |editor, cx| {
7317                            editor.render_edit_prediction_popover(
7318                                &text_hitbox.bounds,
7319                                content_origin,
7320                                &snapshot,
7321                                start_row..end_row,
7322                                scroll_position.y,
7323                                scroll_position.y + height_in_lines,
7324                                &line_layouts,
7325                                line_height,
7326                                scroll_pixel_position,
7327                                newest_selection_head,
7328                                editor_width,
7329                                &style,
7330                                window,
7331                                cx,
7332                            )
7333                        })
7334                        .unzip();
7335
7336                    let mut inline_diagnostics = self.layout_inline_diagnostics(
7337                        &line_layouts,
7338                        &crease_trailers,
7339                        content_origin,
7340                        scroll_pixel_position,
7341                        inline_completion_popover_origin,
7342                        start_row,
7343                        end_row,
7344                        line_height,
7345                        em_width,
7346                        &style,
7347                        window,
7348                        cx,
7349                    );
7350
7351                    let mut inline_blame = None;
7352                    if let Some(newest_selection_head) = newest_selection_head {
7353                        let display_row = newest_selection_head.row();
7354                        if (start_row..end_row).contains(&display_row) {
7355                            let line_ix = display_row.minus(start_row) as usize;
7356                            let row_info = &row_infos[line_ix];
7357                            let line_layout = &line_layouts[line_ix];
7358                            let crease_trailer_layout = crease_trailers[line_ix].as_ref();
7359                            inline_blame = self.layout_inline_blame(
7360                                display_row,
7361                                row_info,
7362                                line_layout,
7363                                crease_trailer_layout,
7364                                em_width,
7365                                content_origin,
7366                                scroll_pixel_position,
7367                                line_height,
7368                                window,
7369                                cx,
7370                            );
7371                            if inline_blame.is_some() {
7372                                // Blame overrides inline diagnostics
7373                                inline_diagnostics.remove(&display_row);
7374                            }
7375                        }
7376                    }
7377
7378                    let blamed_display_rows = self.layout_blame_entries(
7379                        &row_infos,
7380                        em_width,
7381                        scroll_position,
7382                        line_height,
7383                        &gutter_hitbox,
7384                        gutter_dimensions.git_blame_entries_width,
7385                        window,
7386                        cx,
7387                    );
7388
7389                    let scroll_max = point(
7390                        ((scroll_width - scrollbar_bounds.size.width) / em_width).max(0.0),
7391                        max_scroll_top,
7392                    );
7393
7394                    self.editor.update(cx, |editor, cx| {
7395                        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
7396
7397                        let autoscrolled = if autoscroll_horizontally {
7398                            editor.autoscroll_horizontally(
7399                                start_row,
7400                                editor_width - (letter_size.width / 2.0) + style.scrollbar_width,
7401                                scroll_width,
7402                                em_width,
7403                                &line_layouts,
7404                                cx,
7405                            )
7406                        } else {
7407                            false
7408                        };
7409
7410                        if clamped || autoscrolled {
7411                            snapshot = editor.snapshot(window, cx);
7412                            scroll_position = snapshot.scroll_position();
7413                        }
7414                    });
7415
7416                    let line_elements = self.prepaint_lines(
7417                        start_row,
7418                        &mut line_layouts,
7419                        line_height,
7420                        scroll_pixel_position,
7421                        content_origin,
7422                        window,
7423                        cx,
7424                    );
7425
7426                    let mut block_start_rows = HashSet::default();
7427
7428                    window.with_element_namespace("blocks", |window| {
7429                        self.layout_blocks(
7430                            &mut blocks,
7431                            &mut block_start_rows,
7432                            &hitbox,
7433                            line_height,
7434                            scroll_pixel_position,
7435                            window,
7436                            cx,
7437                        );
7438                    });
7439
7440                    let cursors = self.collect_cursors(&snapshot, cx);
7441                    let visible_row_range = start_row..end_row;
7442                    let non_visible_cursors = cursors
7443                        .iter()
7444                        .any(|c| !visible_row_range.contains(&c.0.row()));
7445
7446                    let visible_cursors = self.layout_visible_cursors(
7447                        &snapshot,
7448                        &selections,
7449                        &block_start_rows,
7450                        start_row..end_row,
7451                        &line_layouts,
7452                        &text_hitbox,
7453                        content_origin,
7454                        scroll_position,
7455                        scroll_pixel_position,
7456                        line_height,
7457                        em_width,
7458                        em_advance,
7459                        autoscroll_containing_element,
7460                        window,
7461                        cx,
7462                    );
7463
7464                    let scrollbars_layout = self.layout_scrollbars(
7465                        &snapshot,
7466                        scrollbar_range_data,
7467                        scroll_position,
7468                        non_visible_cursors,
7469                        window,
7470                        cx,
7471                    );
7472
7473                    let gutter_settings = EditorSettings::get_global(cx).gutter;
7474
7475                    let mut code_actions_indicator = None;
7476                    if let Some(newest_selection_head) = newest_selection_head {
7477                        let newest_selection_point =
7478                            newest_selection_head.to_point(&snapshot.display_snapshot);
7479
7480                        if (start_row..end_row).contains(&newest_selection_head.row()) {
7481                            self.layout_cursor_popovers(
7482                                line_height,
7483                                &text_hitbox,
7484                                content_origin,
7485                                start_row,
7486                                scroll_pixel_position,
7487                                &line_layouts,
7488                                newest_selection_head,
7489                                newest_selection_point,
7490                                &style,
7491                                window,
7492                                cx,
7493                            );
7494
7495                            let show_code_actions = snapshot
7496                                .show_code_actions
7497                                .unwrap_or(gutter_settings.code_actions);
7498                            if show_code_actions {
7499                                let newest_selection_point =
7500                                    newest_selection_head.to_point(&snapshot.display_snapshot);
7501                                if !snapshot
7502                                    .is_line_folded(MultiBufferRow(newest_selection_point.row))
7503                                {
7504                                    let buffer = snapshot.buffer_snapshot.buffer_line_for_row(
7505                                        MultiBufferRow(newest_selection_point.row),
7506                                    );
7507                                    if let Some((buffer, range)) = buffer {
7508                                        let buffer_id = buffer.remote_id();
7509                                        let row = range.start.row;
7510                                        let has_test_indicator = self
7511                                            .editor
7512                                            .read(cx)
7513                                            .tasks
7514                                            .contains_key(&(buffer_id, row));
7515
7516                                        let has_expand_indicator = row_infos
7517                                            .get(
7518                                                (newest_selection_head.row() - start_row).0
7519                                                    as usize,
7520                                            )
7521                                            .is_some_and(|row_info| row_info.expand_info.is_some());
7522
7523                                        if !has_test_indicator && !has_expand_indicator {
7524                                            code_actions_indicator = self
7525                                                .layout_code_actions_indicator(
7526                                                    line_height,
7527                                                    newest_selection_head,
7528                                                    scroll_pixel_position,
7529                                                    &gutter_dimensions,
7530                                                    &gutter_hitbox,
7531                                                    &mut breakpoint_rows,
7532                                                    &display_hunks,
7533                                                    window,
7534                                                    cx,
7535                                                );
7536                                        }
7537                                    }
7538                                }
7539                            }
7540                        }
7541                    }
7542
7543                    self.layout_gutter_menu(
7544                        line_height,
7545                        &text_hitbox,
7546                        content_origin,
7547                        scroll_pixel_position,
7548                        gutter_dimensions.width - gutter_dimensions.left_padding,
7549                        window,
7550                        cx,
7551                    );
7552
7553                    let test_indicators = if gutter_settings.runnables {
7554                        self.layout_run_indicators(
7555                            line_height,
7556                            start_row..end_row,
7557                            &row_infos,
7558                            scroll_pixel_position,
7559                            &gutter_dimensions,
7560                            &gutter_hitbox,
7561                            &display_hunks,
7562                            &snapshot,
7563                            &mut breakpoint_rows,
7564                            window,
7565                            cx,
7566                        )
7567                    } else {
7568                        Vec::new()
7569                    };
7570
7571                    let show_breakpoints = snapshot
7572                        .show_breakpoints
7573                        .unwrap_or(gutter_settings.breakpoints);
7574                    let breakpoints = if cx.has_flag::<Debugger>() && show_breakpoints {
7575                        self.layout_breakpoints(
7576                            line_height,
7577                            start_row..end_row,
7578                            scroll_pixel_position,
7579                            &gutter_dimensions,
7580                            &gutter_hitbox,
7581                            &display_hunks,
7582                            &snapshot,
7583                            breakpoint_rows,
7584                            &row_infos,
7585                            window,
7586                            cx,
7587                        )
7588                    } else {
7589                        vec![]
7590                    };
7591
7592                    self.layout_signature_help(
7593                        &hitbox,
7594                        content_origin,
7595                        scroll_pixel_position,
7596                        newest_selection_head,
7597                        start_row,
7598                        &line_layouts,
7599                        line_height,
7600                        em_width,
7601                        window,
7602                        cx,
7603                    );
7604
7605                    if !cx.has_active_drag() {
7606                        self.layout_hover_popovers(
7607                            &snapshot,
7608                            &hitbox,
7609                            &text_hitbox,
7610                            start_row..end_row,
7611                            content_origin,
7612                            scroll_pixel_position,
7613                            &line_layouts,
7614                            line_height,
7615                            em_width,
7616                            window,
7617                            cx,
7618                        );
7619                    }
7620
7621                    let mouse_context_menu = self.layout_mouse_context_menu(
7622                        &snapshot,
7623                        start_row..end_row,
7624                        content_origin,
7625                        window,
7626                        cx,
7627                    );
7628
7629                    window.with_element_namespace("crease_toggles", |window| {
7630                        self.prepaint_crease_toggles(
7631                            &mut crease_toggles,
7632                            line_height,
7633                            &gutter_dimensions,
7634                            gutter_settings,
7635                            scroll_pixel_position,
7636                            &gutter_hitbox,
7637                            window,
7638                            cx,
7639                        )
7640                    });
7641
7642                    window.with_element_namespace("expand_toggles", |window| {
7643                        self.prepaint_expand_toggles(&mut expand_toggles, window, cx)
7644                    });
7645
7646                    let invisible_symbol_font_size = font_size / 2.;
7647                    let tab_invisible = window
7648                        .text_system()
7649                        .shape_line(
7650                            "".into(),
7651                            invisible_symbol_font_size,
7652                            &[TextRun {
7653                                len: "".len(),
7654                                font: self.style.text.font(),
7655                                color: cx.theme().colors().editor_invisible,
7656                                background_color: None,
7657                                underline: None,
7658                                strikethrough: None,
7659                            }],
7660                        )
7661                        .unwrap();
7662                    let space_invisible = window
7663                        .text_system()
7664                        .shape_line(
7665                            "".into(),
7666                            invisible_symbol_font_size,
7667                            &[TextRun {
7668                                len: "".len(),
7669                                font: self.style.text.font(),
7670                                color: cx.theme().colors().editor_invisible,
7671                                background_color: None,
7672                                underline: None,
7673                                strikethrough: None,
7674                            }],
7675                        )
7676                        .unwrap();
7677
7678                    let mode = snapshot.mode;
7679
7680                    let position_map = Rc::new(PositionMap {
7681                        size: bounds.size,
7682                        visible_row_range,
7683                        scroll_pixel_position,
7684                        scroll_max,
7685                        line_layouts,
7686                        line_height,
7687                        em_width,
7688                        em_advance,
7689                        snapshot,
7690                        gutter_hitbox: gutter_hitbox.clone(),
7691                        text_hitbox: text_hitbox.clone(),
7692                    });
7693
7694                    self.editor.update(cx, |editor, _| {
7695                        editor.last_position_map = Some(position_map.clone())
7696                    });
7697
7698                    let diff_hunk_controls = self.layout_diff_hunk_controls(
7699                        start_row..end_row,
7700                        &row_infos,
7701                        &text_hitbox,
7702                        &position_map,
7703                        newest_selection_head,
7704                        line_height,
7705                        scroll_pixel_position,
7706                        &display_hunks,
7707                        self.editor.clone(),
7708                        window,
7709                        cx,
7710                    );
7711
7712                    EditorLayout {
7713                        mode,
7714                        position_map,
7715                        visible_display_row_range: start_row..end_row,
7716                        wrap_guides,
7717                        indent_guides,
7718                        hitbox,
7719                        gutter_hitbox,
7720                        display_hunks,
7721                        content_origin,
7722                        scrollbars_layout,
7723                        active_rows,
7724                        highlighted_rows,
7725                        highlighted_ranges,
7726                        highlighted_gutter_ranges,
7727                        redacted_ranges,
7728                        line_elements,
7729                        line_numbers,
7730                        blamed_display_rows,
7731                        inline_diagnostics,
7732                        inline_blame,
7733                        blocks,
7734                        cursors,
7735                        visible_cursors,
7736                        selections,
7737                        inline_completion_popover,
7738                        diff_hunk_controls,
7739                        mouse_context_menu,
7740                        test_indicators,
7741                        breakpoints,
7742                        code_actions_indicator,
7743                        crease_toggles,
7744                        crease_trailers,
7745                        tab_invisible,
7746                        space_invisible,
7747                        sticky_buffer_header,
7748                        expand_toggles,
7749                    }
7750                })
7751            })
7752        })
7753    }
7754
7755    fn paint(
7756        &mut self,
7757        _: Option<&GlobalElementId>,
7758        bounds: Bounds<gpui::Pixels>,
7759        _: &mut Self::RequestLayoutState,
7760        layout: &mut Self::PrepaintState,
7761        window: &mut Window,
7762        cx: &mut App,
7763    ) {
7764        let focus_handle = self.editor.focus_handle(cx);
7765        let key_context = self
7766            .editor
7767            .update(cx, |editor, cx| editor.key_context(window, cx));
7768
7769        window.set_key_context(key_context);
7770        window.handle_input(
7771            &focus_handle,
7772            ElementInputHandler::new(bounds, self.editor.clone()),
7773            cx,
7774        );
7775        self.register_actions(window, cx);
7776        self.register_key_listeners(window, cx, layout);
7777
7778        let text_style = TextStyleRefinement {
7779            font_size: Some(self.style.text.font_size),
7780            line_height: Some(self.style.text.line_height),
7781            ..Default::default()
7782        };
7783        let rem_size = self.rem_size(cx);
7784        window.with_rem_size(rem_size, |window| {
7785            window.with_text_style(Some(text_style), |window| {
7786                window.with_content_mask(Some(ContentMask { bounds }), |window| {
7787                    self.paint_mouse_listeners(layout, window, cx);
7788                    self.paint_background(layout, window, cx);
7789                    self.paint_indent_guides(layout, window, cx);
7790
7791                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
7792                        self.paint_blamed_display_rows(layout, window, cx);
7793                        self.paint_line_numbers(layout, window, cx);
7794                    }
7795
7796                    self.paint_text(layout, window, cx);
7797
7798                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
7799                        self.paint_gutter_highlights(layout, window, cx);
7800                        self.paint_gutter_indicators(layout, window, cx);
7801                    }
7802
7803                    if !layout.blocks.is_empty() {
7804                        window.with_element_namespace("blocks", |window| {
7805                            self.paint_blocks(layout, window, cx);
7806                        });
7807                    }
7808
7809                    window.with_element_namespace("blocks", |window| {
7810                        if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
7811                            sticky_header.paint(window, cx)
7812                        }
7813                    });
7814
7815                    self.paint_scrollbars(layout, window, cx);
7816                    self.paint_inline_completion_popover(layout, window, cx);
7817                    self.paint_mouse_context_menu(layout, window, cx);
7818                });
7819            })
7820        })
7821    }
7822}
7823
7824pub(super) fn gutter_bounds(
7825    editor_bounds: Bounds<Pixels>,
7826    gutter_dimensions: GutterDimensions,
7827) -> Bounds<Pixels> {
7828    Bounds {
7829        origin: editor_bounds.origin,
7830        size: size(gutter_dimensions.width, editor_bounds.size.height),
7831    }
7832}
7833
7834struct ScrollbarRangeData {
7835    scrollbar_bounds: Bounds<Pixels>,
7836    scroll_range: Bounds<Pixels>,
7837    letter_size: Size<Pixels>,
7838}
7839
7840impl ScrollbarRangeData {
7841    pub fn new(
7842        scrollbar_bounds: Bounds<Pixels>,
7843        letter_size: Size<Pixels>,
7844        snapshot: &EditorSnapshot,
7845        longest_line_width: Pixels,
7846        longest_line_blame_width: Pixels,
7847        style: &EditorStyle,
7848        editor_width: Pixels,
7849        cx: &mut App,
7850    ) -> ScrollbarRangeData {
7851        // TODO: Simplify this function down, it requires a lot of parameters
7852        let max_row = snapshot.max_point().row();
7853        let text_bounds_size = size(longest_line_width, max_row.0 as f32 * letter_size.height);
7854
7855        let settings = EditorSettings::get_global(cx);
7856        let scroll_beyond_last_line: Pixels = match settings.scroll_beyond_last_line {
7857            ScrollBeyondLastLine::OnePage => px(scrollbar_bounds.size.height / letter_size.height),
7858            ScrollBeyondLastLine::Off => px(1.),
7859            ScrollBeyondLastLine::VerticalScrollMargin => px(1.0 + settings.vertical_scroll_margin),
7860        };
7861
7862        let right_margin = if longest_line_width + longest_line_blame_width >= editor_width {
7863            letter_size.width + style.scrollbar_width
7864        } else {
7865            px(0.0)
7866        };
7867
7868        let overscroll = size(
7869            right_margin + longest_line_blame_width,
7870            letter_size.height * scroll_beyond_last_line,
7871        );
7872
7873        let scroll_range = Bounds {
7874            origin: scrollbar_bounds.origin,
7875            size: text_bounds_size + overscroll,
7876        };
7877
7878        ScrollbarRangeData {
7879            scrollbar_bounds,
7880            scroll_range,
7881            letter_size,
7882        }
7883    }
7884}
7885
7886impl IntoElement for EditorElement {
7887    type Element = Self;
7888
7889    fn into_element(self) -> Self::Element {
7890        self
7891    }
7892}
7893
7894pub struct EditorLayout {
7895    position_map: Rc<PositionMap>,
7896    hitbox: Hitbox,
7897    gutter_hitbox: Hitbox,
7898    content_origin: gpui::Point<Pixels>,
7899    scrollbars_layout: AxisPair<Option<ScrollbarLayout>>,
7900    mode: EditorMode,
7901    wrap_guides: SmallVec<[(Pixels, bool); 2]>,
7902    indent_guides: Option<Vec<IndentGuideLayout>>,
7903    visible_display_row_range: Range<DisplayRow>,
7904    active_rows: BTreeMap<DisplayRow, LineHighlightSpec>,
7905    highlighted_rows: BTreeMap<DisplayRow, LineHighlight>,
7906    line_elements: SmallVec<[AnyElement; 1]>,
7907    line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
7908    display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
7909    blamed_display_rows: Option<Vec<AnyElement>>,
7910    inline_diagnostics: HashMap<DisplayRow, AnyElement>,
7911    inline_blame: Option<AnyElement>,
7912    blocks: Vec<BlockLayout>,
7913    highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
7914    highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
7915    redacted_ranges: Vec<Range<DisplayPoint>>,
7916    cursors: Vec<(DisplayPoint, Hsla)>,
7917    visible_cursors: Vec<CursorLayout>,
7918    selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
7919    code_actions_indicator: Option<AnyElement>,
7920    test_indicators: Vec<AnyElement>,
7921    breakpoints: Vec<AnyElement>,
7922    crease_toggles: Vec<Option<AnyElement>>,
7923    expand_toggles: Vec<Option<(AnyElement, gpui::Point<Pixels>)>>,
7924    diff_hunk_controls: Vec<AnyElement>,
7925    crease_trailers: Vec<Option<CreaseTrailerLayout>>,
7926    inline_completion_popover: Option<AnyElement>,
7927    mouse_context_menu: Option<AnyElement>,
7928    tab_invisible: ShapedLine,
7929    space_invisible: ShapedLine,
7930    sticky_buffer_header: Option<AnyElement>,
7931}
7932
7933impl EditorLayout {
7934    fn line_end_overshoot(&self) -> Pixels {
7935        0.15 * self.position_map.line_height
7936    }
7937}
7938
7939struct LineNumberLayout {
7940    shaped_line: ShapedLine,
7941    hitbox: Option<Hitbox>,
7942}
7943
7944struct ColoredRange<T> {
7945    start: T,
7946    end: T,
7947    color: Hsla,
7948}
7949
7950#[derive(Clone)]
7951struct ScrollbarLayout {
7952    hitbox: Hitbox,
7953    visible_range: Range<f32>,
7954    visible: bool,
7955    text_unit_size: Pixels,
7956    thumb_size: Pixels,
7957    axis: Axis,
7958}
7959
7960impl ScrollbarLayout {
7961    const BORDER_WIDTH: Pixels = px(1.0);
7962    const LINE_MARKER_HEIGHT: Pixels = px(2.0);
7963    const MIN_MARKER_HEIGHT: Pixels = px(5.0);
7964    // const MIN_THUMB_HEIGHT: Pixels = px(20.0);
7965
7966    fn thumb_bounds(&self) -> Bounds<Pixels> {
7967        match self.axis {
7968            Axis::Vertical => {
7969                let thumb_top = self.y_for_row(self.visible_range.start);
7970                let thumb_bottom = thumb_top + self.thumb_size;
7971                Bounds::from_corners(
7972                    point(self.hitbox.left(), thumb_top),
7973                    point(self.hitbox.right(), thumb_bottom),
7974                )
7975            }
7976            Axis::Horizontal => {
7977                let thumb_left =
7978                    self.hitbox.left() + self.visible_range.start * self.text_unit_size;
7979                let thumb_right = thumb_left + self.thumb_size;
7980                Bounds::from_corners(
7981                    point(thumb_left, self.hitbox.top()),
7982                    point(thumb_right, self.hitbox.bottom()),
7983                )
7984            }
7985        }
7986    }
7987
7988    fn y_for_row(&self, row: f32) -> Pixels {
7989        self.hitbox.top() + row * self.text_unit_size
7990    }
7991
7992    fn marker_quads_for_ranges(
7993        &self,
7994        row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
7995        column: Option<usize>,
7996    ) -> Vec<PaintQuad> {
7997        struct MinMax {
7998            min: Pixels,
7999            max: Pixels,
8000        }
8001        let (x_range, height_limit) = if let Some(column) = column {
8002            let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
8003            let start = Self::BORDER_WIDTH + (column as f32 * column_width);
8004            let end = start + column_width;
8005            (
8006                Range { start, end },
8007                MinMax {
8008                    min: Self::MIN_MARKER_HEIGHT,
8009                    max: px(f32::MAX),
8010                },
8011            )
8012        } else {
8013            (
8014                Range {
8015                    start: Self::BORDER_WIDTH,
8016                    end: self.hitbox.size.width,
8017                },
8018                MinMax {
8019                    min: Self::LINE_MARKER_HEIGHT,
8020                    max: Self::LINE_MARKER_HEIGHT,
8021                },
8022            )
8023        };
8024
8025        let row_to_y = |row: DisplayRow| row.as_f32() * self.text_unit_size;
8026        let mut pixel_ranges = row_ranges
8027            .into_iter()
8028            .map(|range| {
8029                let start_y = row_to_y(range.start);
8030                let end_y = row_to_y(range.end)
8031                    + self
8032                        .text_unit_size
8033                        .max(height_limit.min)
8034                        .min(height_limit.max);
8035                ColoredRange {
8036                    start: start_y,
8037                    end: end_y,
8038                    color: range.color,
8039                }
8040            })
8041            .peekable();
8042
8043        let mut quads = Vec::new();
8044        while let Some(mut pixel_range) = pixel_ranges.next() {
8045            while let Some(next_pixel_range) = pixel_ranges.peek() {
8046                if pixel_range.end >= next_pixel_range.start - px(1.0)
8047                    && pixel_range.color == next_pixel_range.color
8048                {
8049                    pixel_range.end = next_pixel_range.end.max(pixel_range.end);
8050                    pixel_ranges.next();
8051                } else {
8052                    break;
8053                }
8054            }
8055
8056            let bounds = Bounds::from_corners(
8057                point(x_range.start, pixel_range.start),
8058                point(x_range.end, pixel_range.end),
8059            );
8060            quads.push(quad(
8061                bounds,
8062                Corners::default(),
8063                pixel_range.color,
8064                Edges::default(),
8065                Hsla::transparent_black(),
8066            ));
8067        }
8068
8069        quads
8070    }
8071}
8072
8073struct CreaseTrailerLayout {
8074    element: AnyElement,
8075    bounds: Bounds<Pixels>,
8076}
8077
8078pub(crate) struct PositionMap {
8079    pub size: Size<Pixels>,
8080    pub line_height: Pixels,
8081    pub scroll_pixel_position: gpui::Point<Pixels>,
8082    pub scroll_max: gpui::Point<f32>,
8083    pub em_width: Pixels,
8084    pub em_advance: Pixels,
8085    pub visible_row_range: Range<DisplayRow>,
8086    pub line_layouts: Vec<LineWithInvisibles>,
8087    pub snapshot: EditorSnapshot,
8088    pub text_hitbox: Hitbox,
8089    pub gutter_hitbox: Hitbox,
8090}
8091
8092#[derive(Debug, Copy, Clone)]
8093pub struct PointForPosition {
8094    pub previous_valid: DisplayPoint,
8095    pub next_valid: DisplayPoint,
8096    pub exact_unclipped: DisplayPoint,
8097    pub column_overshoot_after_line_end: u32,
8098}
8099
8100impl PointForPosition {
8101    pub fn as_valid(&self) -> Option<DisplayPoint> {
8102        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
8103            Some(self.previous_valid)
8104        } else {
8105            None
8106        }
8107    }
8108}
8109
8110impl PositionMap {
8111    pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
8112        let text_bounds = self.text_hitbox.bounds;
8113        let scroll_position = self.snapshot.scroll_position();
8114        let position = position - text_bounds.origin;
8115        let y = position.y.max(px(0.)).min(self.size.height);
8116        let x = position.x + (scroll_position.x * self.em_width);
8117        let row = ((y / self.line_height) + scroll_position.y) as u32;
8118
8119        let (column, x_overshoot_after_line_end) = if let Some(line) = self
8120            .line_layouts
8121            .get(row as usize - scroll_position.y as usize)
8122        {
8123            if let Some(ix) = line.index_for_x(x) {
8124                (ix as u32, px(0.))
8125            } else {
8126                (line.len as u32, px(0.).max(x - line.width))
8127            }
8128        } else {
8129            (0, x)
8130        };
8131
8132        let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
8133        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
8134        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
8135
8136        let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
8137        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
8138        PointForPosition {
8139            previous_valid,
8140            next_valid,
8141            exact_unclipped,
8142            column_overshoot_after_line_end,
8143        }
8144    }
8145}
8146
8147struct BlockLayout {
8148    id: BlockId,
8149    row: Option<DisplayRow>,
8150    element: AnyElement,
8151    available_space: Size<AvailableSpace>,
8152    style: BlockStyle,
8153    is_buffer_header: bool,
8154}
8155
8156pub fn layout_line(
8157    row: DisplayRow,
8158    snapshot: &EditorSnapshot,
8159    style: &EditorStyle,
8160    text_width: Pixels,
8161    is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
8162    window: &mut Window,
8163    cx: &mut App,
8164) -> LineWithInvisibles {
8165    let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
8166    LineWithInvisibles::from_chunks(
8167        chunks,
8168        &style,
8169        MAX_LINE_LEN,
8170        1,
8171        snapshot.mode,
8172        text_width,
8173        is_row_soft_wrapped,
8174        window,
8175        cx,
8176    )
8177    .pop()
8178    .unwrap()
8179}
8180
8181#[derive(Debug)]
8182pub struct IndentGuideLayout {
8183    origin: gpui::Point<Pixels>,
8184    length: Pixels,
8185    single_indent_width: Pixels,
8186    depth: u32,
8187    active: bool,
8188    settings: IndentGuideSettings,
8189}
8190
8191pub struct CursorLayout {
8192    origin: gpui::Point<Pixels>,
8193    block_width: Pixels,
8194    line_height: Pixels,
8195    color: Hsla,
8196    shape: CursorShape,
8197    block_text: Option<ShapedLine>,
8198    cursor_name: Option<AnyElement>,
8199}
8200
8201#[derive(Debug)]
8202pub struct CursorName {
8203    string: SharedString,
8204    color: Hsla,
8205    is_top_row: bool,
8206}
8207
8208impl CursorLayout {
8209    pub fn new(
8210        origin: gpui::Point<Pixels>,
8211        block_width: Pixels,
8212        line_height: Pixels,
8213        color: Hsla,
8214        shape: CursorShape,
8215        block_text: Option<ShapedLine>,
8216    ) -> CursorLayout {
8217        CursorLayout {
8218            origin,
8219            block_width,
8220            line_height,
8221            color,
8222            shape,
8223            block_text,
8224            cursor_name: None,
8225        }
8226    }
8227
8228    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
8229        Bounds {
8230            origin: self.origin + origin,
8231            size: size(self.block_width, self.line_height),
8232        }
8233    }
8234
8235    fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
8236        match self.shape {
8237            CursorShape::Bar => Bounds {
8238                origin: self.origin + origin,
8239                size: size(px(2.0), self.line_height),
8240            },
8241            CursorShape::Block | CursorShape::Hollow => Bounds {
8242                origin: self.origin + origin,
8243                size: size(self.block_width, self.line_height),
8244            },
8245            CursorShape::Underline => Bounds {
8246                origin: self.origin
8247                    + origin
8248                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
8249                size: size(self.block_width, px(2.0)),
8250            },
8251        }
8252    }
8253
8254    pub fn layout(
8255        &mut self,
8256        origin: gpui::Point<Pixels>,
8257        cursor_name: Option<CursorName>,
8258        window: &mut Window,
8259        cx: &mut App,
8260    ) {
8261        if let Some(cursor_name) = cursor_name {
8262            let bounds = self.bounds(origin);
8263            let text_size = self.line_height / 1.5;
8264
8265            let name_origin = if cursor_name.is_top_row {
8266                point(bounds.right() - px(1.), bounds.top())
8267            } else {
8268                match self.shape {
8269                    CursorShape::Bar => point(
8270                        bounds.right() - px(2.),
8271                        bounds.top() - text_size / 2. - px(1.),
8272                    ),
8273                    _ => point(
8274                        bounds.right() - px(1.),
8275                        bounds.top() - text_size / 2. - px(1.),
8276                    ),
8277                }
8278            };
8279            let mut name_element = div()
8280                .bg(self.color)
8281                .text_size(text_size)
8282                .px_0p5()
8283                .line_height(text_size + px(2.))
8284                .text_color(cursor_name.color)
8285                .child(cursor_name.string.clone())
8286                .into_any_element();
8287
8288            name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
8289
8290            self.cursor_name = Some(name_element);
8291        }
8292    }
8293
8294    pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
8295        let bounds = self.bounds(origin);
8296
8297        //Draw background or border quad
8298        let cursor = if matches!(self.shape, CursorShape::Hollow) {
8299            outline(bounds, self.color)
8300        } else {
8301            fill(bounds, self.color)
8302        };
8303
8304        if let Some(name) = &mut self.cursor_name {
8305            name.paint(window, cx);
8306        }
8307
8308        window.paint_quad(cursor);
8309
8310        if let Some(block_text) = &self.block_text {
8311            block_text
8312                .paint(self.origin + origin, self.line_height, window, cx)
8313                .log_err();
8314        }
8315    }
8316
8317    pub fn shape(&self) -> CursorShape {
8318        self.shape
8319    }
8320}
8321
8322#[derive(Debug)]
8323pub struct HighlightedRange {
8324    pub start_y: Pixels,
8325    pub line_height: Pixels,
8326    pub lines: Vec<HighlightedRangeLine>,
8327    pub color: Hsla,
8328    pub corner_radius: Pixels,
8329}
8330
8331#[derive(Debug)]
8332pub struct HighlightedRangeLine {
8333    pub start_x: Pixels,
8334    pub end_x: Pixels,
8335}
8336
8337impl HighlightedRange {
8338    pub fn paint(&self, bounds: Bounds<Pixels>, window: &mut Window) {
8339        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
8340            self.paint_lines(self.start_y, &self.lines[0..1], bounds, window);
8341            self.paint_lines(
8342                self.start_y + self.line_height,
8343                &self.lines[1..],
8344                bounds,
8345                window,
8346            );
8347        } else {
8348            self.paint_lines(self.start_y, &self.lines, bounds, window);
8349        }
8350    }
8351
8352    fn paint_lines(
8353        &self,
8354        start_y: Pixels,
8355        lines: &[HighlightedRangeLine],
8356        _bounds: Bounds<Pixels>,
8357        window: &mut Window,
8358    ) {
8359        if lines.is_empty() {
8360            return;
8361        }
8362
8363        let first_line = lines.first().unwrap();
8364        let last_line = lines.last().unwrap();
8365
8366        let first_top_left = point(first_line.start_x, start_y);
8367        let first_top_right = point(first_line.end_x, start_y);
8368
8369        let curve_height = point(Pixels::ZERO, self.corner_radius);
8370        let curve_width = |start_x: Pixels, end_x: Pixels| {
8371            let max = (end_x - start_x) / 2.;
8372            let width = if max < self.corner_radius {
8373                max
8374            } else {
8375                self.corner_radius
8376            };
8377
8378            point(width, Pixels::ZERO)
8379        };
8380
8381        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
8382        let mut builder = gpui::PathBuilder::fill();
8383        builder.move_to(first_top_right - top_curve_width);
8384        builder.curve_to(first_top_right + curve_height, first_top_right);
8385
8386        let mut iter = lines.iter().enumerate().peekable();
8387        while let Some((ix, line)) = iter.next() {
8388            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
8389
8390            if let Some((_, next_line)) = iter.peek() {
8391                let next_top_right = point(next_line.end_x, bottom_right.y);
8392
8393                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
8394                    Ordering::Equal => {
8395                        builder.line_to(bottom_right);
8396                    }
8397                    Ordering::Less => {
8398                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
8399                        builder.line_to(bottom_right - curve_height);
8400                        if self.corner_radius > Pixels::ZERO {
8401                            builder.curve_to(bottom_right - curve_width, bottom_right);
8402                        }
8403                        builder.line_to(next_top_right + curve_width);
8404                        if self.corner_radius > Pixels::ZERO {
8405                            builder.curve_to(next_top_right + curve_height, next_top_right);
8406                        }
8407                    }
8408                    Ordering::Greater => {
8409                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
8410                        builder.line_to(bottom_right - curve_height);
8411                        if self.corner_radius > Pixels::ZERO {
8412                            builder.curve_to(bottom_right + curve_width, bottom_right);
8413                        }
8414                        builder.line_to(next_top_right - curve_width);
8415                        if self.corner_radius > Pixels::ZERO {
8416                            builder.curve_to(next_top_right + curve_height, next_top_right);
8417                        }
8418                    }
8419                }
8420            } else {
8421                let curve_width = curve_width(line.start_x, line.end_x);
8422                builder.line_to(bottom_right - curve_height);
8423                if self.corner_radius > Pixels::ZERO {
8424                    builder.curve_to(bottom_right - curve_width, bottom_right);
8425                }
8426
8427                let bottom_left = point(line.start_x, bottom_right.y);
8428                builder.line_to(bottom_left + curve_width);
8429                if self.corner_radius > Pixels::ZERO {
8430                    builder.curve_to(bottom_left - curve_height, bottom_left);
8431                }
8432            }
8433        }
8434
8435        if first_line.start_x > last_line.start_x {
8436            let curve_width = curve_width(last_line.start_x, first_line.start_x);
8437            let second_top_left = point(last_line.start_x, start_y + self.line_height);
8438            builder.line_to(second_top_left + curve_height);
8439            if self.corner_radius > Pixels::ZERO {
8440                builder.curve_to(second_top_left + curve_width, second_top_left);
8441            }
8442            let first_bottom_left = point(first_line.start_x, second_top_left.y);
8443            builder.line_to(first_bottom_left - curve_width);
8444            if self.corner_radius > Pixels::ZERO {
8445                builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
8446            }
8447        }
8448
8449        builder.line_to(first_top_left + curve_height);
8450        if self.corner_radius > Pixels::ZERO {
8451            builder.curve_to(first_top_left + top_curve_width, first_top_left);
8452        }
8453        builder.line_to(first_top_right - top_curve_width);
8454
8455        if let Ok(path) = builder.build() {
8456            window.paint_path(path, self.color);
8457        }
8458    }
8459}
8460
8461enum CursorPopoverType {
8462    CodeContextMenu,
8463    EditPrediction,
8464}
8465
8466pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
8467    (delta.pow(1.5) / 100.0).into()
8468}
8469
8470fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
8471    (delta.pow(1.2) / 300.0).into()
8472}
8473
8474pub fn register_action<T: Action>(
8475    editor: &Entity<Editor>,
8476    window: &mut Window,
8477    listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
8478) {
8479    let editor = editor.clone();
8480    window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
8481        let action = action.downcast_ref().unwrap();
8482        if phase == DispatchPhase::Bubble {
8483            editor.update(cx, |editor, cx| {
8484                listener(editor, action, window, cx);
8485            })
8486        }
8487    })
8488}
8489
8490fn compute_auto_height_layout(
8491    editor: &mut Editor,
8492    max_lines: usize,
8493    max_line_number_width: Pixels,
8494    known_dimensions: Size<Option<Pixels>>,
8495    available_width: AvailableSpace,
8496    window: &mut Window,
8497    cx: &mut Context<Editor>,
8498) -> Option<Size<Pixels>> {
8499    let width = known_dimensions.width.or({
8500        if let AvailableSpace::Definite(available_width) = available_width {
8501            Some(available_width)
8502        } else {
8503            None
8504        }
8505    })?;
8506    if let Some(height) = known_dimensions.height {
8507        return Some(size(width, height));
8508    }
8509
8510    let style = editor.style.as_ref().unwrap();
8511    let font_id = window.text_system().resolve_font(&style.text.font());
8512    let font_size = style.text.font_size.to_pixels(window.rem_size());
8513    let line_height = style.text.line_height_in_pixels(window.rem_size());
8514    let em_width = window.text_system().em_width(font_id, font_size).unwrap();
8515
8516    let mut snapshot = editor.snapshot(window, cx);
8517    let gutter_dimensions = snapshot
8518        .gutter_dimensions(font_id, font_size, max_line_number_width, cx)
8519        .unwrap_or_default();
8520
8521    editor.gutter_dimensions = gutter_dimensions;
8522    let text_width = width - gutter_dimensions.width;
8523    let overscroll = size(em_width, px(0.));
8524
8525    let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
8526    if editor.set_wrap_width(Some(editor_width), cx) {
8527        snapshot = editor.snapshot(window, cx);
8528    }
8529
8530    let scroll_height = Pixels::from(snapshot.max_point().row().next_row().0) * line_height;
8531    let height = scroll_height
8532        .max(line_height)
8533        .min(line_height * max_lines as f32);
8534
8535    Some(size(width, height))
8536}
8537
8538#[cfg(test)]
8539mod tests {
8540    use super::*;
8541    use crate::{
8542        display_map::{BlockPlacement, BlockProperties},
8543        editor_tests::{init_test, update_test_language_settings},
8544        Editor, MultiBuffer,
8545    };
8546    use gpui::{TestAppContext, VisualTestContext};
8547    use language::language_settings;
8548    use log::info;
8549    use std::num::NonZeroU32;
8550    use util::test::sample_text;
8551
8552    #[gpui::test]
8553    fn test_shape_line_numbers(cx: &mut TestAppContext) {
8554        init_test(cx, |_| {});
8555        let window = cx.add_window(|window, cx| {
8556            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
8557            Editor::new(EditorMode::Full, buffer, None, window, cx)
8558        });
8559
8560        let editor = window.root(cx).unwrap();
8561        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
8562        let line_height = window
8563            .update(cx, |_, window, _| {
8564                style.text.line_height_in_pixels(window.rem_size())
8565            })
8566            .unwrap();
8567        let element = EditorElement::new(&editor, style);
8568        let snapshot = window
8569            .update(cx, |editor, window, cx| editor.snapshot(window, cx))
8570            .unwrap();
8571
8572        let layouts = cx
8573            .update_window(*window, |_, window, cx| {
8574                element.layout_line_numbers(
8575                    None,
8576                    GutterDimensions {
8577                        left_padding: Pixels::ZERO,
8578                        right_padding: Pixels::ZERO,
8579                        width: px(30.0),
8580                        margin: Pixels::ZERO,
8581                        git_blame_entries_width: None,
8582                    },
8583                    line_height,
8584                    gpui::Point::default(),
8585                    DisplayRow(0)..DisplayRow(6),
8586                    &(0..6)
8587                        .map(|row| RowInfo {
8588                            buffer_row: Some(row),
8589                            ..Default::default()
8590                        })
8591                        .collect::<Vec<_>>(),
8592                    &BTreeMap::default(),
8593                    Some(DisplayPoint::new(DisplayRow(0), 0)),
8594                    &snapshot,
8595                    window,
8596                    cx,
8597                )
8598            })
8599            .unwrap();
8600        assert_eq!(layouts.len(), 6);
8601
8602        let relative_rows = window
8603            .update(cx, |editor, window, cx| {
8604                let snapshot = editor.snapshot(window, cx);
8605                element.calculate_relative_line_numbers(
8606                    &snapshot,
8607                    &(DisplayRow(0)..DisplayRow(6)),
8608                    Some(DisplayRow(3)),
8609                )
8610            })
8611            .unwrap();
8612        assert_eq!(relative_rows[&DisplayRow(0)], 3);
8613        assert_eq!(relative_rows[&DisplayRow(1)], 2);
8614        assert_eq!(relative_rows[&DisplayRow(2)], 1);
8615        // current line has no relative number
8616        assert_eq!(relative_rows[&DisplayRow(4)], 1);
8617        assert_eq!(relative_rows[&DisplayRow(5)], 2);
8618
8619        // works if cursor is before screen
8620        let relative_rows = window
8621            .update(cx, |editor, window, cx| {
8622                let snapshot = editor.snapshot(window, cx);
8623                element.calculate_relative_line_numbers(
8624                    &snapshot,
8625                    &(DisplayRow(3)..DisplayRow(6)),
8626                    Some(DisplayRow(1)),
8627                )
8628            })
8629            .unwrap();
8630        assert_eq!(relative_rows.len(), 3);
8631        assert_eq!(relative_rows[&DisplayRow(3)], 2);
8632        assert_eq!(relative_rows[&DisplayRow(4)], 3);
8633        assert_eq!(relative_rows[&DisplayRow(5)], 4);
8634
8635        // works if cursor is after screen
8636        let relative_rows = window
8637            .update(cx, |editor, window, cx| {
8638                let snapshot = editor.snapshot(window, cx);
8639                element.calculate_relative_line_numbers(
8640                    &snapshot,
8641                    &(DisplayRow(0)..DisplayRow(3)),
8642                    Some(DisplayRow(6)),
8643                )
8644            })
8645            .unwrap();
8646        assert_eq!(relative_rows.len(), 3);
8647        assert_eq!(relative_rows[&DisplayRow(0)], 5);
8648        assert_eq!(relative_rows[&DisplayRow(1)], 4);
8649        assert_eq!(relative_rows[&DisplayRow(2)], 3);
8650    }
8651
8652    #[gpui::test]
8653    async fn test_vim_visual_selections(cx: &mut TestAppContext) {
8654        init_test(cx, |_| {});
8655
8656        let window = cx.add_window(|window, cx| {
8657            let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
8658            Editor::new(EditorMode::Full, buffer, None, window, cx)
8659        });
8660        let cx = &mut VisualTestContext::from_window(*window, cx);
8661        let editor = window.root(cx).unwrap();
8662        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8663
8664        window
8665            .update(cx, |editor, window, cx| {
8666                editor.cursor_shape = CursorShape::Block;
8667                editor.change_selections(None, window, cx, |s| {
8668                    s.select_ranges([
8669                        Point::new(0, 0)..Point::new(1, 0),
8670                        Point::new(3, 2)..Point::new(3, 3),
8671                        Point::new(5, 6)..Point::new(6, 0),
8672                    ]);
8673                });
8674            })
8675            .unwrap();
8676
8677        let (_, state) = cx.draw(
8678            point(px(500.), px(500.)),
8679            size(px(500.), px(500.)),
8680            |_, _| EditorElement::new(&editor, style),
8681        );
8682
8683        assert_eq!(state.selections.len(), 1);
8684        let local_selections = &state.selections[0].1;
8685        assert_eq!(local_selections.len(), 3);
8686        // moves cursor back one line
8687        assert_eq!(
8688            local_selections[0].head,
8689            DisplayPoint::new(DisplayRow(0), 6)
8690        );
8691        assert_eq!(
8692            local_selections[0].range,
8693            DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
8694        );
8695
8696        // moves cursor back one column
8697        assert_eq!(
8698            local_selections[1].range,
8699            DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
8700        );
8701        assert_eq!(
8702            local_selections[1].head,
8703            DisplayPoint::new(DisplayRow(3), 2)
8704        );
8705
8706        // leaves cursor on the max point
8707        assert_eq!(
8708            local_selections[2].range,
8709            DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
8710        );
8711        assert_eq!(
8712            local_selections[2].head,
8713            DisplayPoint::new(DisplayRow(6), 0)
8714        );
8715
8716        // active lines does not include 1 (even though the range of the selection does)
8717        assert_eq!(
8718            state.active_rows.keys().cloned().collect::<Vec<_>>(),
8719            vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
8720        );
8721    }
8722
8723    #[gpui::test]
8724    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
8725        init_test(cx, |_| {});
8726
8727        let window = cx.add_window(|window, cx| {
8728            let buffer = MultiBuffer::build_simple("", cx);
8729            Editor::new(EditorMode::Full, buffer, None, window, cx)
8730        });
8731        let cx = &mut VisualTestContext::from_window(*window, cx);
8732        let editor = window.root(cx).unwrap();
8733        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8734        window
8735            .update(cx, |editor, window, cx| {
8736                editor.set_placeholder_text("hello", cx);
8737                editor.insert_blocks(
8738                    [BlockProperties {
8739                        style: BlockStyle::Fixed,
8740                        placement: BlockPlacement::Above(Anchor::min()),
8741                        height: 3,
8742                        render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
8743                        priority: 0,
8744                    }],
8745                    None,
8746                    cx,
8747                );
8748
8749                // Blur the editor so that it displays placeholder text.
8750                window.blur();
8751            })
8752            .unwrap();
8753
8754        let (_, state) = cx.draw(
8755            point(px(500.), px(500.)),
8756            size(px(500.), px(500.)),
8757            |_, _| EditorElement::new(&editor, style),
8758        );
8759        assert_eq!(state.position_map.line_layouts.len(), 4);
8760        assert_eq!(state.line_numbers.len(), 1);
8761        assert_eq!(
8762            state
8763                .line_numbers
8764                .get(&MultiBufferRow(0))
8765                .map(|line_number| line_number.shaped_line.text.as_ref()),
8766            Some("1")
8767        );
8768    }
8769
8770    #[gpui::test]
8771    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
8772        const TAB_SIZE: u32 = 4;
8773
8774        let input_text = "\t \t|\t| a b";
8775        let expected_invisibles = vec![
8776            Invisible::Tab {
8777                line_start_offset: 0,
8778                line_end_offset: TAB_SIZE as usize,
8779            },
8780            Invisible::Whitespace {
8781                line_offset: TAB_SIZE as usize,
8782            },
8783            Invisible::Tab {
8784                line_start_offset: TAB_SIZE as usize + 1,
8785                line_end_offset: TAB_SIZE as usize * 2,
8786            },
8787            Invisible::Tab {
8788                line_start_offset: TAB_SIZE as usize * 2 + 1,
8789                line_end_offset: TAB_SIZE as usize * 3,
8790            },
8791            Invisible::Whitespace {
8792                line_offset: TAB_SIZE as usize * 3 + 1,
8793            },
8794            Invisible::Whitespace {
8795                line_offset: TAB_SIZE as usize * 3 + 3,
8796            },
8797        ];
8798        assert_eq!(
8799            expected_invisibles.len(),
8800            input_text
8801                .chars()
8802                .filter(|initial_char| initial_char.is_whitespace())
8803                .count(),
8804            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
8805        );
8806
8807        for show_line_numbers in [true, false] {
8808            init_test(cx, |s| {
8809                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8810                s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
8811            });
8812
8813            let actual_invisibles = collect_invisibles_from_new_editor(
8814                cx,
8815                EditorMode::Full,
8816                input_text,
8817                px(500.0),
8818                show_line_numbers,
8819            );
8820
8821            assert_eq!(expected_invisibles, actual_invisibles);
8822        }
8823    }
8824
8825    #[gpui::test]
8826    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
8827        init_test(cx, |s| {
8828            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8829            s.defaults.tab_size = NonZeroU32::new(4);
8830        });
8831
8832        for editor_mode_without_invisibles in [
8833            EditorMode::SingleLine { auto_width: false },
8834            EditorMode::AutoHeight { max_lines: 100 },
8835        ] {
8836            for show_line_numbers in [true, false] {
8837                let invisibles = collect_invisibles_from_new_editor(
8838                    cx,
8839                    editor_mode_without_invisibles,
8840                    "\t\t\t| | a b",
8841                    px(500.0),
8842                    show_line_numbers,
8843                );
8844                assert!(invisibles.is_empty(),
8845                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
8846            }
8847        }
8848    }
8849
8850    #[gpui::test]
8851    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
8852        let tab_size = 4;
8853        let input_text = "a\tbcd     ".repeat(9);
8854        let repeated_invisibles = [
8855            Invisible::Tab {
8856                line_start_offset: 1,
8857                line_end_offset: tab_size as usize,
8858            },
8859            Invisible::Whitespace {
8860                line_offset: tab_size as usize + 3,
8861            },
8862            Invisible::Whitespace {
8863                line_offset: tab_size as usize + 4,
8864            },
8865            Invisible::Whitespace {
8866                line_offset: tab_size as usize + 5,
8867            },
8868            Invisible::Whitespace {
8869                line_offset: tab_size as usize + 6,
8870            },
8871            Invisible::Whitespace {
8872                line_offset: tab_size as usize + 7,
8873            },
8874        ];
8875        let expected_invisibles = std::iter::once(repeated_invisibles)
8876            .cycle()
8877            .take(9)
8878            .flatten()
8879            .collect::<Vec<_>>();
8880        assert_eq!(
8881            expected_invisibles.len(),
8882            input_text
8883                .chars()
8884                .filter(|initial_char| initial_char.is_whitespace())
8885                .count(),
8886            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
8887        );
8888        info!("Expected invisibles: {expected_invisibles:?}");
8889
8890        init_test(cx, |_| {});
8891
8892        // Put the same string with repeating whitespace pattern into editors of various size,
8893        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
8894        let resize_step = 10.0;
8895        let mut editor_width = 200.0;
8896        while editor_width <= 1000.0 {
8897            for show_line_numbers in [true, false] {
8898                update_test_language_settings(cx, |s| {
8899                    s.defaults.tab_size = NonZeroU32::new(tab_size);
8900                    s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8901                    s.defaults.preferred_line_length = Some(editor_width as u32);
8902                    s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
8903                });
8904
8905                let actual_invisibles = collect_invisibles_from_new_editor(
8906                    cx,
8907                    EditorMode::Full,
8908                    &input_text,
8909                    px(editor_width),
8910                    show_line_numbers,
8911                );
8912
8913                // Whatever the editor size is, ensure it has the same invisible kinds in the same order
8914                // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
8915                let mut i = 0;
8916                for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
8917                    i = actual_index;
8918                    match expected_invisibles.get(i) {
8919                        Some(expected_invisible) => match (expected_invisible, actual_invisible) {
8920                            (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
8921                            | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
8922                            _ => {
8923                                panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
8924                            }
8925                        },
8926                        None => {
8927                            panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
8928                        }
8929                    }
8930                }
8931                let missing_expected_invisibles = &expected_invisibles[i + 1..];
8932                assert!(
8933                    missing_expected_invisibles.is_empty(),
8934                    "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
8935                );
8936
8937                editor_width += resize_step;
8938            }
8939        }
8940    }
8941
8942    fn collect_invisibles_from_new_editor(
8943        cx: &mut TestAppContext,
8944        editor_mode: EditorMode,
8945        input_text: &str,
8946        editor_width: Pixels,
8947        show_line_numbers: bool,
8948    ) -> Vec<Invisible> {
8949        info!(
8950            "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
8951            editor_width.0
8952        );
8953        let window = cx.add_window(|window, cx| {
8954            let buffer = MultiBuffer::build_simple(input_text, cx);
8955            Editor::new(editor_mode, buffer, None, window, cx)
8956        });
8957        let cx = &mut VisualTestContext::from_window(*window, cx);
8958        let editor = window.root(cx).unwrap();
8959
8960        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8961        window
8962            .update(cx, |editor, _, cx| {
8963                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
8964                editor.set_wrap_width(Some(editor_width), cx);
8965                editor.set_show_line_numbers(show_line_numbers, cx);
8966            })
8967            .unwrap();
8968        let (_, state) = cx.draw(
8969            point(px(500.), px(500.)),
8970            size(px(500.), px(500.)),
8971            |_, _| EditorElement::new(&editor, style),
8972        );
8973        state
8974            .position_map
8975            .line_layouts
8976            .iter()
8977            .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
8978            .cloned()
8979            .collect()
8980    }
8981}
8982
8983fn diff_hunk_controls(
8984    row: u32,
8985    status: &DiffHunkStatus,
8986    hunk_range: Range<Anchor>,
8987    is_created_file: bool,
8988    line_height: Pixels,
8989    editor: &Entity<Editor>,
8990    cx: &mut App,
8991) -> AnyElement {
8992    h_flex()
8993        .h(line_height)
8994        .mr_1()
8995        .gap_1()
8996        .px_0p5()
8997        .pb_1()
8998        .border_x_1()
8999        .border_b_1()
9000        .border_color(cx.theme().colors().border_variant)
9001        .rounded_b_lg()
9002        .bg(cx.theme().colors().editor_background)
9003        .gap_1()
9004        .occlude()
9005        .shadow_md()
9006        .child(if status.has_secondary_hunk() {
9007            Button::new(("stage", row as u64), "Stage")
9008                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
9009                .tooltip({
9010                    let focus_handle = editor.focus_handle(cx);
9011                    move |window, cx| {
9012                        Tooltip::for_action_in(
9013                            "Stage Hunk",
9014                            &::git::ToggleStaged,
9015                            &focus_handle,
9016                            window,
9017                            cx,
9018                        )
9019                    }
9020                })
9021                .on_click({
9022                    let editor = editor.clone();
9023                    move |_event, _window, cx| {
9024                        editor.update(cx, |editor, cx| {
9025                            editor.stage_or_unstage_diff_hunks(
9026                                true,
9027                                vec![hunk_range.start..hunk_range.start],
9028                                cx,
9029                            );
9030                        });
9031                    }
9032                })
9033        } else {
9034            Button::new(("unstage", row as u64), "Unstage")
9035                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
9036                .tooltip({
9037                    let focus_handle = editor.focus_handle(cx);
9038                    move |window, cx| {
9039                        Tooltip::for_action_in(
9040                            "Unstage Hunk",
9041                            &::git::ToggleStaged,
9042                            &focus_handle,
9043                            window,
9044                            cx,
9045                        )
9046                    }
9047                })
9048                .on_click({
9049                    let editor = editor.clone();
9050                    move |_event, _window, cx| {
9051                        editor.update(cx, |editor, cx| {
9052                            editor.stage_or_unstage_diff_hunks(
9053                                false,
9054                                vec![hunk_range.start..hunk_range.start],
9055                                cx,
9056                            );
9057                        });
9058                    }
9059                })
9060        })
9061        .child(
9062            Button::new("restore", "Restore")
9063                .tooltip({
9064                    let focus_handle = editor.focus_handle(cx);
9065                    move |window, cx| {
9066                        Tooltip::for_action_in(
9067                            "Restore Hunk",
9068                            &::git::Restore,
9069                            &focus_handle,
9070                            window,
9071                            cx,
9072                        )
9073                    }
9074                })
9075                .on_click({
9076                    let editor = editor.clone();
9077                    move |_event, window, cx| {
9078                        editor.update(cx, |editor, cx| {
9079                            let snapshot = editor.snapshot(window, cx);
9080                            let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
9081                            editor.restore_hunks_in_ranges(vec![point..point], window, cx);
9082                        });
9083                    }
9084                })
9085                .disabled(is_created_file),
9086        )
9087        .when(
9088            !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
9089            |el| {
9090                el.child(
9091                    IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
9092                        .shape(IconButtonShape::Square)
9093                        .icon_size(IconSize::Small)
9094                        // .disabled(!has_multiple_hunks)
9095                        .tooltip({
9096                            let focus_handle = editor.focus_handle(cx);
9097                            move |window, cx| {
9098                                Tooltip::for_action_in(
9099                                    "Next Hunk",
9100                                    &GoToHunk,
9101                                    &focus_handle,
9102                                    window,
9103                                    cx,
9104                                )
9105                            }
9106                        })
9107                        .on_click({
9108                            let editor = editor.clone();
9109                            move |_event, window, cx| {
9110                                editor.update(cx, |editor, cx| {
9111                                    let snapshot = editor.snapshot(window, cx);
9112                                    let position =
9113                                        hunk_range.end.to_point(&snapshot.buffer_snapshot);
9114                                    editor.go_to_hunk_before_or_after_position(
9115                                        &snapshot,
9116                                        position,
9117                                        Direction::Next,
9118                                        window,
9119                                        cx,
9120                                    );
9121                                    editor.expand_selected_diff_hunks(cx);
9122                                });
9123                            }
9124                        }),
9125                )
9126                .child(
9127                    IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
9128                        .shape(IconButtonShape::Square)
9129                        .icon_size(IconSize::Small)
9130                        // .disabled(!has_multiple_hunks)
9131                        .tooltip({
9132                            let focus_handle = editor.focus_handle(cx);
9133                            move |window, cx| {
9134                                Tooltip::for_action_in(
9135                                    "Previous Hunk",
9136                                    &GoToPreviousHunk,
9137                                    &focus_handle,
9138                                    window,
9139                                    cx,
9140                                )
9141                            }
9142                        })
9143                        .on_click({
9144                            let editor = editor.clone();
9145                            move |_event, window, cx| {
9146                                editor.update(cx, |editor, cx| {
9147                                    let snapshot = editor.snapshot(window, cx);
9148                                    let point =
9149                                        hunk_range.start.to_point(&snapshot.buffer_snapshot);
9150                                    editor.go_to_hunk_before_or_after_position(
9151                                        &snapshot,
9152                                        point,
9153                                        Direction::Prev,
9154                                        window,
9155                                        cx,
9156                                    );
9157                                    editor.expand_selected_diff_hunks(cx);
9158                                });
9159                            }
9160                        }),
9161                )
9162            },
9163        )
9164        .into_any_element()
9165}