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, CursorShape, CustomBlockId, DisplayDiffHunk, DisplayPoint,
  20    DisplayRow, DocumentHighlightRead, DocumentHighlightWrite, EditDisplayMode, Editor, EditorMode,
  21    EditorSettings, EditorSnapshot, EditorStyle, FocusedBlock, GoToHunk, GoToPreviousHunk,
  22    GutterDimensions, HalfPageDown, HalfPageUp, HandleInput, HoveredCursor, InlayHintRefreshReason,
  23    InlineCompletion, JumpData, LineDown, LineHighlight, LineUp, OpenExcerpts, PageDown, PageUp,
  24    Point, RowExt, RowRangeExt, SelectPhase, SelectedTextHighlight, Selection, SoftWrap,
  25    StickyHeaderExcerpt, ToPoint, ToggleFold, COLUMNAR_SELECTION_MODIFIERS, CURSORS_VISIBLE_FOR,
  26    FILE_HEADER_HEIGHT, GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED, MAX_LINE_LEN, MIN_LINE_NUMBER_DIGITS,
  27    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
3342        {
3343            let editor = self.editor.read(cx);
3344            if editor
3345                .edit_prediction_visible_in_cursor_popover(editor.has_active_inline_completion())
3346            {
3347                height_above_menu +=
3348                    editor.edit_prediction_cursor_popover_height() + POPOVER_Y_PADDING;
3349                edit_prediction_popover_visible = true;
3350            }
3351
3352            if editor.context_menu_visible() {
3353                if let Some(crate::ContextMenuOrigin::Cursor) = editor.context_menu_origin() {
3354                    min_menu_height += line_height * 3. + POPOVER_Y_PADDING;
3355                    max_menu_height += line_height * 12. + POPOVER_Y_PADDING;
3356                    context_menu_visible = true;
3357                }
3358            }
3359        }
3360
3361        let visible = edit_prediction_popover_visible || context_menu_visible;
3362        if !visible {
3363            return;
3364        }
3365
3366        let cursor_row_layout = &line_layouts[cursor.row().minus(start_row) as usize];
3367        let target_position = content_origin
3368            + gpui::Point {
3369                x: cmp::max(
3370                    px(0.),
3371                    cursor_row_layout.x_for_index(cursor.column() as usize)
3372                        - scroll_pixel_position.x,
3373                ),
3374                y: cmp::max(
3375                    px(0.),
3376                    cursor.row().next_row().as_f32() * line_height - scroll_pixel_position.y,
3377                ),
3378            };
3379
3380        let viewport_bounds =
3381            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
3382                right: -Self::SCROLLBAR_WIDTH - MENU_GAP,
3383                ..Default::default()
3384            });
3385
3386        let min_height = height_above_menu + min_menu_height + height_below_menu;
3387        let max_height = height_above_menu + max_menu_height + height_below_menu;
3388        let Some((laid_out_popovers, y_flipped)) = self.layout_popovers_above_or_below_line(
3389            target_position,
3390            line_height,
3391            min_height,
3392            max_height,
3393            text_hitbox,
3394            viewport_bounds,
3395            window,
3396            cx,
3397            |height, max_width_for_stable_x, y_flipped, window, cx| {
3398                // First layout the menu to get its size - others can be at least this wide.
3399                let context_menu = if context_menu_visible {
3400                    let menu_height = if y_flipped {
3401                        height - height_below_menu
3402                    } else {
3403                        height - height_above_menu
3404                    };
3405                    let mut element = self
3406                        .render_context_menu(line_height, menu_height, y_flipped, window, cx)
3407                        .expect("Visible context menu should always render.");
3408                    let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3409                    Some((CursorPopoverType::CodeContextMenu, element, size))
3410                } else {
3411                    None
3412                };
3413                let min_width = context_menu
3414                    .as_ref()
3415                    .map_or(px(0.), |(_, _, size)| size.width);
3416                let max_width = max_width_for_stable_x.max(
3417                    context_menu
3418                        .as_ref()
3419                        .map_or(px(0.), |(_, _, size)| size.width),
3420                );
3421
3422                let edit_prediction = if edit_prediction_popover_visible {
3423                    self.editor.update(cx, move |editor, cx| {
3424                        let accept_binding = editor.accept_edit_prediction_keybind(window, cx);
3425                        let mut element = editor.render_edit_prediction_cursor_popover(
3426                            min_width,
3427                            max_width,
3428                            cursor_point,
3429                            style,
3430                            accept_binding.keystroke(),
3431                            window,
3432                            cx,
3433                        )?;
3434                        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3435                        Some((CursorPopoverType::EditPrediction, element, size))
3436                    })
3437                } else {
3438                    None
3439                };
3440                vec![edit_prediction, context_menu]
3441                    .into_iter()
3442                    .flatten()
3443                    .collect::<Vec<_>>()
3444            },
3445        ) else {
3446            return;
3447        };
3448
3449        let Some((menu_ix, (_, menu_bounds))) = laid_out_popovers
3450            .iter()
3451            .find_position(|(x, _)| matches!(x, CursorPopoverType::CodeContextMenu))
3452        else {
3453            return;
3454        };
3455        let last_ix = laid_out_popovers.len() - 1;
3456        let menu_is_last = menu_ix == last_ix;
3457        let first_popover_bounds = laid_out_popovers[0].1;
3458        let last_popover_bounds = laid_out_popovers[last_ix].1;
3459
3460        // Bounds to layout the aside around. When y_flipped, the aside goes either above or to the
3461        // right, and otherwise it goes below or to the right.
3462        let mut target_bounds = Bounds::from_corners(
3463            first_popover_bounds.origin,
3464            last_popover_bounds.bottom_right(),
3465        );
3466        target_bounds.size.width = menu_bounds.size.width;
3467
3468        // Like `target_bounds`, but with the max height it could occupy. Choosing an aside position
3469        // based on this is preferred for layout stability.
3470        let mut max_target_bounds = target_bounds;
3471        max_target_bounds.size.height = max_height;
3472        if y_flipped {
3473            max_target_bounds.origin.y -= max_height - target_bounds.size.height;
3474        }
3475
3476        // Add spacing around `target_bounds` and `max_target_bounds`.
3477        let mut extend_amount = Edges::all(MENU_GAP);
3478        if y_flipped {
3479            extend_amount.bottom = line_height;
3480        } else {
3481            extend_amount.top = line_height;
3482        }
3483        let target_bounds = target_bounds.extend(extend_amount);
3484        let max_target_bounds = max_target_bounds.extend(extend_amount);
3485
3486        let must_place_above_or_below =
3487            if y_flipped && !menu_is_last && menu_bounds.size.height < max_menu_height {
3488                laid_out_popovers[menu_ix + 1..]
3489                    .iter()
3490                    .any(|(_, popover_bounds)| popover_bounds.size.width > menu_bounds.size.width)
3491            } else {
3492                false
3493            };
3494
3495        self.layout_context_menu_aside(
3496            y_flipped,
3497            *menu_bounds,
3498            target_bounds,
3499            max_target_bounds,
3500            max_menu_height,
3501            must_place_above_or_below,
3502            text_hitbox,
3503            viewport_bounds,
3504            window,
3505            cx,
3506        );
3507    }
3508
3509    fn layout_gutter_menu(
3510        &self,
3511        line_height: Pixels,
3512        text_hitbox: &Hitbox,
3513        content_origin: gpui::Point<Pixels>,
3514        scroll_pixel_position: gpui::Point<Pixels>,
3515        gutter_overshoot: Pixels,
3516        window: &mut Window,
3517        cx: &mut App,
3518    ) {
3519        let editor = self.editor.read(cx);
3520        if !editor.context_menu_visible() {
3521            return;
3522        }
3523        let Some(crate::ContextMenuOrigin::GutterIndicator(gutter_row)) =
3524            editor.context_menu_origin()
3525        else {
3526            return;
3527        };
3528        // Context menu was spawned via a click on a gutter. Ensure it's a bit closer to the
3529        // indicator than just a plain first column of the text field.
3530        let target_position = content_origin
3531            + gpui::Point {
3532                x: -gutter_overshoot,
3533                y: gutter_row.next_row().as_f32() * line_height - scroll_pixel_position.y,
3534            };
3535        let min_height = line_height * 3. + POPOVER_Y_PADDING;
3536        let max_height = line_height * 12. + POPOVER_Y_PADDING;
3537        let viewport_bounds =
3538            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
3539                right: -Self::SCROLLBAR_WIDTH - MENU_GAP,
3540                ..Default::default()
3541            });
3542        self.layout_popovers_above_or_below_line(
3543            target_position,
3544            line_height,
3545            min_height,
3546            max_height,
3547            text_hitbox,
3548            viewport_bounds,
3549            window,
3550            cx,
3551            move |height, _max_width_for_stable_x, y_flipped, window, cx| {
3552                let mut element = self
3553                    .render_context_menu(line_height, height, y_flipped, window, cx)
3554                    .expect("Visible context menu should always render.");
3555                let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3556                vec![(CursorPopoverType::CodeContextMenu, element, size)]
3557            },
3558        );
3559    }
3560
3561    fn layout_popovers_above_or_below_line(
3562        &self,
3563        target_position: gpui::Point<Pixels>,
3564        line_height: Pixels,
3565        min_height: Pixels,
3566        max_height: Pixels,
3567        text_hitbox: &Hitbox,
3568        viewport_bounds: Bounds<Pixels>,
3569        window: &mut Window,
3570        cx: &mut App,
3571        make_sized_popovers: impl FnOnce(
3572            Pixels,
3573            Pixels,
3574            bool,
3575            &mut Window,
3576            &mut App,
3577        ) -> Vec<(CursorPopoverType, AnyElement, Size<Pixels>)>,
3578    ) -> Option<(Vec<(CursorPopoverType, Bounds<Pixels>)>, bool)> {
3579        let text_style = TextStyleRefinement {
3580            line_height: Some(DefiniteLength::Fraction(
3581                BufferLineHeight::Comfortable.value(),
3582            )),
3583            ..Default::default()
3584        };
3585        window.with_text_style(Some(text_style), |window| {
3586            // If the max height won't fit below and there is more space above, put it above the line.
3587            let bottom_y_when_flipped = target_position.y - line_height;
3588            let available_above = bottom_y_when_flipped - text_hitbox.top();
3589            let available_below = text_hitbox.bottom() - target_position.y;
3590            let y_overflows_below = max_height > available_below;
3591            let mut y_flipped = y_overflows_below && available_above > available_below;
3592            let mut height = cmp::min(
3593                max_height,
3594                if y_flipped {
3595                    available_above
3596                } else {
3597                    available_below
3598                },
3599            );
3600
3601            // If the min height doesn't fit within text bounds, instead fit within the window.
3602            if height < min_height {
3603                let available_above = bottom_y_when_flipped;
3604                let available_below = viewport_bounds.bottom() - target_position.y;
3605                if available_below > min_height {
3606                    y_flipped = false;
3607                    height = min_height;
3608                } else if available_above > min_height {
3609                    y_flipped = true;
3610                    height = min_height;
3611                } else if available_above > available_below {
3612                    y_flipped = true;
3613                    height = available_above;
3614                } else {
3615                    y_flipped = false;
3616                    height = available_below;
3617                }
3618            }
3619
3620            let max_width_for_stable_x = viewport_bounds.right() - target_position.x;
3621
3622            // TODO: Use viewport_bounds.width as a max width so that it doesn't get clipped on the left
3623            // for very narrow windows.
3624            let popovers =
3625                make_sized_popovers(height, max_width_for_stable_x, y_flipped, window, cx);
3626            if popovers.is_empty() {
3627                return None;
3628            }
3629
3630            let max_width = popovers
3631                .iter()
3632                .map(|(_, _, size)| size.width)
3633                .max()
3634                .unwrap_or_default();
3635
3636            let mut current_position = gpui::Point {
3637                // Snap the right edge of the list to the right edge of the window if its horizontal bounds
3638                // overflow. Include space for the scrollbar.
3639                x: target_position
3640                    .x
3641                    .min((viewport_bounds.right() - max_width).max(Pixels::ZERO)),
3642                y: if y_flipped {
3643                    bottom_y_when_flipped
3644                } else {
3645                    target_position.y
3646                },
3647            };
3648
3649            let mut laid_out_popovers = popovers
3650                .into_iter()
3651                .map(|(popover_type, element, size)| {
3652                    if y_flipped {
3653                        current_position.y -= size.height;
3654                    }
3655                    let position = current_position;
3656                    window.defer_draw(element, current_position, 1);
3657                    if !y_flipped {
3658                        current_position.y += size.height + MENU_GAP;
3659                    } else {
3660                        current_position.y -= MENU_GAP;
3661                    }
3662                    (popover_type, Bounds::new(position, size))
3663                })
3664                .collect::<Vec<_>>();
3665
3666            if y_flipped {
3667                laid_out_popovers.reverse();
3668            }
3669
3670            Some((laid_out_popovers, y_flipped))
3671        })
3672    }
3673
3674    fn layout_context_menu_aside(
3675        &self,
3676        y_flipped: bool,
3677        menu_bounds: Bounds<Pixels>,
3678        target_bounds: Bounds<Pixels>,
3679        max_target_bounds: Bounds<Pixels>,
3680        max_height: Pixels,
3681        must_place_above_or_below: bool,
3682        text_hitbox: &Hitbox,
3683        viewport_bounds: Bounds<Pixels>,
3684        window: &mut Window,
3685        cx: &mut App,
3686    ) {
3687        let available_within_viewport = target_bounds.space_within(&viewport_bounds);
3688        let positioned_aside = if available_within_viewport.right >= MENU_ASIDE_MIN_WIDTH
3689            && !must_place_above_or_below
3690        {
3691            let max_width = cmp::min(
3692                available_within_viewport.right - px(1.),
3693                MENU_ASIDE_MAX_WIDTH,
3694            );
3695            let Some(mut aside) = self.render_context_menu_aside(
3696                size(max_width, max_height - POPOVER_Y_PADDING),
3697                window,
3698                cx,
3699            ) else {
3700                return;
3701            };
3702            aside.layout_as_root(AvailableSpace::min_size(), window, cx);
3703            let right_position = point(target_bounds.right(), menu_bounds.origin.y);
3704            Some((aside, right_position))
3705        } else {
3706            let max_size = size(
3707                // TODO(mgsloan): Once the menu is bounded by viewport width the bound on viewport
3708                // won't be needed here.
3709                cmp::min(
3710                    cmp::max(menu_bounds.size.width - px(2.), MENU_ASIDE_MIN_WIDTH),
3711                    viewport_bounds.right(),
3712                ),
3713                cmp::min(
3714                    max_height,
3715                    cmp::max(
3716                        available_within_viewport.top,
3717                        available_within_viewport.bottom,
3718                    ),
3719                ) - POPOVER_Y_PADDING,
3720            );
3721            let Some(mut aside) = self.render_context_menu_aside(max_size, window, cx) else {
3722                return;
3723            };
3724            let actual_size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
3725
3726            let top_position = point(
3727                menu_bounds.origin.x,
3728                target_bounds.top() - actual_size.height,
3729            );
3730            let bottom_position = point(menu_bounds.origin.x, target_bounds.bottom());
3731
3732            let fit_within = |available: Edges<Pixels>, wanted: Size<Pixels>| {
3733                // Prefer to fit on the same side of the line as the menu, then on the other side of
3734                // the line.
3735                if !y_flipped && wanted.height < available.bottom {
3736                    Some(bottom_position)
3737                } else if !y_flipped && wanted.height < available.top {
3738                    Some(top_position)
3739                } else if y_flipped && wanted.height < available.top {
3740                    Some(top_position)
3741                } else if y_flipped && wanted.height < available.bottom {
3742                    Some(bottom_position)
3743                } else {
3744                    None
3745                }
3746            };
3747
3748            // Prefer choosing a direction using max sizes rather than actual size for stability.
3749            let available_within_text = max_target_bounds.space_within(&text_hitbox.bounds);
3750            let wanted = size(MENU_ASIDE_MAX_WIDTH, max_height);
3751            let aside_position = fit_within(available_within_text, wanted)
3752                // Fallback: fit max size in window.
3753                .or_else(|| fit_within(max_target_bounds.space_within(&viewport_bounds), wanted))
3754                // Fallback: fit actual size in window.
3755                .or_else(|| fit_within(available_within_viewport, actual_size));
3756
3757            aside_position.map(|position| (aside, position))
3758        };
3759
3760        // Skip drawing if it doesn't fit anywhere.
3761        if let Some((aside, position)) = positioned_aside {
3762            window.defer_draw(aside, position, 2);
3763        }
3764    }
3765
3766    fn render_context_menu(
3767        &self,
3768        line_height: Pixels,
3769        height: Pixels,
3770        y_flipped: bool,
3771        window: &mut Window,
3772        cx: &mut App,
3773    ) -> Option<AnyElement> {
3774        let max_height_in_lines = ((height - POPOVER_Y_PADDING) / line_height).floor() as u32;
3775        self.editor.update(cx, |editor, cx| {
3776            editor.render_context_menu(&self.style, max_height_in_lines, y_flipped, window, cx)
3777        })
3778    }
3779
3780    fn render_context_menu_aside(
3781        &self,
3782        max_size: Size<Pixels>,
3783        window: &mut Window,
3784        cx: &mut App,
3785    ) -> Option<AnyElement> {
3786        if max_size.width < px(100.) || max_size.height < px(12.) {
3787            None
3788        } else {
3789            self.editor.update(cx, |editor, cx| {
3790                editor.render_context_menu_aside(max_size, window, cx)
3791            })
3792        }
3793    }
3794
3795    fn layout_mouse_context_menu(
3796        &self,
3797        editor_snapshot: &EditorSnapshot,
3798        visible_range: Range<DisplayRow>,
3799        content_origin: gpui::Point<Pixels>,
3800        window: &mut Window,
3801        cx: &mut App,
3802    ) -> Option<AnyElement> {
3803        let position = self.editor.update(cx, |editor, _cx| {
3804            let visible_start_point = editor.display_to_pixel_point(
3805                DisplayPoint::new(visible_range.start, 0),
3806                editor_snapshot,
3807                window,
3808            )?;
3809            let visible_end_point = editor.display_to_pixel_point(
3810                DisplayPoint::new(visible_range.end, 0),
3811                editor_snapshot,
3812                window,
3813            )?;
3814
3815            let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
3816            let (source_display_point, position) = match mouse_context_menu.position {
3817                MenuPosition::PinnedToScreen(point) => (None, point),
3818                MenuPosition::PinnedToEditor { source, offset } => {
3819                    let source_display_point = source.to_display_point(editor_snapshot);
3820                    let source_point = editor.to_pixel_point(source, editor_snapshot, window)?;
3821                    let position = content_origin + source_point + offset;
3822                    (Some(source_display_point), position)
3823                }
3824            };
3825
3826            let source_included = source_display_point.map_or(true, |source_display_point| {
3827                visible_range
3828                    .to_inclusive()
3829                    .contains(&source_display_point.row())
3830            });
3831            let position_included =
3832                visible_start_point.y <= position.y && position.y <= visible_end_point.y;
3833            if !source_included && !position_included {
3834                None
3835            } else {
3836                Some(position)
3837            }
3838        })?;
3839
3840        let text_style = TextStyleRefinement {
3841            line_height: Some(DefiniteLength::Fraction(
3842                BufferLineHeight::Comfortable.value(),
3843            )),
3844            ..Default::default()
3845        };
3846        window.with_text_style(Some(text_style), |window| {
3847            let mut element = self.editor.update(cx, |editor, _| {
3848                let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
3849                let context_menu = mouse_context_menu.context_menu.clone();
3850
3851                Some(
3852                    deferred(
3853                        anchored()
3854                            .position(position)
3855                            .child(context_menu)
3856                            .anchor(Corner::TopLeft)
3857                            .snap_to_window_with_margin(px(8.)),
3858                    )
3859                    .with_priority(1)
3860                    .into_any(),
3861                )
3862            })?;
3863
3864            element.prepaint_as_root(position, AvailableSpace::min_size(), window, cx);
3865            Some(element)
3866        })
3867    }
3868
3869    fn layout_hover_popovers(
3870        &self,
3871        snapshot: &EditorSnapshot,
3872        hitbox: &Hitbox,
3873        text_hitbox: &Hitbox,
3874        visible_display_row_range: Range<DisplayRow>,
3875        content_origin: gpui::Point<Pixels>,
3876        scroll_pixel_position: gpui::Point<Pixels>,
3877        line_layouts: &[LineWithInvisibles],
3878        line_height: Pixels,
3879        em_width: Pixels,
3880        window: &mut Window,
3881        cx: &mut App,
3882    ) {
3883        struct MeasuredHoverPopover {
3884            element: AnyElement,
3885            size: Size<Pixels>,
3886            horizontal_offset: Pixels,
3887        }
3888
3889        let max_size = size(
3890            (120. * em_width) // Default size
3891                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
3892                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
3893            (16. * line_height) // Default size
3894                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
3895                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
3896        );
3897
3898        let hover_popovers = self.editor.update(cx, |editor, cx| {
3899            editor
3900                .hover_state
3901                .render(snapshot, visible_display_row_range.clone(), max_size, cx)
3902        });
3903        let Some((position, hover_popovers)) = hover_popovers else {
3904            return;
3905        };
3906
3907        // This is safe because we check on layout whether the required row is available
3908        let hovered_row_layout =
3909            &line_layouts[position.row().minus(visible_display_row_range.start) as usize];
3910
3911        // Compute Hovered Point
3912        let x =
3913            hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
3914        let y = position.row().as_f32() * line_height - scroll_pixel_position.y;
3915        let hovered_point = content_origin + point(x, y);
3916
3917        let mut overall_height = Pixels::ZERO;
3918        let mut measured_hover_popovers = Vec::new();
3919        for mut hover_popover in hover_popovers {
3920            let size = hover_popover.layout_as_root(AvailableSpace::min_size(), window, cx);
3921            let horizontal_offset =
3922                (text_hitbox.top_right().x - (hovered_point.x + size.width)).min(Pixels::ZERO);
3923
3924            overall_height += HOVER_POPOVER_GAP + size.height;
3925
3926            measured_hover_popovers.push(MeasuredHoverPopover {
3927                element: hover_popover,
3928                size,
3929                horizontal_offset,
3930            });
3931        }
3932        overall_height += HOVER_POPOVER_GAP;
3933
3934        fn draw_occluder(
3935            width: Pixels,
3936            origin: gpui::Point<Pixels>,
3937            window: &mut Window,
3938            cx: &mut App,
3939        ) {
3940            let mut occlusion = div()
3941                .size_full()
3942                .occlude()
3943                .on_mouse_move(|_, _, cx| cx.stop_propagation())
3944                .into_any_element();
3945            occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), window, cx);
3946            window.defer_draw(occlusion, origin, 2);
3947        }
3948
3949        if hovered_point.y > overall_height {
3950            // There is enough space above. Render popovers above the hovered point
3951            let mut current_y = hovered_point.y;
3952            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
3953                let size = popover.size;
3954                let popover_origin = point(
3955                    hovered_point.x + popover.horizontal_offset,
3956                    current_y - size.height,
3957                );
3958
3959                window.defer_draw(popover.element, popover_origin, 2);
3960                if position != itertools::Position::Last {
3961                    let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
3962                    draw_occluder(size.width, origin, window, cx);
3963                }
3964
3965                current_y = popover_origin.y - HOVER_POPOVER_GAP;
3966            }
3967        } else {
3968            // There is not enough space above. Render popovers below the hovered point
3969            let mut current_y = hovered_point.y + line_height;
3970            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
3971                let size = popover.size;
3972                let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
3973
3974                window.defer_draw(popover.element, popover_origin, 2);
3975                if position != itertools::Position::Last {
3976                    let origin = point(popover_origin.x, popover_origin.y + size.height);
3977                    draw_occluder(size.width, origin, window, cx);
3978                }
3979
3980                current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
3981            }
3982        }
3983    }
3984
3985    fn layout_diff_hunk_controls(
3986        &self,
3987        row_range: Range<DisplayRow>,
3988        row_infos: &[RowInfo],
3989        text_hitbox: &Hitbox,
3990        position_map: &PositionMap,
3991        newest_cursor_position: Option<DisplayPoint>,
3992        line_height: Pixels,
3993        scroll_pixel_position: gpui::Point<Pixels>,
3994        display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
3995        editor: Entity<Editor>,
3996        window: &mut Window,
3997        cx: &mut App,
3998    ) -> Vec<AnyElement> {
3999        let point_for_position = position_map.point_for_position(window.mouse_position());
4000
4001        let mut controls = vec![];
4002
4003        let active_positions = [
4004            Some(point_for_position.previous_valid),
4005            newest_cursor_position,
4006        ];
4007
4008        for (hunk, _) in display_hunks {
4009            if let DisplayDiffHunk::Unfolded {
4010                display_row_range,
4011                multi_buffer_range,
4012                status,
4013                is_created_file,
4014                ..
4015            } = &hunk
4016            {
4017                if display_row_range.start < row_range.start
4018                    || display_row_range.start >= row_range.end
4019                {
4020                    continue;
4021                }
4022                let row_ix = (display_row_range.start - row_range.start).0 as usize;
4023                if row_infos[row_ix].diff_status.is_none() {
4024                    continue;
4025                }
4026                if row_infos[row_ix]
4027                    .diff_status
4028                    .is_some_and(|status| status.is_added())
4029                    && !status.is_added()
4030                {
4031                    continue;
4032                }
4033                if active_positions
4034                    .iter()
4035                    .any(|p| p.map_or(false, |p| display_row_range.contains(&p.row())))
4036                {
4037                    let y = display_row_range.start.as_f32() * line_height
4038                        + text_hitbox.bounds.top()
4039                        - scroll_pixel_position.y;
4040
4041                    let mut element = diff_hunk_controls(
4042                        display_row_range.start.0,
4043                        status,
4044                        multi_buffer_range.clone(),
4045                        *is_created_file,
4046                        line_height,
4047                        &editor,
4048                        cx,
4049                    );
4050                    let size =
4051                        element.layout_as_root(size(px(100.0), line_height).into(), window, cx);
4052
4053                    let x = text_hitbox.bounds.right()
4054                        - self.style.scrollbar_width
4055                        - px(10.)
4056                        - size.width;
4057
4058                    window.with_absolute_element_offset(gpui::Point::new(x, y), |window| {
4059                        element.prepaint(window, cx)
4060                    });
4061                    controls.push(element);
4062                }
4063            }
4064        }
4065
4066        controls
4067    }
4068
4069    fn layout_signature_help(
4070        &self,
4071        hitbox: &Hitbox,
4072        content_origin: gpui::Point<Pixels>,
4073        scroll_pixel_position: gpui::Point<Pixels>,
4074        newest_selection_head: Option<DisplayPoint>,
4075        start_row: DisplayRow,
4076        line_layouts: &[LineWithInvisibles],
4077        line_height: Pixels,
4078        em_width: Pixels,
4079        window: &mut Window,
4080        cx: &mut App,
4081    ) {
4082        if !self.editor.focus_handle(cx).is_focused(window) {
4083            return;
4084        }
4085        let Some(newest_selection_head) = newest_selection_head else {
4086            return;
4087        };
4088        let selection_row = newest_selection_head.row();
4089        if selection_row < start_row {
4090            return;
4091        }
4092        let Some(cursor_row_layout) = line_layouts.get(selection_row.minus(start_row) as usize)
4093        else {
4094            return;
4095        };
4096
4097        let start_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
4098            - scroll_pixel_position.x
4099            + content_origin.x;
4100        let start_y =
4101            selection_row.as_f32() * line_height + content_origin.y - scroll_pixel_position.y;
4102
4103        let max_size = size(
4104            (120. * em_width) // Default size
4105                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
4106                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
4107            (16. * line_height) // Default size
4108                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
4109                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
4110        );
4111
4112        let maybe_element = self.editor.update(cx, |editor, cx| {
4113            if let Some(popover) = editor.signature_help_state.popover_mut() {
4114                let element = popover.render(max_size, cx);
4115                Some(element)
4116            } else {
4117                None
4118            }
4119        });
4120        if let Some(mut element) = maybe_element {
4121            let window_size = window.viewport_size();
4122            let size = element.layout_as_root(Size::<AvailableSpace>::default(), window, cx);
4123            let mut point = point(start_x, start_y - size.height);
4124
4125            // Adjusting to ensure the popover does not overflow in the X-axis direction.
4126            if point.x + size.width >= window_size.width {
4127                point.x = window_size.width - size.width;
4128            }
4129
4130            window.defer_draw(element, point, 1)
4131        }
4132    }
4133
4134    fn paint_background(&self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
4135        window.paint_layer(layout.hitbox.bounds, |window| {
4136            let scroll_top = layout.position_map.snapshot.scroll_position().y;
4137            let gutter_bg = cx.theme().colors().editor_gutter_background;
4138            window.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
4139            window.paint_quad(fill(
4140                layout.position_map.text_hitbox.bounds,
4141                self.style.background,
4142            ));
4143
4144            if let EditorMode::Full = layout.mode {
4145                let mut active_rows = layout.active_rows.iter().peekable();
4146                while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
4147                    let mut end_row = start_row.0;
4148                    while active_rows
4149                        .peek()
4150                        .map_or(false, |(active_row, has_selection)| {
4151                            active_row.0 == end_row + 1
4152                                && has_selection.selection == contains_non_empty_selection.selection
4153                        })
4154                    {
4155                        active_rows.next().unwrap();
4156                        end_row += 1;
4157                    }
4158
4159                    if !contains_non_empty_selection.selection {
4160                        let highlight_h_range =
4161                            match layout.position_map.snapshot.current_line_highlight {
4162                                CurrentLineHighlight::Gutter => Some(Range {
4163                                    start: layout.hitbox.left(),
4164                                    end: layout.gutter_hitbox.right(),
4165                                }),
4166                                CurrentLineHighlight::Line => Some(Range {
4167                                    start: layout.position_map.text_hitbox.bounds.left(),
4168                                    end: layout.position_map.text_hitbox.bounds.right(),
4169                                }),
4170                                CurrentLineHighlight::All => Some(Range {
4171                                    start: layout.hitbox.left(),
4172                                    end: layout.hitbox.right(),
4173                                }),
4174                                CurrentLineHighlight::None => None,
4175                            };
4176                        if let Some(range) = highlight_h_range {
4177                            let active_line_bg = cx.theme().colors().editor_active_line_background;
4178                            let bounds = Bounds {
4179                                origin: point(
4180                                    range.start,
4181                                    layout.hitbox.origin.y
4182                                        + (start_row.as_f32() - scroll_top)
4183                                            * layout.position_map.line_height,
4184                                ),
4185                                size: size(
4186                                    range.end - range.start,
4187                                    layout.position_map.line_height
4188                                        * (end_row - start_row.0 + 1) as f32,
4189                                ),
4190                            };
4191                            window.paint_quad(fill(bounds, active_line_bg));
4192                        }
4193                    }
4194                }
4195
4196                let mut paint_highlight = |highlight_row_start: DisplayRow,
4197                                           highlight_row_end: DisplayRow,
4198                                           highlight: crate::LineHighlight,
4199                                           edges| {
4200                    let origin = point(
4201                        layout.hitbox.origin.x,
4202                        layout.hitbox.origin.y
4203                            + (highlight_row_start.as_f32() - scroll_top)
4204                                * layout.position_map.line_height,
4205                    );
4206                    let size = size(
4207                        layout.hitbox.size.width,
4208                        layout.position_map.line_height
4209                            * highlight_row_end.next_row().minus(highlight_row_start) as f32,
4210                    );
4211                    let mut quad = fill(Bounds { origin, size }, highlight.background);
4212                    if let Some(border_color) = highlight.border {
4213                        quad.border_color = border_color;
4214                        quad.border_widths = edges
4215                    }
4216                    window.paint_quad(quad);
4217                };
4218
4219                let mut current_paint: Option<(LineHighlight, Range<DisplayRow>, Edges<Pixels>)> =
4220                    None;
4221                for (&new_row, &new_background) in &layout.highlighted_rows {
4222                    match &mut current_paint {
4223                        Some((current_background, current_range, mut edges)) => {
4224                            let current_background = *current_background;
4225                            let new_range_started = current_background != new_background
4226                                || current_range.end.next_row() != new_row;
4227                            if new_range_started {
4228                                if current_range.end.next_row() == new_row {
4229                                    edges.bottom = px(0.);
4230                                };
4231                                paint_highlight(
4232                                    current_range.start,
4233                                    current_range.end,
4234                                    current_background,
4235                                    edges,
4236                                );
4237                                let edges = Edges {
4238                                    top: if current_range.end.next_row() != new_row {
4239                                        px(1.)
4240                                    } else {
4241                                        px(0.)
4242                                    },
4243                                    bottom: px(1.),
4244                                    ..Default::default()
4245                                };
4246                                current_paint = Some((new_background, new_row..new_row, edges));
4247                                continue;
4248                            } else {
4249                                current_range.end = current_range.end.next_row();
4250                            }
4251                        }
4252                        None => {
4253                            let edges = Edges {
4254                                top: px(1.),
4255                                bottom: px(1.),
4256                                ..Default::default()
4257                            };
4258                            current_paint = Some((new_background, new_row..new_row, edges))
4259                        }
4260                    };
4261                }
4262                if let Some((color, range, edges)) = current_paint {
4263                    paint_highlight(range.start, range.end, color, edges);
4264                }
4265
4266                let scroll_left =
4267                    layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
4268
4269                for (wrap_position, active) in layout.wrap_guides.iter() {
4270                    let x = (layout.position_map.text_hitbox.origin.x
4271                        + *wrap_position
4272                        + layout.position_map.em_width / 2.)
4273                        - scroll_left;
4274
4275                    let show_scrollbars = {
4276                        let (scrollbar_x, scrollbar_y) = &layout.scrollbars_layout.as_xy();
4277
4278                        scrollbar_x.as_ref().map_or(false, |sx| sx.visible)
4279                            || scrollbar_y.as_ref().map_or(false, |sy| sy.visible)
4280                    };
4281
4282                    if x < layout.position_map.text_hitbox.origin.x
4283                        || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
4284                    {
4285                        continue;
4286                    }
4287
4288                    let color = if *active {
4289                        cx.theme().colors().editor_active_wrap_guide
4290                    } else {
4291                        cx.theme().colors().editor_wrap_guide
4292                    };
4293                    window.paint_quad(fill(
4294                        Bounds {
4295                            origin: point(x, layout.position_map.text_hitbox.origin.y),
4296                            size: size(px(1.), layout.position_map.text_hitbox.size.height),
4297                        },
4298                        color,
4299                    ));
4300                }
4301            }
4302        })
4303    }
4304
4305    fn paint_indent_guides(
4306        &mut self,
4307        layout: &mut EditorLayout,
4308        window: &mut Window,
4309        cx: &mut App,
4310    ) {
4311        let Some(indent_guides) = &layout.indent_guides else {
4312            return;
4313        };
4314
4315        let faded_color = |color: Hsla, alpha: f32| {
4316            let mut faded = color;
4317            faded.a = alpha;
4318            faded
4319        };
4320
4321        for indent_guide in indent_guides {
4322            let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
4323            let settings = indent_guide.settings;
4324
4325            // TODO fixed for now, expose them through themes later
4326            const INDENT_AWARE_ALPHA: f32 = 0.2;
4327            const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
4328            const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
4329            const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
4330
4331            let line_color = match (settings.coloring, indent_guide.active) {
4332                (IndentGuideColoring::Disabled, _) => None,
4333                (IndentGuideColoring::Fixed, false) => {
4334                    Some(cx.theme().colors().editor_indent_guide)
4335                }
4336                (IndentGuideColoring::Fixed, true) => {
4337                    Some(cx.theme().colors().editor_indent_guide_active)
4338                }
4339                (IndentGuideColoring::IndentAware, false) => {
4340                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
4341                }
4342                (IndentGuideColoring::IndentAware, true) => {
4343                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
4344                }
4345            };
4346
4347            let background_color = match (settings.background_coloring, indent_guide.active) {
4348                (IndentGuideBackgroundColoring::Disabled, _) => None,
4349                (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
4350                    indent_accent_colors,
4351                    INDENT_AWARE_BACKGROUND_ALPHA,
4352                )),
4353                (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
4354                    indent_accent_colors,
4355                    INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
4356                )),
4357            };
4358
4359            let requested_line_width = if indent_guide.active {
4360                settings.active_line_width
4361            } else {
4362                settings.line_width
4363            }
4364            .clamp(1, 10);
4365            let mut line_indicator_width = 0.;
4366            if let Some(color) = line_color {
4367                window.paint_quad(fill(
4368                    Bounds {
4369                        origin: indent_guide.origin,
4370                        size: size(px(requested_line_width as f32), indent_guide.length),
4371                    },
4372                    color,
4373                ));
4374                line_indicator_width = requested_line_width as f32;
4375            }
4376
4377            if let Some(color) = background_color {
4378                let width = indent_guide.single_indent_width - px(line_indicator_width);
4379                window.paint_quad(fill(
4380                    Bounds {
4381                        origin: point(
4382                            indent_guide.origin.x + px(line_indicator_width),
4383                            indent_guide.origin.y,
4384                        ),
4385                        size: size(width, indent_guide.length),
4386                    },
4387                    color,
4388                ));
4389            }
4390        }
4391    }
4392
4393    fn paint_line_numbers(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4394        let is_singleton = self.editor.read(cx).is_singleton(cx);
4395
4396        let line_height = layout.position_map.line_height;
4397        window.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
4398
4399        for LineNumberLayout {
4400            shaped_line,
4401            hitbox,
4402        } in layout.line_numbers.values()
4403        {
4404            let Some(hitbox) = hitbox else {
4405                continue;
4406            };
4407
4408            let Some(()) = (if !is_singleton && hitbox.is_hovered(window) {
4409                let color = cx.theme().colors().editor_hover_line_number;
4410
4411                let Some(line) = self
4412                    .shape_line_number(shaped_line.text.clone(), color, window)
4413                    .log_err()
4414                else {
4415                    continue;
4416                };
4417
4418                line.paint(hitbox.origin, line_height, window, cx).log_err()
4419            } else {
4420                shaped_line
4421                    .paint(hitbox.origin, line_height, window, cx)
4422                    .log_err()
4423            }) else {
4424                continue;
4425            };
4426
4427            // In singleton buffers, we select corresponding lines on the line number click, so use | -like cursor.
4428            // In multi buffers, we open file at the line number clicked, so use a pointing hand cursor.
4429            if is_singleton {
4430                window.set_cursor_style(CursorStyle::IBeam, &hitbox);
4431            } else {
4432                window.set_cursor_style(CursorStyle::PointingHand, &hitbox);
4433            }
4434        }
4435    }
4436
4437    fn paint_gutter_diff_hunks(layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4438        if layout.display_hunks.is_empty() {
4439            return;
4440        }
4441
4442        let line_height = layout.position_map.line_height;
4443        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4444            for (hunk, hitbox) in &layout.display_hunks {
4445                let hunk_to_paint = match hunk {
4446                    DisplayDiffHunk::Folded { .. } => {
4447                        let hunk_bounds = Self::diff_hunk_bounds(
4448                            &layout.position_map.snapshot,
4449                            line_height,
4450                            layout.gutter_hitbox.bounds,
4451                            &hunk,
4452                        );
4453                        Some((
4454                            hunk_bounds,
4455                            cx.theme().colors().version_control_modified,
4456                            Corners::all(px(0.)),
4457                            DiffHunkStatus::modified_none(),
4458                        ))
4459                    }
4460                    DisplayDiffHunk::Unfolded {
4461                        status,
4462                        display_row_range,
4463                        ..
4464                    } => hitbox.as_ref().map(|hunk_hitbox| match status.kind {
4465                        DiffHunkStatusKind::Added => (
4466                            hunk_hitbox.bounds,
4467                            cx.theme().colors().version_control_added,
4468                            Corners::all(px(0.)),
4469                            *status,
4470                        ),
4471                        DiffHunkStatusKind::Modified => (
4472                            hunk_hitbox.bounds,
4473                            cx.theme().colors().version_control_modified,
4474                            Corners::all(px(0.)),
4475                            *status,
4476                        ),
4477                        DiffHunkStatusKind::Deleted if !display_row_range.is_empty() => (
4478                            hunk_hitbox.bounds,
4479                            cx.theme().colors().version_control_deleted,
4480                            Corners::all(px(0.)),
4481                            *status,
4482                        ),
4483                        DiffHunkStatusKind::Deleted => (
4484                            Bounds::new(
4485                                point(
4486                                    hunk_hitbox.origin.x - hunk_hitbox.size.width,
4487                                    hunk_hitbox.origin.y,
4488                                ),
4489                                size(hunk_hitbox.size.width * px(2.), hunk_hitbox.size.height),
4490                            ),
4491                            cx.theme().colors().version_control_deleted,
4492                            Corners::all(1. * line_height),
4493                            *status,
4494                        ),
4495                    }),
4496                };
4497
4498                if let Some((hunk_bounds, background_color, corner_radii, status)) = hunk_to_paint {
4499                    // Flatten the background color with the editor color to prevent
4500                    // elements below transparent hunks from showing through
4501                    let flattened_background_color = cx
4502                        .theme()
4503                        .colors()
4504                        .editor_background
4505                        .blend(background_color);
4506
4507                    if !Self::diff_hunk_hollow(status, cx) {
4508                        window.paint_quad(quad(
4509                            hunk_bounds,
4510                            corner_radii,
4511                            flattened_background_color,
4512                            Edges::default(),
4513                            transparent_black(),
4514                        ));
4515                    } else {
4516                        let flattened_unstaged_background_color = cx
4517                            .theme()
4518                            .colors()
4519                            .editor_background
4520                            .blend(background_color.opacity(0.3));
4521
4522                        window.paint_quad(quad(
4523                            hunk_bounds,
4524                            corner_radii,
4525                            flattened_unstaged_background_color,
4526                            Edges::all(Pixels(1.0)),
4527                            flattened_background_color,
4528                        ));
4529                    }
4530                }
4531            }
4532        });
4533    }
4534
4535    fn gutter_strip_width(line_height: Pixels) -> Pixels {
4536        (0.275 * line_height).floor()
4537    }
4538
4539    fn diff_hunk_bounds(
4540        snapshot: &EditorSnapshot,
4541        line_height: Pixels,
4542        gutter_bounds: Bounds<Pixels>,
4543        hunk: &DisplayDiffHunk,
4544    ) -> Bounds<Pixels> {
4545        let scroll_position = snapshot.scroll_position();
4546        let scroll_top = scroll_position.y * line_height;
4547        let gutter_strip_width = Self::gutter_strip_width(line_height);
4548
4549        match hunk {
4550            DisplayDiffHunk::Folded { display_row, .. } => {
4551                let start_y = display_row.as_f32() * line_height - scroll_top;
4552                let end_y = start_y + line_height;
4553                let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4554                let highlight_size = size(gutter_strip_width, end_y - start_y);
4555                Bounds::new(highlight_origin, highlight_size)
4556            }
4557            DisplayDiffHunk::Unfolded {
4558                display_row_range,
4559                status,
4560                ..
4561            } => {
4562                if status.is_deleted() && display_row_range.is_empty() {
4563                    let row = display_row_range.start;
4564
4565                    let offset = line_height / 2.;
4566                    let start_y = row.as_f32() * line_height - offset - scroll_top;
4567                    let end_y = start_y + line_height;
4568
4569                    let width = (0.35 * line_height).floor();
4570                    let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4571                    let highlight_size = size(width, end_y - start_y);
4572                    Bounds::new(highlight_origin, highlight_size)
4573                } else {
4574                    let start_row = display_row_range.start;
4575                    let end_row = display_row_range.end;
4576                    // If we're in a multibuffer, row range span might include an
4577                    // excerpt header, so if we were to draw the marker straight away,
4578                    // the hunk might include the rows of that header.
4579                    // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
4580                    // Instead, we simply check whether the range we're dealing with includes
4581                    // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
4582                    let end_row_in_current_excerpt = snapshot
4583                        .blocks_in_range(start_row..end_row)
4584                        .find_map(|(start_row, block)| {
4585                            if matches!(block, Block::ExcerptBoundary { .. }) {
4586                                Some(start_row)
4587                            } else {
4588                                None
4589                            }
4590                        })
4591                        .unwrap_or(end_row);
4592
4593                    let start_y = start_row.as_f32() * line_height - scroll_top;
4594                    let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
4595
4596                    let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4597                    let highlight_size = size(gutter_strip_width, end_y - start_y);
4598                    Bounds::new(highlight_origin, highlight_size)
4599                }
4600            }
4601        }
4602    }
4603
4604    fn paint_gutter_indicators(
4605        &self,
4606        layout: &mut EditorLayout,
4607        window: &mut Window,
4608        cx: &mut App,
4609    ) {
4610        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4611            window.with_element_namespace("crease_toggles", |window| {
4612                for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
4613                    crease_toggle.paint(window, cx);
4614                }
4615            });
4616
4617            window.with_element_namespace("expand_toggles", |window| {
4618                for (expand_toggle, _) in layout.expand_toggles.iter_mut().flatten() {
4619                    expand_toggle.paint(window, cx);
4620                }
4621            });
4622
4623            for breakpoint in layout.breakpoints.iter_mut() {
4624                breakpoint.paint(window, cx);
4625            }
4626
4627            for test_indicator in layout.test_indicators.iter_mut() {
4628                test_indicator.paint(window, cx);
4629            }
4630
4631            if let Some(indicator) = layout.code_actions_indicator.as_mut() {
4632                indicator.paint(window, cx);
4633            }
4634        });
4635    }
4636
4637    fn paint_gutter_highlights(
4638        &self,
4639        layout: &mut EditorLayout,
4640        window: &mut Window,
4641        cx: &mut App,
4642    ) {
4643        for (_, hunk_hitbox) in &layout.display_hunks {
4644            if let Some(hunk_hitbox) = hunk_hitbox {
4645                if !self
4646                    .editor
4647                    .read(cx)
4648                    .buffer()
4649                    .read(cx)
4650                    .all_diff_hunks_expanded()
4651                {
4652                    window.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
4653                }
4654            }
4655        }
4656
4657        let show_git_gutter = layout
4658            .position_map
4659            .snapshot
4660            .show_git_diff_gutter
4661            .unwrap_or_else(|| {
4662                matches!(
4663                    ProjectSettings::get_global(cx).git.git_gutter,
4664                    Some(GitGutterSetting::TrackedFiles)
4665                )
4666            });
4667        if show_git_gutter {
4668            Self::paint_gutter_diff_hunks(layout, window, cx)
4669        }
4670
4671        let highlight_width = 0.275 * layout.position_map.line_height;
4672        let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
4673        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4674            for (range, color) in &layout.highlighted_gutter_ranges {
4675                let start_row = if range.start.row() < layout.visible_display_row_range.start {
4676                    layout.visible_display_row_range.start - DisplayRow(1)
4677                } else {
4678                    range.start.row()
4679                };
4680                let end_row = if range.end.row() > layout.visible_display_row_range.end {
4681                    layout.visible_display_row_range.end + DisplayRow(1)
4682                } else {
4683                    range.end.row()
4684                };
4685
4686                let start_y = layout.gutter_hitbox.top()
4687                    + start_row.0 as f32 * layout.position_map.line_height
4688                    - layout.position_map.scroll_pixel_position.y;
4689                let end_y = layout.gutter_hitbox.top()
4690                    + (end_row.0 + 1) as f32 * layout.position_map.line_height
4691                    - layout.position_map.scroll_pixel_position.y;
4692                let bounds = Bounds::from_corners(
4693                    point(layout.gutter_hitbox.left(), start_y),
4694                    point(layout.gutter_hitbox.left() + highlight_width, end_y),
4695                );
4696                window.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
4697            }
4698        });
4699    }
4700
4701    fn paint_blamed_display_rows(
4702        &self,
4703        layout: &mut EditorLayout,
4704        window: &mut Window,
4705        cx: &mut App,
4706    ) {
4707        let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
4708            return;
4709        };
4710
4711        window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4712            for mut blame_element in blamed_display_rows.into_iter() {
4713                blame_element.paint(window, cx);
4714            }
4715        })
4716    }
4717
4718    fn paint_text(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4719        window.with_content_mask(
4720            Some(ContentMask {
4721                bounds: layout.position_map.text_hitbox.bounds,
4722            }),
4723            |window| {
4724                let cursor_style = if self
4725                    .editor
4726                    .read(cx)
4727                    .hovered_link_state
4728                    .as_ref()
4729                    .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
4730                {
4731                    CursorStyle::PointingHand
4732                } else {
4733                    CursorStyle::IBeam
4734                };
4735                window.set_cursor_style(cursor_style, &layout.position_map.text_hitbox);
4736
4737                self.paint_lines_background(layout, window, cx);
4738                let invisible_display_ranges = self.paint_highlights(layout, window);
4739                self.paint_lines(&invisible_display_ranges, layout, window, cx);
4740                self.paint_redactions(layout, window);
4741                self.paint_cursors(layout, window, cx);
4742                self.paint_inline_diagnostics(layout, window, cx);
4743                self.paint_inline_blame(layout, window, cx);
4744                self.paint_diff_hunk_controls(layout, window, cx);
4745                window.with_element_namespace("crease_trailers", |window| {
4746                    for trailer in layout.crease_trailers.iter_mut().flatten() {
4747                        trailer.element.paint(window, cx);
4748                    }
4749                });
4750            },
4751        )
4752    }
4753
4754    fn paint_highlights(
4755        &mut self,
4756        layout: &mut EditorLayout,
4757        window: &mut Window,
4758    ) -> SmallVec<[Range<DisplayPoint>; 32]> {
4759        window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
4760            let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
4761            let line_end_overshoot = 0.15 * layout.position_map.line_height;
4762            for (range, color) in &layout.highlighted_ranges {
4763                self.paint_highlighted_range(
4764                    range.clone(),
4765                    *color,
4766                    Pixels::ZERO,
4767                    line_end_overshoot,
4768                    layout,
4769                    window,
4770                );
4771            }
4772
4773            let corner_radius = 0.15 * layout.position_map.line_height;
4774
4775            for (player_color, selections) in &layout.selections {
4776                for selection in selections.iter() {
4777                    self.paint_highlighted_range(
4778                        selection.range.clone(),
4779                        player_color.selection,
4780                        corner_radius,
4781                        corner_radius * 2.,
4782                        layout,
4783                        window,
4784                    );
4785
4786                    if selection.is_local && !selection.range.is_empty() {
4787                        invisible_display_ranges.push(selection.range.clone());
4788                    }
4789                }
4790            }
4791            invisible_display_ranges
4792        })
4793    }
4794
4795    fn paint_lines(
4796        &mut self,
4797        invisible_display_ranges: &[Range<DisplayPoint>],
4798        layout: &mut EditorLayout,
4799        window: &mut Window,
4800        cx: &mut App,
4801    ) {
4802        let whitespace_setting = self
4803            .editor
4804            .read(cx)
4805            .buffer
4806            .read(cx)
4807            .language_settings(cx)
4808            .show_whitespaces;
4809
4810        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
4811            let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
4812            line_with_invisibles.draw(
4813                layout,
4814                row,
4815                layout.content_origin,
4816                whitespace_setting,
4817                invisible_display_ranges,
4818                window,
4819                cx,
4820            )
4821        }
4822
4823        for line_element in &mut layout.line_elements {
4824            line_element.paint(window, cx);
4825        }
4826    }
4827
4828    fn paint_lines_background(
4829        &mut self,
4830        layout: &mut EditorLayout,
4831        window: &mut Window,
4832        cx: &mut App,
4833    ) {
4834        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
4835            let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
4836            line_with_invisibles.draw_background(layout, row, layout.content_origin, window, cx);
4837        }
4838    }
4839
4840    fn paint_redactions(&mut self, layout: &EditorLayout, window: &mut Window) {
4841        if layout.redacted_ranges.is_empty() {
4842            return;
4843        }
4844
4845        let line_end_overshoot = layout.line_end_overshoot();
4846
4847        // A softer than perfect black
4848        let redaction_color = gpui::rgb(0x0e1111);
4849
4850        window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
4851            for range in layout.redacted_ranges.iter() {
4852                self.paint_highlighted_range(
4853                    range.clone(),
4854                    redaction_color.into(),
4855                    Pixels::ZERO,
4856                    line_end_overshoot,
4857                    layout,
4858                    window,
4859                );
4860            }
4861        });
4862    }
4863
4864    fn paint_cursors(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4865        for cursor in &mut layout.visible_cursors {
4866            cursor.paint(layout.content_origin, window, cx);
4867        }
4868    }
4869
4870    fn paint_scrollbars(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4871        let (scrollbar_x, scrollbar_y) = layout.scrollbars_layout.as_xy();
4872
4873        if let Some(scrollbar_layout) = scrollbar_x {
4874            let hitbox = scrollbar_layout.hitbox.clone();
4875            let text_unit_size = scrollbar_layout.text_unit_size;
4876            let visible_range = scrollbar_layout.visible_range.clone();
4877            let thumb_bounds = scrollbar_layout.thumb_bounds();
4878
4879            if scrollbar_layout.visible {
4880                window.paint_layer(hitbox.bounds, |window| {
4881                    window.paint_quad(quad(
4882                        hitbox.bounds,
4883                        Corners::default(),
4884                        cx.theme().colors().scrollbar_track_background,
4885                        Edges {
4886                            top: Pixels::ZERO,
4887                            right: Pixels::ZERO,
4888                            bottom: Pixels::ZERO,
4889                            left: Pixels::ZERO,
4890                        },
4891                        cx.theme().colors().scrollbar_track_border,
4892                    ));
4893
4894                    window.paint_quad(quad(
4895                        thumb_bounds,
4896                        Corners::default(),
4897                        cx.theme().colors().scrollbar_thumb_background,
4898                        Edges {
4899                            top: Pixels::ZERO,
4900                            right: Pixels::ZERO,
4901                            bottom: Pixels::ZERO,
4902                            left: ScrollbarLayout::BORDER_WIDTH,
4903                        },
4904                        cx.theme().colors().scrollbar_thumb_border,
4905                    ));
4906                })
4907            }
4908
4909            window.set_cursor_style(CursorStyle::Arrow, &hitbox);
4910
4911            window.on_mouse_event({
4912                let editor = self.editor.clone();
4913
4914                // there may be a way to avoid this clone
4915                let hitbox = hitbox.clone();
4916
4917                let mut mouse_position = window.mouse_position();
4918                move |event: &MouseMoveEvent, phase, window, cx| {
4919                    if phase == DispatchPhase::Capture {
4920                        return;
4921                    }
4922
4923                    editor.update(cx, |editor, cx| {
4924                        if event.pressed_button == Some(MouseButton::Left)
4925                            && editor
4926                                .scroll_manager
4927                                .is_dragging_scrollbar(Axis::Horizontal)
4928                        {
4929                            let x = mouse_position.x;
4930                            let new_x = event.position.x;
4931                            if (hitbox.left()..hitbox.right()).contains(&x) {
4932                                let mut position = editor.scroll_position(cx);
4933
4934                                position.x += (new_x - x) / text_unit_size;
4935                                if position.x < 0.0 {
4936                                    position.x = 0.0;
4937                                }
4938                                editor.set_scroll_position(position, window, cx);
4939                            }
4940
4941                            cx.stop_propagation();
4942                        } else {
4943                            editor.scroll_manager.set_is_dragging_scrollbar(
4944                                Axis::Horizontal,
4945                                false,
4946                                cx,
4947                            );
4948
4949                            if hitbox.is_hovered(window) {
4950                                editor.scroll_manager.show_scrollbar(window, cx);
4951                            }
4952                        }
4953                        mouse_position = event.position;
4954                    })
4955                }
4956            });
4957
4958            if self
4959                .editor
4960                .read(cx)
4961                .scroll_manager
4962                .is_dragging_scrollbar(Axis::Horizontal)
4963            {
4964                window.on_mouse_event({
4965                    let editor = self.editor.clone();
4966                    move |_: &MouseUpEvent, phase, _, cx| {
4967                        if phase == DispatchPhase::Capture {
4968                            return;
4969                        }
4970
4971                        editor.update(cx, |editor, cx| {
4972                            editor.scroll_manager.set_is_dragging_scrollbar(
4973                                Axis::Horizontal,
4974                                false,
4975                                cx,
4976                            );
4977                            cx.stop_propagation();
4978                        });
4979                    }
4980                });
4981            } else {
4982                window.on_mouse_event({
4983                    let editor = self.editor.clone();
4984
4985                    move |event: &MouseDownEvent, phase, window, cx| {
4986                        if phase == DispatchPhase::Capture || !hitbox.is_hovered(window) {
4987                            return;
4988                        }
4989
4990                        editor.update(cx, |editor, cx| {
4991                            editor.scroll_manager.set_is_dragging_scrollbar(
4992                                Axis::Horizontal,
4993                                true,
4994                                cx,
4995                            );
4996
4997                            let x = event.position.x;
4998
4999                            if x < thumb_bounds.left() || thumb_bounds.right() < x {
5000                                let center_row =
5001                                    ((x - hitbox.left()) / text_unit_size).round() as u32;
5002                                let top_row = center_row.saturating_sub(
5003                                    (visible_range.end - visible_range.start) as u32 / 2,
5004                                );
5005
5006                                let mut position = editor.scroll_position(cx);
5007                                position.x = top_row as f32;
5008
5009                                editor.set_scroll_position(position, window, cx);
5010                            } else {
5011                                editor.scroll_manager.show_scrollbar(window, cx);
5012                            }
5013
5014                            cx.stop_propagation();
5015                        });
5016                    }
5017                });
5018            }
5019        }
5020
5021        if let Some(scrollbar_layout) = scrollbar_y {
5022            let hitbox = scrollbar_layout.hitbox.clone();
5023            let text_unit_size = scrollbar_layout.text_unit_size;
5024            let visible_range = scrollbar_layout.visible_range.clone();
5025            let thumb_bounds = scrollbar_layout.thumb_bounds();
5026
5027            if scrollbar_layout.visible {
5028                window.paint_layer(hitbox.bounds, |window| {
5029                    window.paint_quad(quad(
5030                        hitbox.bounds,
5031                        Corners::default(),
5032                        cx.theme().colors().scrollbar_track_background,
5033                        Edges {
5034                            top: Pixels::ZERO,
5035                            right: Pixels::ZERO,
5036                            bottom: Pixels::ZERO,
5037                            left: ScrollbarLayout::BORDER_WIDTH,
5038                        },
5039                        cx.theme().colors().scrollbar_track_border,
5040                    ));
5041
5042                    let fast_markers =
5043                        self.collect_fast_scrollbar_markers(layout, &scrollbar_layout, cx);
5044                    // Refresh slow scrollbar markers in the background. Below, we paint whatever markers have already been computed.
5045                    self.refresh_slow_scrollbar_markers(layout, &scrollbar_layout, window, cx);
5046
5047                    let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
5048                    for marker in markers.iter().chain(&fast_markers) {
5049                        let mut marker = marker.clone();
5050                        marker.bounds.origin += hitbox.origin;
5051                        window.paint_quad(marker);
5052                    }
5053
5054                    window.paint_quad(quad(
5055                        thumb_bounds,
5056                        Corners::default(),
5057                        cx.theme().colors().scrollbar_thumb_background,
5058                        Edges {
5059                            top: Pixels::ZERO,
5060                            right: Pixels::ZERO,
5061                            bottom: Pixels::ZERO,
5062                            left: ScrollbarLayout::BORDER_WIDTH,
5063                        },
5064                        cx.theme().colors().scrollbar_thumb_border,
5065                    ));
5066                });
5067            }
5068
5069            window.set_cursor_style(CursorStyle::Arrow, &hitbox);
5070
5071            window.on_mouse_event({
5072                let editor = self.editor.clone();
5073
5074                let hitbox = hitbox.clone();
5075
5076                let mut mouse_position = window.mouse_position();
5077                move |event: &MouseMoveEvent, phase, window, cx| {
5078                    if phase == DispatchPhase::Capture {
5079                        return;
5080                    }
5081
5082                    editor.update(cx, |editor, cx| {
5083                        if event.pressed_button == Some(MouseButton::Left)
5084                            && editor.scroll_manager.is_dragging_scrollbar(Axis::Vertical)
5085                        {
5086                            let y = mouse_position.y;
5087                            let new_y = event.position.y;
5088                            if (hitbox.top()..hitbox.bottom()).contains(&y) {
5089                                let mut position = editor.scroll_position(cx);
5090                                position.y += (new_y - y) / text_unit_size;
5091                                if position.y < 0.0 {
5092                                    position.y = 0.0;
5093                                }
5094                                editor.set_scroll_position(position, window, cx);
5095                            }
5096                        } else {
5097                            editor.scroll_manager.set_is_dragging_scrollbar(
5098                                Axis::Vertical,
5099                                false,
5100                                cx,
5101                            );
5102
5103                            if hitbox.is_hovered(window) {
5104                                editor.scroll_manager.show_scrollbar(window, cx);
5105                            }
5106                        }
5107                        mouse_position = event.position;
5108                    })
5109                }
5110            });
5111
5112            if self
5113                .editor
5114                .read(cx)
5115                .scroll_manager
5116                .is_dragging_scrollbar(Axis::Vertical)
5117            {
5118                window.on_mouse_event({
5119                    let editor = self.editor.clone();
5120                    move |_: &MouseUpEvent, phase, _, cx| {
5121                        if phase == DispatchPhase::Capture {
5122                            return;
5123                        }
5124
5125                        editor.update(cx, |editor, cx| {
5126                            editor.scroll_manager.set_is_dragging_scrollbar(
5127                                Axis::Vertical,
5128                                false,
5129                                cx,
5130                            );
5131                            cx.stop_propagation();
5132                        });
5133                    }
5134                });
5135            } else {
5136                window.on_mouse_event({
5137                    let editor = self.editor.clone();
5138
5139                    move |event: &MouseDownEvent, phase, window, cx| {
5140                        if phase == DispatchPhase::Capture || !hitbox.is_hovered(window) {
5141                            return;
5142                        }
5143
5144                        editor.update(cx, |editor, cx| {
5145                            editor.scroll_manager.set_is_dragging_scrollbar(
5146                                Axis::Vertical,
5147                                true,
5148                                cx,
5149                            );
5150
5151                            let y = event.position.y;
5152                            if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
5153                                let center_row =
5154                                    ((y - hitbox.top()) / text_unit_size).round() as u32;
5155                                let top_row = center_row.saturating_sub(
5156                                    (visible_range.end - visible_range.start) as u32 / 2,
5157                                );
5158                                let mut position = editor.scroll_position(cx);
5159                                position.y = top_row as f32;
5160                                editor.set_scroll_position(position, window, cx);
5161                            } else {
5162                                editor.scroll_manager.show_scrollbar(window, cx);
5163                            }
5164
5165                            cx.stop_propagation();
5166                        });
5167                    }
5168                });
5169            }
5170        }
5171    }
5172
5173    fn collect_fast_scrollbar_markers(
5174        &self,
5175        layout: &EditorLayout,
5176        scrollbar_layout: &ScrollbarLayout,
5177        cx: &mut App,
5178    ) -> Vec<PaintQuad> {
5179        const LIMIT: usize = 100;
5180        if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
5181            return vec![];
5182        }
5183        let cursor_ranges = layout
5184            .cursors
5185            .iter()
5186            .map(|(point, color)| ColoredRange {
5187                start: point.row(),
5188                end: point.row(),
5189                color: *color,
5190            })
5191            .collect_vec();
5192        scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
5193    }
5194
5195    fn refresh_slow_scrollbar_markers(
5196        &self,
5197        layout: &EditorLayout,
5198        scrollbar_layout: &ScrollbarLayout,
5199        window: &mut Window,
5200        cx: &mut App,
5201    ) {
5202        self.editor.update(cx, |editor, cx| {
5203            if !editor.is_singleton(cx)
5204                || !editor
5205                    .scrollbar_marker_state
5206                    .should_refresh(scrollbar_layout.hitbox.size)
5207            {
5208                return;
5209            }
5210
5211            let scrollbar_layout = scrollbar_layout.clone();
5212            let background_highlights = editor.background_highlights.clone();
5213            let snapshot = layout.position_map.snapshot.clone();
5214            let theme = cx.theme().clone();
5215            let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
5216
5217            editor.scrollbar_marker_state.dirty = false;
5218            editor.scrollbar_marker_state.pending_refresh =
5219                Some(cx.spawn_in(window, async move |editor, cx| {
5220                    let scrollbar_size = scrollbar_layout.hitbox.size;
5221                    let scrollbar_markers = cx
5222                        .background_spawn(async move {
5223                            let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
5224                            let mut marker_quads = Vec::new();
5225                            if scrollbar_settings.git_diff {
5226                                let marker_row_ranges =
5227                                    snapshot.buffer_snapshot.diff_hunks().map(|hunk| {
5228                                        let start_display_row =
5229                                            MultiBufferPoint::new(hunk.row_range.start.0, 0)
5230                                                .to_display_point(&snapshot.display_snapshot)
5231                                                .row();
5232                                        let mut end_display_row =
5233                                            MultiBufferPoint::new(hunk.row_range.end.0, 0)
5234                                                .to_display_point(&snapshot.display_snapshot)
5235                                                .row();
5236                                        if end_display_row != start_display_row {
5237                                            end_display_row.0 -= 1;
5238                                        }
5239                                        let color = match &hunk.status().kind {
5240                                            DiffHunkStatusKind::Added => {
5241                                                theme.colors().version_control_added
5242                                            }
5243                                            DiffHunkStatusKind::Modified => {
5244                                                theme.colors().version_control_modified
5245                                            }
5246                                            DiffHunkStatusKind::Deleted => {
5247                                                theme.colors().version_control_deleted
5248                                            }
5249                                        };
5250                                        ColoredRange {
5251                                            start: start_display_row,
5252                                            end: end_display_row,
5253                                            color,
5254                                        }
5255                                    });
5256
5257                                marker_quads.extend(
5258                                    scrollbar_layout
5259                                        .marker_quads_for_ranges(marker_row_ranges, Some(0)),
5260                                );
5261                            }
5262
5263                            for (background_highlight_id, (_, background_ranges)) in
5264                                background_highlights.iter()
5265                            {
5266                                let is_search_highlights = *background_highlight_id
5267                                    == TypeId::of::<BufferSearchHighlights>();
5268                                let is_text_highlights = *background_highlight_id
5269                                    == TypeId::of::<SelectedTextHighlight>();
5270                                let is_symbol_occurrences = *background_highlight_id
5271                                    == TypeId::of::<DocumentHighlightRead>()
5272                                    || *background_highlight_id
5273                                        == TypeId::of::<DocumentHighlightWrite>();
5274                                if (is_search_highlights && scrollbar_settings.search_results)
5275                                    || (is_text_highlights && scrollbar_settings.selected_text)
5276                                    || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
5277                                {
5278                                    let mut color = theme.status().info;
5279                                    if is_symbol_occurrences {
5280                                        color.fade_out(0.5);
5281                                    }
5282                                    let marker_row_ranges = background_ranges.iter().map(|range| {
5283                                        let display_start = range
5284                                            .start
5285                                            .to_display_point(&snapshot.display_snapshot);
5286                                        let display_end =
5287                                            range.end.to_display_point(&snapshot.display_snapshot);
5288                                        ColoredRange {
5289                                            start: display_start.row(),
5290                                            end: display_end.row(),
5291                                            color,
5292                                        }
5293                                    });
5294                                    marker_quads.extend(
5295                                        scrollbar_layout
5296                                            .marker_quads_for_ranges(marker_row_ranges, Some(1)),
5297                                    );
5298                                }
5299                            }
5300
5301                            if scrollbar_settings.diagnostics != ScrollbarDiagnostics::None {
5302                                let diagnostics = snapshot
5303                                    .buffer_snapshot
5304                                    .diagnostics_in_range::<Point>(Point::zero()..max_point)
5305                                    // Don't show diagnostics the user doesn't care about
5306                                    .filter(|diagnostic| {
5307                                        match (
5308                                            scrollbar_settings.diagnostics,
5309                                            diagnostic.diagnostic.severity,
5310                                        ) {
5311                                            (ScrollbarDiagnostics::All, _) => true,
5312                                            (
5313                                                ScrollbarDiagnostics::Error,
5314                                                DiagnosticSeverity::ERROR,
5315                                            ) => true,
5316                                            (
5317                                                ScrollbarDiagnostics::Warning,
5318                                                DiagnosticSeverity::ERROR
5319                                                | DiagnosticSeverity::WARNING,
5320                                            ) => true,
5321                                            (
5322                                                ScrollbarDiagnostics::Information,
5323                                                DiagnosticSeverity::ERROR
5324                                                | DiagnosticSeverity::WARNING
5325                                                | DiagnosticSeverity::INFORMATION,
5326                                            ) => true,
5327                                            (_, _) => false,
5328                                        }
5329                                    })
5330                                    // We want to sort by severity, in order to paint the most severe diagnostics last.
5331                                    .sorted_by_key(|diagnostic| {
5332                                        std::cmp::Reverse(diagnostic.diagnostic.severity)
5333                                    });
5334
5335                                let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
5336                                    let start_display = diagnostic
5337                                        .range
5338                                        .start
5339                                        .to_display_point(&snapshot.display_snapshot);
5340                                    let end_display = diagnostic
5341                                        .range
5342                                        .end
5343                                        .to_display_point(&snapshot.display_snapshot);
5344                                    let color = match diagnostic.diagnostic.severity {
5345                                        DiagnosticSeverity::ERROR => theme.status().error,
5346                                        DiagnosticSeverity::WARNING => theme.status().warning,
5347                                        DiagnosticSeverity::INFORMATION => theme.status().info,
5348                                        _ => theme.status().hint,
5349                                    };
5350                                    ColoredRange {
5351                                        start: start_display.row(),
5352                                        end: end_display.row(),
5353                                        color,
5354                                    }
5355                                });
5356                                marker_quads.extend(
5357                                    scrollbar_layout
5358                                        .marker_quads_for_ranges(marker_row_ranges, Some(2)),
5359                                );
5360                            }
5361
5362                            Arc::from(marker_quads)
5363                        })
5364                        .await;
5365
5366                    editor.update(cx, |editor, cx| {
5367                        editor.scrollbar_marker_state.markers = scrollbar_markers;
5368                        editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
5369                        editor.scrollbar_marker_state.pending_refresh = None;
5370                        cx.notify();
5371                    })?;
5372
5373                    Ok(())
5374                }));
5375        });
5376    }
5377
5378    fn paint_highlighted_range(
5379        &self,
5380        range: Range<DisplayPoint>,
5381        color: Hsla,
5382        corner_radius: Pixels,
5383        line_end_overshoot: Pixels,
5384        layout: &EditorLayout,
5385        window: &mut Window,
5386    ) {
5387        let start_row = layout.visible_display_row_range.start;
5388        let end_row = layout.visible_display_row_range.end;
5389        if range.start != range.end {
5390            let row_range = if range.end.column() == 0 {
5391                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
5392            } else {
5393                cmp::max(range.start.row(), start_row)
5394                    ..cmp::min(range.end.row().next_row(), end_row)
5395            };
5396
5397            let highlighted_range = HighlightedRange {
5398                color,
5399                line_height: layout.position_map.line_height,
5400                corner_radius,
5401                start_y: layout.content_origin.y
5402                    + row_range.start.as_f32() * layout.position_map.line_height
5403                    - layout.position_map.scroll_pixel_position.y,
5404                lines: row_range
5405                    .iter_rows()
5406                    .map(|row| {
5407                        let line_layout =
5408                            &layout.position_map.line_layouts[row.minus(start_row) as usize];
5409                        HighlightedRangeLine {
5410                            start_x: if row == range.start.row() {
5411                                layout.content_origin.x
5412                                    + line_layout.x_for_index(range.start.column() as usize)
5413                                    - layout.position_map.scroll_pixel_position.x
5414                            } else {
5415                                layout.content_origin.x
5416                                    - layout.position_map.scroll_pixel_position.x
5417                            },
5418                            end_x: if row == range.end.row() {
5419                                layout.content_origin.x
5420                                    + line_layout.x_for_index(range.end.column() as usize)
5421                                    - layout.position_map.scroll_pixel_position.x
5422                            } else {
5423                                layout.content_origin.x + line_layout.width + line_end_overshoot
5424                                    - layout.position_map.scroll_pixel_position.x
5425                            },
5426                        }
5427                    })
5428                    .collect(),
5429            };
5430
5431            highlighted_range.paint(layout.position_map.text_hitbox.bounds, window);
5432        }
5433    }
5434
5435    fn paint_inline_diagnostics(
5436        &mut self,
5437        layout: &mut EditorLayout,
5438        window: &mut Window,
5439        cx: &mut App,
5440    ) {
5441        for mut inline_diagnostic in layout.inline_diagnostics.drain() {
5442            inline_diagnostic.1.paint(window, cx);
5443        }
5444    }
5445
5446    fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5447        if let Some(mut inline_blame) = layout.inline_blame.take() {
5448            window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
5449                inline_blame.paint(window, cx);
5450            })
5451        }
5452    }
5453
5454    fn paint_diff_hunk_controls(
5455        &mut self,
5456        layout: &mut EditorLayout,
5457        window: &mut Window,
5458        cx: &mut App,
5459    ) {
5460        for mut diff_hunk_control in layout.diff_hunk_controls.drain(..) {
5461            diff_hunk_control.paint(window, cx);
5462        }
5463    }
5464
5465    fn paint_blocks(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5466        for mut block in layout.blocks.drain(..) {
5467            block.element.paint(window, cx);
5468        }
5469    }
5470
5471    fn paint_inline_completion_popover(
5472        &mut self,
5473        layout: &mut EditorLayout,
5474        window: &mut Window,
5475        cx: &mut App,
5476    ) {
5477        if let Some(inline_completion_popover) = layout.inline_completion_popover.as_mut() {
5478            inline_completion_popover.paint(window, cx);
5479        }
5480    }
5481
5482    fn paint_mouse_context_menu(
5483        &mut self,
5484        layout: &mut EditorLayout,
5485        window: &mut Window,
5486        cx: &mut App,
5487    ) {
5488        if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
5489            mouse_context_menu.paint(window, cx);
5490        }
5491    }
5492
5493    fn paint_scroll_wheel_listener(
5494        &mut self,
5495        layout: &EditorLayout,
5496        window: &mut Window,
5497        cx: &mut App,
5498    ) {
5499        window.on_mouse_event({
5500            let position_map = layout.position_map.clone();
5501            let editor = self.editor.clone();
5502            let hitbox = layout.hitbox.clone();
5503            let mut delta = ScrollDelta::default();
5504
5505            // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
5506            // accidentally turn off their scrolling.
5507            let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
5508
5509            move |event: &ScrollWheelEvent, phase, window, cx| {
5510                if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
5511                    delta = delta.coalesce(event.delta);
5512                    editor.update(cx, |editor, cx| {
5513                        let position_map: &PositionMap = &position_map;
5514
5515                        let line_height = position_map.line_height;
5516                        let max_glyph_width = position_map.em_width;
5517                        let (delta, axis) = match delta {
5518                            gpui::ScrollDelta::Pixels(mut pixels) => {
5519                                //Trackpad
5520                                let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
5521                                (pixels, axis)
5522                            }
5523
5524                            gpui::ScrollDelta::Lines(lines) => {
5525                                //Not trackpad
5526                                let pixels =
5527                                    point(lines.x * max_glyph_width, lines.y * line_height);
5528                                (pixels, None)
5529                            }
5530                        };
5531
5532                        let current_scroll_position = position_map.snapshot.scroll_position();
5533                        let x = (current_scroll_position.x * max_glyph_width
5534                            - (delta.x * scroll_sensitivity))
5535                            / max_glyph_width;
5536                        let y = (current_scroll_position.y * line_height
5537                            - (delta.y * scroll_sensitivity))
5538                            / line_height;
5539                        let mut scroll_position =
5540                            point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
5541                        let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
5542                        if forbid_vertical_scroll {
5543                            scroll_position.y = current_scroll_position.y;
5544                        }
5545
5546                        if scroll_position != current_scroll_position {
5547                            editor.scroll(scroll_position, axis, window, cx);
5548                            cx.stop_propagation();
5549                        } else if y < 0. {
5550                            // Due to clamping, we may fail to detect cases of overscroll to the top;
5551                            // We want the scroll manager to get an update in such cases and detect the change of direction
5552                            // on the next frame.
5553                            cx.notify();
5554                        }
5555                    });
5556                }
5557            }
5558        });
5559    }
5560
5561    fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
5562        self.paint_scroll_wheel_listener(layout, window, cx);
5563
5564        window.on_mouse_event({
5565            let position_map = layout.position_map.clone();
5566            let editor = self.editor.clone();
5567            let diff_hunk_range =
5568                layout
5569                    .display_hunks
5570                    .iter()
5571                    .find_map(|(hunk, hunk_hitbox)| match hunk {
5572                        DisplayDiffHunk::Folded { .. } => None,
5573                        DisplayDiffHunk::Unfolded {
5574                            multi_buffer_range, ..
5575                        } => {
5576                            if hunk_hitbox
5577                                .as_ref()
5578                                .map(|hitbox| hitbox.is_hovered(window))
5579                                .unwrap_or(false)
5580                            {
5581                                Some(multi_buffer_range.clone())
5582                            } else {
5583                                None
5584                            }
5585                        }
5586                    });
5587            let line_numbers = layout.line_numbers.clone();
5588
5589            move |event: &MouseDownEvent, phase, window, cx| {
5590                if phase == DispatchPhase::Bubble {
5591                    match event.button {
5592                        MouseButton::Left => editor.update(cx, |editor, cx| {
5593                            let pending_mouse_down = editor
5594                                .pending_mouse_down
5595                                .get_or_insert_with(Default::default)
5596                                .clone();
5597
5598                            *pending_mouse_down.borrow_mut() = Some(event.clone());
5599
5600                            Self::mouse_left_down(
5601                                editor,
5602                                event,
5603                                diff_hunk_range.clone(),
5604                                &position_map,
5605                                line_numbers.as_ref(),
5606                                window,
5607                                cx,
5608                            );
5609                        }),
5610                        MouseButton::Right => editor.update(cx, |editor, cx| {
5611                            Self::mouse_right_down(editor, event, &position_map, window, cx);
5612                        }),
5613                        MouseButton::Middle => editor.update(cx, |editor, cx| {
5614                            Self::mouse_middle_down(editor, event, &position_map, window, cx);
5615                        }),
5616                        _ => {}
5617                    };
5618                }
5619            }
5620        });
5621
5622        window.on_mouse_event({
5623            let editor = self.editor.clone();
5624            let position_map = layout.position_map.clone();
5625
5626            move |event: &MouseUpEvent, phase, window, cx| {
5627                if phase == DispatchPhase::Bubble {
5628                    editor.update(cx, |editor, cx| {
5629                        Self::mouse_up(editor, event, &position_map, window, cx)
5630                    });
5631                }
5632            }
5633        });
5634
5635        window.on_mouse_event({
5636            let editor = self.editor.clone();
5637            let position_map = layout.position_map.clone();
5638            let mut captured_mouse_down = None;
5639
5640            move |event: &MouseUpEvent, phase, window, cx| match phase {
5641                // Clear the pending mouse down during the capture phase,
5642                // so that it happens even if another event handler stops
5643                // propagation.
5644                DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
5645                    let pending_mouse_down = editor
5646                        .pending_mouse_down
5647                        .get_or_insert_with(Default::default)
5648                        .clone();
5649
5650                    let mut pending_mouse_down = pending_mouse_down.borrow_mut();
5651                    if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
5652                        captured_mouse_down = pending_mouse_down.take();
5653                        window.refresh();
5654                    }
5655                }),
5656                // Fire click handlers during the bubble phase.
5657                DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
5658                    if let Some(mouse_down) = captured_mouse_down.take() {
5659                        let event = ClickEvent {
5660                            down: mouse_down,
5661                            up: event.clone(),
5662                        };
5663                        Self::click(editor, &event, &position_map, window, cx);
5664                    }
5665                }),
5666            }
5667        });
5668
5669        window.on_mouse_event({
5670            let position_map = layout.position_map.clone();
5671            let editor = self.editor.clone();
5672
5673            move |event: &MouseMoveEvent, phase, window, cx| {
5674                if phase == DispatchPhase::Bubble {
5675                    editor.update(cx, |editor, cx| {
5676                        if editor.hover_state.focused(window, cx) {
5677                            return;
5678                        }
5679                        if event.pressed_button == Some(MouseButton::Left)
5680                            || event.pressed_button == Some(MouseButton::Middle)
5681                        {
5682                            Self::mouse_dragged(editor, event, &position_map, window, cx)
5683                        }
5684
5685                        Self::mouse_moved(editor, event, &position_map, window, cx)
5686                    });
5687                }
5688            }
5689        });
5690    }
5691
5692    fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
5693        bounds.top_right().x - self.style.scrollbar_width
5694    }
5695
5696    fn column_pixels(&self, column: usize, window: &mut Window, _: &mut App) -> Pixels {
5697        let style = &self.style;
5698        let font_size = style.text.font_size.to_pixels(window.rem_size());
5699        let layout = window
5700            .text_system()
5701            .shape_line(
5702                SharedString::from(" ".repeat(column)),
5703                font_size,
5704                &[TextRun {
5705                    len: column,
5706                    font: style.text.font(),
5707                    color: Hsla::default(),
5708                    background_color: None,
5709                    underline: None,
5710                    strikethrough: None,
5711                }],
5712            )
5713            .unwrap();
5714
5715        layout.width
5716    }
5717
5718    fn max_line_number_width(
5719        &self,
5720        snapshot: &EditorSnapshot,
5721        window: &mut Window,
5722        cx: &mut App,
5723    ) -> Pixels {
5724        let digit_count = snapshot.widest_line_number().ilog10() + 1;
5725        self.column_pixels(digit_count as usize, window, cx)
5726    }
5727
5728    fn shape_line_number(
5729        &self,
5730        text: SharedString,
5731        color: Hsla,
5732        window: &mut Window,
5733    ) -> anyhow::Result<ShapedLine> {
5734        let run = TextRun {
5735            len: text.len(),
5736            font: self.style.text.font(),
5737            color,
5738            background_color: None,
5739            underline: None,
5740            strikethrough: None,
5741        };
5742        window.text_system().shape_line(
5743            text,
5744            self.style.text.font_size.to_pixels(window.rem_size()),
5745            &[run],
5746        )
5747    }
5748
5749    fn diff_hunk_hollow(status: DiffHunkStatus, cx: &mut App) -> bool {
5750        let unstaged = status.has_secondary_hunk();
5751        let unstaged_hollow = ProjectSettings::get_global(cx)
5752            .git
5753            .hunk_style
5754            .map_or(false, |style| {
5755                matches!(style, GitHunkStyleSetting::UnstagedHollow)
5756            });
5757
5758        unstaged == unstaged_hollow
5759    }
5760}
5761
5762fn header_jump_data(
5763    snapshot: &EditorSnapshot,
5764    block_row_start: DisplayRow,
5765    height: u32,
5766    for_excerpt: &ExcerptInfo,
5767) -> JumpData {
5768    let range = &for_excerpt.range;
5769    let buffer = &for_excerpt.buffer;
5770    let jump_anchor = range
5771        .primary
5772        .as_ref()
5773        .map_or(range.context.start, |primary| primary.start);
5774
5775    let excerpt_start = range.context.start;
5776    let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
5777    let rows_from_excerpt_start = if jump_anchor == excerpt_start {
5778        0
5779    } else {
5780        let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
5781        jump_position.row.saturating_sub(excerpt_start_point.row)
5782    };
5783
5784    let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
5785        .saturating_sub(
5786            snapshot
5787                .scroll_anchor
5788                .scroll_position(&snapshot.display_snapshot)
5789                .y as u32,
5790        );
5791
5792    JumpData::MultiBufferPoint {
5793        excerpt_id: for_excerpt.id,
5794        anchor: jump_anchor,
5795        position: jump_position,
5796        line_offset_from_top,
5797    }
5798}
5799
5800pub struct AcceptEditPredictionBinding(pub(crate) Option<gpui::KeyBinding>);
5801
5802impl AcceptEditPredictionBinding {
5803    pub fn keystroke(&self) -> Option<&Keystroke> {
5804        if let Some(binding) = self.0.as_ref() {
5805            match &binding.keystrokes() {
5806                [keystroke] => Some(keystroke),
5807                _ => None,
5808            }
5809        } else {
5810            None
5811        }
5812    }
5813}
5814
5815fn prepaint_gutter_button(
5816    button: IconButton,
5817    row: DisplayRow,
5818    line_height: Pixels,
5819    gutter_dimensions: &GutterDimensions,
5820    scroll_pixel_position: gpui::Point<Pixels>,
5821    gutter_hitbox: &Hitbox,
5822    display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
5823    window: &mut Window,
5824    cx: &mut App,
5825) -> AnyElement {
5826    let mut button = button.into_any_element();
5827
5828    let available_space = size(
5829        AvailableSpace::MinContent,
5830        AvailableSpace::Definite(line_height),
5831    );
5832    let indicator_size = button.layout_as_root(available_space, window, cx);
5833
5834    let blame_width = gutter_dimensions.git_blame_entries_width;
5835    let gutter_width = display_hunks
5836        .binary_search_by(|(hunk, _)| match hunk {
5837            DisplayDiffHunk::Folded { display_row } => display_row.cmp(&row),
5838            DisplayDiffHunk::Unfolded {
5839                display_row_range, ..
5840            } => {
5841                if display_row_range.end <= row {
5842                    Ordering::Less
5843                } else if display_row_range.start > row {
5844                    Ordering::Greater
5845                } else {
5846                    Ordering::Equal
5847                }
5848            }
5849        })
5850        .ok()
5851        .and_then(|ix| Some(display_hunks[ix].1.as_ref()?.size.width));
5852    let left_offset = blame_width.max(gutter_width).unwrap_or_default();
5853
5854    let mut x = left_offset;
5855    let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
5856        - indicator_size.width
5857        - left_offset;
5858    x += available_width / 2.;
5859
5860    let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
5861    y += (line_height - indicator_size.height) / 2.;
5862
5863    button.prepaint_as_root(
5864        gutter_hitbox.origin + point(x, y),
5865        available_space,
5866        window,
5867        cx,
5868    );
5869    button
5870}
5871
5872fn render_inline_blame_entry(
5873    editor: Entity<Editor>,
5874    blame: &gpui::Entity<GitBlame>,
5875    blame_entry: BlameEntry,
5876    style: &EditorStyle,
5877    cx: &mut App,
5878) -> AnyElement {
5879    let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
5880
5881    let author = blame_entry.author.as_deref().unwrap_or_default();
5882    let summary_enabled = ProjectSettings::get_global(cx)
5883        .git
5884        .show_inline_commit_summary();
5885
5886    let text = match blame_entry.summary.as_ref() {
5887        Some(summary) if summary_enabled => {
5888            format!("{}, {} - {}", author, relative_timestamp, summary)
5889        }
5890        _ => format!("{}, {}", author, relative_timestamp),
5891    };
5892    let blame = blame.clone();
5893    let blame_entry = blame_entry.clone();
5894
5895    h_flex()
5896        .id("inline-blame")
5897        .w_full()
5898        .font_family(style.text.font().family)
5899        .text_color(cx.theme().status().hint)
5900        .line_height(style.text.line_height)
5901        .child(Icon::new(IconName::FileGit).color(Color::Hint))
5902        .child(text)
5903        .gap_2()
5904        .hoverable_tooltip(move |window, cx| {
5905            let details = blame.read(cx).details_for_entry(&blame_entry);
5906            let tooltip =
5907                cx.new(|cx| CommitTooltip::blame_entry(&blame_entry, details, window, cx));
5908            editor.update(cx, |editor, _| {
5909                editor.git_blame_inline_tooltip = Some(tooltip.downgrade())
5910            });
5911            tooltip.into()
5912        })
5913        .into_any()
5914}
5915
5916fn render_blame_entry(
5917    ix: usize,
5918    blame: &gpui::Entity<GitBlame>,
5919    blame_entry: BlameEntry,
5920    style: &EditorStyle,
5921    last_used_color: &mut Option<(PlayerColor, Oid)>,
5922    editor: Entity<Editor>,
5923    cx: &mut App,
5924) -> AnyElement {
5925    let mut sha_color = cx
5926        .theme()
5927        .players()
5928        .color_for_participant(blame_entry.sha.into());
5929    // If the last color we used is the same as the one we get for this line, but
5930    // the commit SHAs are different, then we try again to get a different color.
5931    match *last_used_color {
5932        Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
5933            let index: u32 = blame_entry.sha.into();
5934            sha_color = cx.theme().players().color_for_participant(index + 1);
5935        }
5936        _ => {}
5937    };
5938    last_used_color.replace((sha_color, blame_entry.sha));
5939
5940    let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
5941
5942    let short_commit_id = blame_entry.sha.display_short();
5943
5944    let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
5945    let name = util::truncate_and_trailoff(author_name, GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED);
5946    let details = blame.read(cx).details_for_entry(&blame_entry);
5947
5948    h_flex()
5949        .w_full()
5950        .justify_between()
5951        .font_family(style.text.font().family)
5952        .line_height(style.text.line_height)
5953        .id(("blame", ix))
5954        .text_color(cx.theme().status().hint)
5955        .pr_2()
5956        .gap_2()
5957        .child(
5958            h_flex()
5959                .items_center()
5960                .gap_2()
5961                .child(div().text_color(sha_color.cursor).child(short_commit_id))
5962                .child(name),
5963        )
5964        .child(relative_timestamp)
5965        .on_mouse_down(MouseButton::Right, {
5966            let blame_entry = blame_entry.clone();
5967            let details = details.clone();
5968            move |event, window, cx| {
5969                deploy_blame_entry_context_menu(
5970                    &blame_entry,
5971                    details.as_ref(),
5972                    editor.clone(),
5973                    event.position,
5974                    window,
5975                    cx,
5976                );
5977            }
5978        })
5979        .hover(|style| style.bg(cx.theme().colors().element_hover))
5980        .when_some(
5981            details
5982                .as_ref()
5983                .and_then(|details| details.permalink.clone()),
5984            |this, url| {
5985                this.cursor_pointer().on_click(move |_, _, cx| {
5986                    cx.stop_propagation();
5987                    cx.open_url(url.as_str())
5988                })
5989            },
5990        )
5991        .hoverable_tooltip(move |window, cx| {
5992            cx.new(|cx| CommitTooltip::blame_entry(&blame_entry, details.clone(), window, cx))
5993                .into()
5994        })
5995        .into_any()
5996}
5997
5998fn deploy_blame_entry_context_menu(
5999    blame_entry: &BlameEntry,
6000    details: Option<&ParsedCommitMessage>,
6001    editor: Entity<Editor>,
6002    position: gpui::Point<Pixels>,
6003    window: &mut Window,
6004    cx: &mut App,
6005) {
6006    let context_menu = ContextMenu::build(window, cx, move |menu, _, _| {
6007        let sha = format!("{}", blame_entry.sha);
6008        menu.on_blur_subscription(Subscription::new(|| {}))
6009            .entry("Copy commit SHA", None, move |_, cx| {
6010                cx.write_to_clipboard(ClipboardItem::new_string(sha.clone()));
6011            })
6012            .when_some(
6013                details.and_then(|details| details.permalink.clone()),
6014                |this, url| {
6015                    this.entry("Open permalink", None, move |_, cx| {
6016                        cx.open_url(url.as_str())
6017                    })
6018                },
6019            )
6020    });
6021
6022    editor.update(cx, move |editor, cx| {
6023        editor.mouse_context_menu = Some(MouseContextMenu::new(
6024            MenuPosition::PinnedToScreen(position),
6025            context_menu,
6026            window,
6027            cx,
6028        ));
6029        cx.notify();
6030    });
6031}
6032
6033#[derive(Debug)]
6034pub(crate) struct LineWithInvisibles {
6035    fragments: SmallVec<[LineFragment; 1]>,
6036    invisibles: Vec<Invisible>,
6037    len: usize,
6038    pub(crate) width: Pixels,
6039    font_size: Pixels,
6040}
6041
6042#[allow(clippy::large_enum_variant)]
6043enum LineFragment {
6044    Text(ShapedLine),
6045    Element {
6046        element: Option<AnyElement>,
6047        size: Size<Pixels>,
6048        len: usize,
6049    },
6050}
6051
6052impl fmt::Debug for LineFragment {
6053    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6054        match self {
6055            LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
6056            LineFragment::Element { size, len, .. } => f
6057                .debug_struct("Element")
6058                .field("size", size)
6059                .field("len", len)
6060                .finish(),
6061        }
6062    }
6063}
6064
6065impl LineWithInvisibles {
6066    fn from_chunks<'a>(
6067        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
6068        editor_style: &EditorStyle,
6069        max_line_len: usize,
6070        max_line_count: usize,
6071        editor_mode: EditorMode,
6072        text_width: Pixels,
6073        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
6074        window: &mut Window,
6075        cx: &mut App,
6076    ) -> Vec<Self> {
6077        let text_style = &editor_style.text;
6078        let mut layouts = Vec::with_capacity(max_line_count);
6079        let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
6080        let mut line = String::new();
6081        let mut invisibles = Vec::new();
6082        let mut width = Pixels::ZERO;
6083        let mut len = 0;
6084        let mut styles = Vec::new();
6085        let mut non_whitespace_added = false;
6086        let mut row = 0;
6087        let mut line_exceeded_max_len = false;
6088        let font_size = text_style.font_size.to_pixels(window.rem_size());
6089
6090        let ellipsis = SharedString::from("");
6091
6092        for highlighted_chunk in chunks.chain([HighlightedChunk {
6093            text: "\n",
6094            style: None,
6095            is_tab: false,
6096            replacement: None,
6097        }]) {
6098            if let Some(replacement) = highlighted_chunk.replacement {
6099                if !line.is_empty() {
6100                    let shaped_line = window
6101                        .text_system()
6102                        .shape_line(line.clone().into(), font_size, &styles)
6103                        .unwrap();
6104                    width += shaped_line.width;
6105                    len += shaped_line.len;
6106                    fragments.push(LineFragment::Text(shaped_line));
6107                    line.clear();
6108                    styles.clear();
6109                }
6110
6111                match replacement {
6112                    ChunkReplacement::Renderer(renderer) => {
6113                        let available_width = if renderer.constrain_width {
6114                            let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
6115                                ellipsis.clone()
6116                            } else {
6117                                SharedString::from(Arc::from(highlighted_chunk.text))
6118                            };
6119                            let shaped_line = window
6120                                .text_system()
6121                                .shape_line(
6122                                    chunk,
6123                                    font_size,
6124                                    &[text_style.to_run(highlighted_chunk.text.len())],
6125                                )
6126                                .unwrap();
6127                            AvailableSpace::Definite(shaped_line.width)
6128                        } else {
6129                            AvailableSpace::MinContent
6130                        };
6131
6132                        let mut element = (renderer.render)(&mut ChunkRendererContext {
6133                            context: cx,
6134                            window,
6135                            max_width: text_width,
6136                        });
6137                        let line_height = text_style.line_height_in_pixels(window.rem_size());
6138                        let size = element.layout_as_root(
6139                            size(available_width, AvailableSpace::Definite(line_height)),
6140                            window,
6141                            cx,
6142                        );
6143
6144                        width += size.width;
6145                        len += highlighted_chunk.text.len();
6146                        fragments.push(LineFragment::Element {
6147                            element: Some(element),
6148                            size,
6149                            len: highlighted_chunk.text.len(),
6150                        });
6151                    }
6152                    ChunkReplacement::Str(x) => {
6153                        let text_style = if let Some(style) = highlighted_chunk.style {
6154                            Cow::Owned(text_style.clone().highlight(style))
6155                        } else {
6156                            Cow::Borrowed(text_style)
6157                        };
6158
6159                        let run = TextRun {
6160                            len: x.len(),
6161                            font: text_style.font(),
6162                            color: text_style.color,
6163                            background_color: text_style.background_color,
6164                            underline: text_style.underline,
6165                            strikethrough: text_style.strikethrough,
6166                        };
6167                        let line_layout = window
6168                            .text_system()
6169                            .shape_line(x, font_size, &[run])
6170                            .unwrap()
6171                            .with_len(highlighted_chunk.text.len());
6172
6173                        width += line_layout.width;
6174                        len += highlighted_chunk.text.len();
6175                        fragments.push(LineFragment::Text(line_layout))
6176                    }
6177                }
6178            } else {
6179                for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
6180                    if ix > 0 {
6181                        let shaped_line = window
6182                            .text_system()
6183                            .shape_line(line.clone().into(), font_size, &styles)
6184                            .unwrap();
6185                        width += shaped_line.width;
6186                        len += shaped_line.len;
6187                        fragments.push(LineFragment::Text(shaped_line));
6188                        layouts.push(Self {
6189                            width: mem::take(&mut width),
6190                            len: mem::take(&mut len),
6191                            fragments: mem::take(&mut fragments),
6192                            invisibles: std::mem::take(&mut invisibles),
6193                            font_size,
6194                        });
6195
6196                        line.clear();
6197                        styles.clear();
6198                        row += 1;
6199                        line_exceeded_max_len = false;
6200                        non_whitespace_added = false;
6201                        if row == max_line_count {
6202                            return layouts;
6203                        }
6204                    }
6205
6206                    if !line_chunk.is_empty() && !line_exceeded_max_len {
6207                        let text_style = if let Some(style) = highlighted_chunk.style {
6208                            Cow::Owned(text_style.clone().highlight(style))
6209                        } else {
6210                            Cow::Borrowed(text_style)
6211                        };
6212
6213                        if line.len() + line_chunk.len() > max_line_len {
6214                            let mut chunk_len = max_line_len - line.len();
6215                            while !line_chunk.is_char_boundary(chunk_len) {
6216                                chunk_len -= 1;
6217                            }
6218                            line_chunk = &line_chunk[..chunk_len];
6219                            line_exceeded_max_len = true;
6220                        }
6221
6222                        styles.push(TextRun {
6223                            len: line_chunk.len(),
6224                            font: text_style.font(),
6225                            color: text_style.color,
6226                            background_color: text_style.background_color,
6227                            underline: text_style.underline,
6228                            strikethrough: text_style.strikethrough,
6229                        });
6230
6231                        if editor_mode == EditorMode::Full {
6232                            // Line wrap pads its contents with fake whitespaces,
6233                            // avoid printing them
6234                            let is_soft_wrapped = is_row_soft_wrapped(row);
6235                            if highlighted_chunk.is_tab {
6236                                if non_whitespace_added || !is_soft_wrapped {
6237                                    invisibles.push(Invisible::Tab {
6238                                        line_start_offset: line.len(),
6239                                        line_end_offset: line.len() + line_chunk.len(),
6240                                    });
6241                                }
6242                            } else {
6243                                invisibles.extend(line_chunk.char_indices().filter_map(
6244                                    |(index, c)| {
6245                                        let is_whitespace = c.is_whitespace();
6246                                        non_whitespace_added |= !is_whitespace;
6247                                        if is_whitespace
6248                                            && (non_whitespace_added || !is_soft_wrapped)
6249                                        {
6250                                            Some(Invisible::Whitespace {
6251                                                line_offset: line.len() + index,
6252                                            })
6253                                        } else {
6254                                            None
6255                                        }
6256                                    },
6257                                ))
6258                            }
6259                        }
6260
6261                        line.push_str(line_chunk);
6262                    }
6263                }
6264            }
6265        }
6266
6267        layouts
6268    }
6269
6270    fn prepaint(
6271        &mut self,
6272        line_height: Pixels,
6273        scroll_pixel_position: gpui::Point<Pixels>,
6274        row: DisplayRow,
6275        content_origin: gpui::Point<Pixels>,
6276        line_elements: &mut SmallVec<[AnyElement; 1]>,
6277        window: &mut Window,
6278        cx: &mut App,
6279    ) {
6280        let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
6281        let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
6282        for fragment in &mut self.fragments {
6283            match fragment {
6284                LineFragment::Text(line) => {
6285                    fragment_origin.x += line.width;
6286                }
6287                LineFragment::Element { element, size, .. } => {
6288                    let mut element = element
6289                        .take()
6290                        .expect("you can't prepaint LineWithInvisibles twice");
6291
6292                    // Center the element vertically within the line.
6293                    let mut element_origin = fragment_origin;
6294                    element_origin.y += (line_height - size.height) / 2.;
6295                    element.prepaint_at(element_origin, window, cx);
6296                    line_elements.push(element);
6297
6298                    fragment_origin.x += size.width;
6299                }
6300            }
6301        }
6302    }
6303
6304    fn draw(
6305        &self,
6306        layout: &EditorLayout,
6307        row: DisplayRow,
6308        content_origin: gpui::Point<Pixels>,
6309        whitespace_setting: ShowWhitespaceSetting,
6310        selection_ranges: &[Range<DisplayPoint>],
6311        window: &mut Window,
6312        cx: &mut App,
6313    ) {
6314        let line_height = layout.position_map.line_height;
6315        let line_y = line_height
6316            * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
6317
6318        let mut fragment_origin =
6319            content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
6320
6321        for fragment in &self.fragments {
6322            match fragment {
6323                LineFragment::Text(line) => {
6324                    line.paint(fragment_origin, line_height, window, cx)
6325                        .log_err();
6326                    fragment_origin.x += line.width;
6327                }
6328                LineFragment::Element { size, .. } => {
6329                    fragment_origin.x += size.width;
6330                }
6331            }
6332        }
6333
6334        self.draw_invisibles(
6335            selection_ranges,
6336            layout,
6337            content_origin,
6338            line_y,
6339            row,
6340            line_height,
6341            whitespace_setting,
6342            window,
6343            cx,
6344        );
6345    }
6346
6347    fn draw_background(
6348        &self,
6349        layout: &EditorLayout,
6350        row: DisplayRow,
6351        content_origin: gpui::Point<Pixels>,
6352        window: &mut Window,
6353        cx: &mut App,
6354    ) {
6355        let line_height = layout.position_map.line_height;
6356        let line_y = line_height
6357            * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
6358
6359        let mut fragment_origin =
6360            content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
6361
6362        for fragment in &self.fragments {
6363            match fragment {
6364                LineFragment::Text(line) => {
6365                    line.paint_background(fragment_origin, line_height, window, cx)
6366                        .log_err();
6367                    fragment_origin.x += line.width;
6368                }
6369                LineFragment::Element { size, .. } => {
6370                    fragment_origin.x += size.width;
6371                }
6372            }
6373        }
6374    }
6375
6376    fn draw_invisibles(
6377        &self,
6378        selection_ranges: &[Range<DisplayPoint>],
6379        layout: &EditorLayout,
6380        content_origin: gpui::Point<Pixels>,
6381        line_y: Pixels,
6382        row: DisplayRow,
6383        line_height: Pixels,
6384        whitespace_setting: ShowWhitespaceSetting,
6385        window: &mut Window,
6386        cx: &mut App,
6387    ) {
6388        let extract_whitespace_info = |invisible: &Invisible| {
6389            let (token_offset, token_end_offset, invisible_symbol) = match invisible {
6390                Invisible::Tab {
6391                    line_start_offset,
6392                    line_end_offset,
6393                } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
6394                Invisible::Whitespace { line_offset } => {
6395                    (*line_offset, line_offset + 1, &layout.space_invisible)
6396                }
6397            };
6398
6399            let x_offset = self.x_for_index(token_offset);
6400            let invisible_offset =
6401                (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
6402            let origin = content_origin
6403                + gpui::point(
6404                    x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
6405                    line_y,
6406                );
6407
6408            (
6409                [token_offset, token_end_offset],
6410                Box::new(move |window: &mut Window, cx: &mut App| {
6411                    invisible_symbol
6412                        .paint(origin, line_height, window, cx)
6413                        .log_err();
6414                }),
6415            )
6416        };
6417
6418        let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
6419        match whitespace_setting {
6420            ShowWhitespaceSetting::None => (),
6421            ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
6422            ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
6423                let invisible_point = DisplayPoint::new(row, start as u32);
6424                if !selection_ranges
6425                    .iter()
6426                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
6427                {
6428                    return;
6429                }
6430
6431                paint(window, cx);
6432            }),
6433
6434            // For a whitespace to be on a boundary, any of the following conditions need to be met:
6435            // - It is a tab
6436            // - It is adjacent to an edge (start or end)
6437            // - It is adjacent to a whitespace (left or right)
6438            ShowWhitespaceSetting::Boundary => {
6439                // 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
6440                // the above cases.
6441                // Note: We zip in the original `invisibles` to check for tab equality
6442                let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
6443                for (([start, end], paint), invisible) in
6444                    invisible_iter.zip_eq(self.invisibles.iter())
6445                {
6446                    let should_render = match (&last_seen, invisible) {
6447                        (_, Invisible::Tab { .. }) => true,
6448                        (Some((_, last_end, _)), _) => *last_end == start,
6449                        _ => false,
6450                    };
6451
6452                    if should_render || start == 0 || end == self.len {
6453                        paint(window, cx);
6454
6455                        // Since we are scanning from the left, we will skip over the first available whitespace that is part
6456                        // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
6457                        if let Some((should_render_last, last_end, paint_last)) = last_seen {
6458                            // Note that we need to make sure that the last one is actually adjacent
6459                            if !should_render_last && last_end == start {
6460                                paint_last(window, cx);
6461                            }
6462                        }
6463                    }
6464
6465                    // Manually render anything within a selection
6466                    let invisible_point = DisplayPoint::new(row, start as u32);
6467                    if selection_ranges.iter().any(|region| {
6468                        region.start <= invisible_point && invisible_point < region.end
6469                    }) {
6470                        paint(window, cx);
6471                    }
6472
6473                    last_seen = Some((should_render, end, paint));
6474                }
6475            }
6476        }
6477    }
6478
6479    pub fn x_for_index(&self, index: usize) -> Pixels {
6480        let mut fragment_start_x = Pixels::ZERO;
6481        let mut fragment_start_index = 0;
6482
6483        for fragment in &self.fragments {
6484            match fragment {
6485                LineFragment::Text(shaped_line) => {
6486                    let fragment_end_index = fragment_start_index + shaped_line.len;
6487                    if index < fragment_end_index {
6488                        return fragment_start_x
6489                            + shaped_line.x_for_index(index - fragment_start_index);
6490                    }
6491                    fragment_start_x += shaped_line.width;
6492                    fragment_start_index = fragment_end_index;
6493                }
6494                LineFragment::Element { len, size, .. } => {
6495                    let fragment_end_index = fragment_start_index + len;
6496                    if index < fragment_end_index {
6497                        return fragment_start_x;
6498                    }
6499                    fragment_start_x += size.width;
6500                    fragment_start_index = fragment_end_index;
6501                }
6502            }
6503        }
6504
6505        fragment_start_x
6506    }
6507
6508    pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
6509        let mut fragment_start_x = Pixels::ZERO;
6510        let mut fragment_start_index = 0;
6511
6512        for fragment in &self.fragments {
6513            match fragment {
6514                LineFragment::Text(shaped_line) => {
6515                    let fragment_end_x = fragment_start_x + shaped_line.width;
6516                    if x < fragment_end_x {
6517                        return Some(
6518                            fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
6519                        );
6520                    }
6521                    fragment_start_x = fragment_end_x;
6522                    fragment_start_index += shaped_line.len;
6523                }
6524                LineFragment::Element { len, size, .. } => {
6525                    let fragment_end_x = fragment_start_x + size.width;
6526                    if x < fragment_end_x {
6527                        return Some(fragment_start_index);
6528                    }
6529                    fragment_start_index += len;
6530                    fragment_start_x = fragment_end_x;
6531                }
6532            }
6533        }
6534
6535        None
6536    }
6537
6538    pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
6539        let mut fragment_start_index = 0;
6540
6541        for fragment in &self.fragments {
6542            match fragment {
6543                LineFragment::Text(shaped_line) => {
6544                    let fragment_end_index = fragment_start_index + shaped_line.len;
6545                    if index < fragment_end_index {
6546                        return shaped_line.font_id_for_index(index - fragment_start_index);
6547                    }
6548                    fragment_start_index = fragment_end_index;
6549                }
6550                LineFragment::Element { len, .. } => {
6551                    let fragment_end_index = fragment_start_index + len;
6552                    if index < fragment_end_index {
6553                        return None;
6554                    }
6555                    fragment_start_index = fragment_end_index;
6556                }
6557            }
6558        }
6559
6560        None
6561    }
6562}
6563
6564#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6565enum Invisible {
6566    /// A tab character
6567    ///
6568    /// A tab character is internally represented by spaces (configured by the user's tab width)
6569    /// aligned to the nearest column, so it's necessary to store the start and end offset for
6570    /// adjacency checks.
6571    Tab {
6572        line_start_offset: usize,
6573        line_end_offset: usize,
6574    },
6575    Whitespace {
6576        line_offset: usize,
6577    },
6578}
6579
6580impl EditorElement {
6581    /// Returns the rem size to use when rendering the [`EditorElement`].
6582    ///
6583    /// This allows UI elements to scale based on the `buffer_font_size`.
6584    fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
6585        match self.editor.read(cx).mode {
6586            EditorMode::Full => {
6587                let buffer_font_size = self.style.text.font_size;
6588                match buffer_font_size {
6589                    AbsoluteLength::Pixels(pixels) => {
6590                        let rem_size_scale = {
6591                            // Our default UI font size is 14px on a 16px base scale.
6592                            // This means the default UI font size is 0.875rems.
6593                            let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
6594
6595                            // We then determine the delta between a single rem and the default font
6596                            // size scale.
6597                            let default_font_size_delta = 1. - default_font_size_scale;
6598
6599                            // Finally, we add this delta to 1rem to get the scale factor that
6600                            // should be used to scale up the UI.
6601                            1. + default_font_size_delta
6602                        };
6603
6604                        Some(pixels * rem_size_scale)
6605                    }
6606                    AbsoluteLength::Rems(rems) => {
6607                        Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
6608                    }
6609                }
6610            }
6611            // We currently use single-line and auto-height editors in UI contexts,
6612            // so we don't want to scale everything with the buffer font size, as it
6613            // ends up looking off.
6614            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => None,
6615        }
6616    }
6617}
6618
6619impl Element for EditorElement {
6620    type RequestLayoutState = ();
6621    type PrepaintState = EditorLayout;
6622
6623    fn id(&self) -> Option<ElementId> {
6624        None
6625    }
6626
6627    fn request_layout(
6628        &mut self,
6629        _: Option<&GlobalElementId>,
6630        window: &mut Window,
6631        cx: &mut App,
6632    ) -> (gpui::LayoutId, ()) {
6633        let rem_size = self.rem_size(cx);
6634        window.with_rem_size(rem_size, |window| {
6635            self.editor.update(cx, |editor, cx| {
6636                editor.set_style(self.style.clone(), window, cx);
6637
6638                let layout_id = match editor.mode {
6639                    EditorMode::SingleLine { auto_width } => {
6640                        let rem_size = window.rem_size();
6641
6642                        let height = self.style.text.line_height_in_pixels(rem_size);
6643                        if auto_width {
6644                            let editor_handle = cx.entity().clone();
6645                            let style = self.style.clone();
6646                            window.request_measured_layout(
6647                                Style::default(),
6648                                move |_, _, window, cx| {
6649                                    let editor_snapshot = editor_handle
6650                                        .update(cx, |editor, cx| editor.snapshot(window, cx));
6651                                    let line = Self::layout_lines(
6652                                        DisplayRow(0)..DisplayRow(1),
6653                                        &editor_snapshot,
6654                                        &style,
6655                                        px(f32::MAX),
6656                                        |_| false, // Single lines never soft wrap
6657                                        window,
6658                                        cx,
6659                                    )
6660                                    .pop()
6661                                    .unwrap();
6662
6663                                    let font_id =
6664                                        window.text_system().resolve_font(&style.text.font());
6665                                    let font_size =
6666                                        style.text.font_size.to_pixels(window.rem_size());
6667                                    let em_width =
6668                                        window.text_system().em_width(font_id, font_size).unwrap();
6669
6670                                    size(line.width + em_width, height)
6671                                },
6672                            )
6673                        } else {
6674                            let mut style = Style::default();
6675                            style.size.height = height.into();
6676                            style.size.width = relative(1.).into();
6677                            window.request_layout(style, None, cx)
6678                        }
6679                    }
6680                    EditorMode::AutoHeight { max_lines } => {
6681                        let editor_handle = cx.entity().clone();
6682                        let max_line_number_width =
6683                            self.max_line_number_width(&editor.snapshot(window, cx), window, cx);
6684                        window.request_measured_layout(
6685                            Style::default(),
6686                            move |known_dimensions, available_space, window, cx| {
6687                                editor_handle
6688                                    .update(cx, |editor, cx| {
6689                                        compute_auto_height_layout(
6690                                            editor,
6691                                            max_lines,
6692                                            max_line_number_width,
6693                                            known_dimensions,
6694                                            available_space.width,
6695                                            window,
6696                                            cx,
6697                                        )
6698                                    })
6699                                    .unwrap_or_default()
6700                            },
6701                        )
6702                    }
6703                    EditorMode::Full => {
6704                        let mut style = Style::default();
6705                        style.size.width = relative(1.).into();
6706                        style.size.height = relative(1.).into();
6707                        window.request_layout(style, None, cx)
6708                    }
6709                };
6710
6711                (layout_id, ())
6712            })
6713        })
6714    }
6715
6716    fn prepaint(
6717        &mut self,
6718        _: Option<&GlobalElementId>,
6719        bounds: Bounds<Pixels>,
6720        _: &mut Self::RequestLayoutState,
6721        window: &mut Window,
6722        cx: &mut App,
6723    ) -> Self::PrepaintState {
6724        let text_style = TextStyleRefinement {
6725            font_size: Some(self.style.text.font_size),
6726            line_height: Some(self.style.text.line_height),
6727            ..Default::default()
6728        };
6729        let focus_handle = self.editor.focus_handle(cx);
6730        window.set_view_id(self.editor.entity_id());
6731        window.set_focus_handle(&focus_handle, cx);
6732
6733        let rem_size = self.rem_size(cx);
6734        window.with_rem_size(rem_size, |window| {
6735            window.with_text_style(Some(text_style), |window| {
6736                window.with_content_mask(Some(ContentMask { bounds }), |window| {
6737                    let mut snapshot = self
6738                        .editor
6739                        .update(cx, |editor, cx| editor.snapshot(window, cx));
6740                    let style = self.style.clone();
6741
6742                    let font_id = window.text_system().resolve_font(&style.text.font());
6743                    let font_size = style.text.font_size.to_pixels(window.rem_size());
6744                    let line_height = style.text.line_height_in_pixels(window.rem_size());
6745                    let em_width = window.text_system().em_width(font_id, font_size).unwrap();
6746                    let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
6747
6748                    let letter_size = size(em_width, line_height);
6749
6750                    let gutter_dimensions = snapshot
6751                        .gutter_dimensions(
6752                            font_id,
6753                            font_size,
6754                            self.max_line_number_width(&snapshot, window, cx),
6755                            cx,
6756                        )
6757                        .unwrap_or_default();
6758                    let text_width = bounds.size.width - gutter_dimensions.width;
6759
6760                    let editor_width =
6761                        text_width - gutter_dimensions.margin - em_width - style.scrollbar_width;
6762
6763                    snapshot = self.editor.update(cx, |editor, cx| {
6764                        editor.last_bounds = Some(bounds);
6765                        editor.gutter_dimensions = gutter_dimensions;
6766                        editor.set_visible_line_count(bounds.size.height / line_height, window, cx);
6767
6768                        if matches!(editor.mode, EditorMode::AutoHeight { .. }) {
6769                            snapshot
6770                        } else {
6771                            let wrap_width = match editor.soft_wrap_mode(cx) {
6772                                SoftWrap::GitDiff => None,
6773                                SoftWrap::None => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
6774                                SoftWrap::EditorWidth => Some(editor_width),
6775                                SoftWrap::Column(column) => Some(column as f32 * em_advance),
6776                                SoftWrap::Bounded(column) => {
6777                                    Some(editor_width.min(column as f32 * em_advance))
6778                                }
6779                            };
6780
6781                            if editor.set_wrap_width(wrap_width, cx) {
6782                                editor.snapshot(window, cx)
6783                            } else {
6784                                snapshot
6785                            }
6786                        }
6787                    });
6788
6789                    let wrap_guides = self
6790                        .editor
6791                        .read(cx)
6792                        .wrap_guides(cx)
6793                        .iter()
6794                        .map(|(guide, active)| (self.column_pixels(*guide, window, cx), *active))
6795                        .collect::<SmallVec<[_; 2]>>();
6796
6797                    let hitbox = window.insert_hitbox(bounds, false);
6798                    let gutter_hitbox =
6799                        window.insert_hitbox(gutter_bounds(bounds, gutter_dimensions), false);
6800                    let text_hitbox = window.insert_hitbox(
6801                        Bounds {
6802                            origin: gutter_hitbox.top_right(),
6803                            size: size(text_width, bounds.size.height),
6804                        },
6805                        false,
6806                    );
6807                    // Offset the content_bounds from the text_bounds by the gutter margin (which
6808                    // is roughly half a character wide) to make hit testing work more like how we want.
6809                    let content_origin =
6810                        text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
6811
6812                    let scrollbar_bounds =
6813                        Bounds::from_corners(content_origin, bounds.bottom_right());
6814
6815                    let height_in_lines = scrollbar_bounds.size.height / line_height;
6816
6817                    // NOTE: The max row number in the current file, minus one
6818                    let max_row = snapshot.max_point().row().as_f32();
6819
6820                    // NOTE: The max scroll position for the top of the window
6821                    let max_scroll_top = if matches!(snapshot.mode, EditorMode::AutoHeight { .. }) {
6822                        (max_row - height_in_lines + 1.).max(0.)
6823                    } else {
6824                        let settings = EditorSettings::get_global(cx);
6825                        match settings.scroll_beyond_last_line {
6826                            ScrollBeyondLastLine::OnePage => max_row,
6827                            ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
6828                            ScrollBeyondLastLine::VerticalScrollMargin => {
6829                                (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
6830                                    .max(0.)
6831                            }
6832                        }
6833                    };
6834
6835                    // TODO: Autoscrolling for both axes
6836                    let mut autoscroll_request = None;
6837                    let mut autoscroll_containing_element = false;
6838                    let mut autoscroll_horizontally = false;
6839                    self.editor.update(cx, |editor, cx| {
6840                        autoscroll_request = editor.autoscroll_request();
6841                        autoscroll_containing_element =
6842                            autoscroll_request.is_some() || editor.has_pending_selection();
6843                        // TODO: Is this horizontal or vertical?!
6844                        autoscroll_horizontally = editor.autoscroll_vertically(
6845                            bounds,
6846                            line_height,
6847                            max_scroll_top,
6848                            window,
6849                            cx,
6850                        );
6851                        snapshot = editor.snapshot(window, cx);
6852                    });
6853
6854                    let mut scroll_position = snapshot.scroll_position();
6855                    // The scroll position is a fractional point, the whole number of which represents
6856                    // the top of the window in terms of display rows.
6857                    let start_row = DisplayRow(scroll_position.y as u32);
6858                    let max_row = snapshot.max_point().row();
6859                    let end_row = cmp::min(
6860                        (scroll_position.y + height_in_lines).ceil() as u32,
6861                        max_row.next_row().0,
6862                    );
6863                    let end_row = DisplayRow(end_row);
6864
6865                    let row_infos = snapshot
6866                        .row_infos(start_row)
6867                        .take((start_row..end_row).len())
6868                        .collect::<Vec<RowInfo>>();
6869                    let is_row_soft_wrapped = |row: usize| {
6870                        row_infos
6871                            .get(row)
6872                            .map_or(true, |info| info.buffer_row.is_none())
6873                    };
6874
6875                    let start_anchor = if start_row == Default::default() {
6876                        Anchor::min()
6877                    } else {
6878                        snapshot.buffer_snapshot.anchor_before(
6879                            DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
6880                        )
6881                    };
6882                    let end_anchor = if end_row > max_row {
6883                        Anchor::max()
6884                    } else {
6885                        snapshot.buffer_snapshot.anchor_before(
6886                            DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
6887                        )
6888                    };
6889
6890                    let mut highlighted_rows = self
6891                        .editor
6892                        .update(cx, |editor, cx| editor.highlighted_display_rows(window, cx));
6893
6894                    let is_light = cx.theme().appearance().is_light();
6895
6896                    for (ix, row_info) in row_infos.iter().enumerate() {
6897                        let Some(diff_status) = row_info.diff_status else {
6898                            continue;
6899                        };
6900
6901                        let background_color = match diff_status.kind {
6902                            DiffHunkStatusKind::Added => cx.theme().colors().version_control_added,
6903                            DiffHunkStatusKind::Deleted => {
6904                                cx.theme().colors().version_control_deleted
6905                            }
6906                            DiffHunkStatusKind::Modified => {
6907                                debug_panic!("modified diff status for row info");
6908                                continue;
6909                            }
6910                        };
6911
6912                        let hunk_opacity = if is_light { 0.16 } else { 0.12 };
6913
6914                        let hollow_highlight = LineHighlight {
6915                            background: (background_color.opacity(if is_light {
6916                                0.08
6917                            } else {
6918                                0.06
6919                            }))
6920                            .into(),
6921                            border: Some(if is_light {
6922                                background_color.opacity(0.48)
6923                            } else {
6924                                background_color.opacity(0.36)
6925                            }),
6926                        };
6927
6928                        let filled_highlight =
6929                            solid_background(background_color.opacity(hunk_opacity)).into();
6930
6931                        let background = if Self::diff_hunk_hollow(diff_status, cx) {
6932                            hollow_highlight
6933                        } else {
6934                            filled_highlight
6935                        };
6936
6937                        highlighted_rows
6938                            .entry(start_row + DisplayRow(ix as u32))
6939                            .or_insert(background);
6940                    }
6941
6942                    let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
6943                        start_anchor..end_anchor,
6944                        &snapshot.display_snapshot,
6945                        cx.theme().colors(),
6946                    );
6947                    let highlighted_gutter_ranges =
6948                        self.editor.read(cx).gutter_highlights_in_range(
6949                            start_anchor..end_anchor,
6950                            &snapshot.display_snapshot,
6951                            cx,
6952                        );
6953
6954                    let redacted_ranges = self.editor.read(cx).redacted_ranges(
6955                        start_anchor..end_anchor,
6956                        &snapshot.display_snapshot,
6957                        cx,
6958                    );
6959
6960                    let (local_selections, selected_buffer_ids): (
6961                        Vec<Selection<Point>>,
6962                        Vec<BufferId>,
6963                    ) = self.editor.update(cx, |editor, cx| {
6964                        let all_selections = editor.selections.all::<Point>(cx);
6965                        let selected_buffer_ids = if editor.is_singleton(cx) {
6966                            Vec::new()
6967                        } else {
6968                            let mut selected_buffer_ids = Vec::with_capacity(all_selections.len());
6969
6970                            for selection in all_selections {
6971                                for buffer_id in snapshot
6972                                    .buffer_snapshot
6973                                    .buffer_ids_for_range(selection.range())
6974                                {
6975                                    if selected_buffer_ids.last() != Some(&buffer_id) {
6976                                        selected_buffer_ids.push(buffer_id);
6977                                    }
6978                                }
6979                            }
6980
6981                            selected_buffer_ids
6982                        };
6983
6984                        let mut selections = editor
6985                            .selections
6986                            .disjoint_in_range(start_anchor..end_anchor, cx);
6987                        selections.extend(editor.selections.pending(cx));
6988
6989                        (selections, selected_buffer_ids)
6990                    });
6991
6992                    let (selections, mut active_rows, newest_selection_head) = self
6993                        .layout_selections(
6994                            start_anchor,
6995                            end_anchor,
6996                            &local_selections,
6997                            &snapshot,
6998                            start_row,
6999                            end_row,
7000                            window,
7001                            cx,
7002                        );
7003                    let mut breakpoint_rows = self.editor.update(cx, |editor, cx| {
7004                        editor.active_breakpoints(start_row..end_row, window, cx)
7005                    });
7006                    if cx.has_flag::<Debugger>() {
7007                        for display_row in breakpoint_rows.keys() {
7008                            active_rows.entry(*display_row).or_default().breakpoint = true;
7009                        }
7010                    }
7011
7012                    let line_numbers = self.layout_line_numbers(
7013                        Some(&gutter_hitbox),
7014                        gutter_dimensions,
7015                        line_height,
7016                        scroll_position,
7017                        start_row..end_row,
7018                        &row_infos,
7019                        &active_rows,
7020                        newest_selection_head,
7021                        &snapshot,
7022                        window,
7023                        cx,
7024                    );
7025
7026                    // We add the gutter breakpoint indicator to breakpoint_rows after painting
7027                    // line numbers so we don't paint a line number debug accent color if a user
7028                    // has their mouse over that line when a breakpoint isn't there
7029                    if cx.has_flag::<Debugger>() {
7030                        let gutter_breakpoint_indicator =
7031                            self.editor.read(cx).gutter_breakpoint_indicator;
7032                        if let Some(gutter_breakpoint_point) = gutter_breakpoint_indicator {
7033                            breakpoint_rows
7034                                .entry(gutter_breakpoint_point.row())
7035                                .or_insert_with(|| {
7036                                    let position = snapshot.display_point_to_anchor(
7037                                        gutter_breakpoint_point,
7038                                        Bias::Left,
7039                                    );
7040                                    let breakpoint = Breakpoint {
7041                                        kind: BreakpointKind::Standard,
7042                                    };
7043
7044                                    (position, breakpoint)
7045                                });
7046                        }
7047                    }
7048
7049                    let mut expand_toggles =
7050                        window.with_element_namespace("expand_toggles", |window| {
7051                            self.layout_expand_toggles(
7052                                &gutter_hitbox,
7053                                gutter_dimensions,
7054                                em_width,
7055                                line_height,
7056                                scroll_position,
7057                                &row_infos,
7058                                window,
7059                                cx,
7060                            )
7061                        });
7062
7063                    let mut crease_toggles =
7064                        window.with_element_namespace("crease_toggles", |window| {
7065                            self.layout_crease_toggles(
7066                                start_row..end_row,
7067                                &row_infos,
7068                                &active_rows,
7069                                &snapshot,
7070                                window,
7071                                cx,
7072                            )
7073                        });
7074                    let crease_trailers =
7075                        window.with_element_namespace("crease_trailers", |window| {
7076                            self.layout_crease_trailers(
7077                                row_infos.iter().copied(),
7078                                &snapshot,
7079                                window,
7080                                cx,
7081                            )
7082                        });
7083
7084                    let display_hunks = self.layout_gutter_diff_hunks(
7085                        line_height,
7086                        &gutter_hitbox,
7087                        start_row..end_row,
7088                        &snapshot,
7089                        window,
7090                        cx,
7091                    );
7092
7093                    let mut line_layouts = Self::layout_lines(
7094                        start_row..end_row,
7095                        &snapshot,
7096                        &self.style,
7097                        editor_width,
7098                        is_row_soft_wrapped,
7099                        window,
7100                        cx,
7101                    );
7102
7103                    let longest_line_blame_width = self
7104                        .editor
7105                        .update(cx, |editor, cx| {
7106                            if !editor.show_git_blame_inline {
7107                                return None;
7108                            }
7109                            let blame = editor.blame.as_ref()?;
7110                            let blame_entry = blame
7111                                .update(cx, |blame, cx| {
7112                                    let row_infos =
7113                                        snapshot.row_infos(snapshot.longest_row()).next()?;
7114                                    blame.blame_for_rows(&[row_infos], cx).next()
7115                                })
7116                                .flatten()?;
7117                            let mut element = render_inline_blame_entry(
7118                                self.editor.clone(),
7119                                blame,
7120                                blame_entry,
7121                                &style,
7122                                cx,
7123                            );
7124                            let inline_blame_padding = INLINE_BLAME_PADDING_EM_WIDTHS * em_advance;
7125                            Some(
7126                                element
7127                                    .layout_as_root(AvailableSpace::min_size(), window, cx)
7128                                    .width
7129                                    + inline_blame_padding,
7130                            )
7131                        })
7132                        .unwrap_or(Pixels::ZERO);
7133
7134                    let longest_line_width = layout_line(
7135                        snapshot.longest_row(),
7136                        &snapshot,
7137                        &style,
7138                        editor_width,
7139                        is_row_soft_wrapped,
7140                        window,
7141                        cx,
7142                    )
7143                    .width;
7144
7145                    let scrollbar_range_data = ScrollbarRangeData::new(
7146                        scrollbar_bounds,
7147                        letter_size,
7148                        &snapshot,
7149                        longest_line_width,
7150                        longest_line_blame_width,
7151                        &style,
7152                        editor_width,
7153                        cx,
7154                    );
7155
7156                    let scroll_range_bounds = scrollbar_range_data.scroll_range;
7157                    let mut scroll_width = scroll_range_bounds.size.width;
7158
7159                    let sticky_header_excerpt = if snapshot.buffer_snapshot.show_headers() {
7160                        snapshot.sticky_header_excerpt(scroll_position.y)
7161                    } else {
7162                        None
7163                    };
7164                    let sticky_header_excerpt_id =
7165                        sticky_header_excerpt.as_ref().map(|top| top.excerpt.id);
7166
7167                    let blocks = window.with_element_namespace("blocks", |window| {
7168                        self.render_blocks(
7169                            start_row..end_row,
7170                            &snapshot,
7171                            &hitbox,
7172                            &text_hitbox,
7173                            editor_width,
7174                            &mut scroll_width,
7175                            &gutter_dimensions,
7176                            em_width,
7177                            gutter_dimensions.full_width(),
7178                            line_height,
7179                            &line_layouts,
7180                            &local_selections,
7181                            &selected_buffer_ids,
7182                            is_row_soft_wrapped,
7183                            sticky_header_excerpt_id,
7184                            window,
7185                            cx,
7186                        )
7187                    });
7188                    let mut blocks = match blocks {
7189                        Ok(blocks) => blocks,
7190                        Err(resized_blocks) => {
7191                            self.editor.update(cx, |editor, cx| {
7192                                editor.resize_blocks(resized_blocks, autoscroll_request, cx)
7193                            });
7194                            return self.prepaint(None, bounds, &mut (), window, cx);
7195                        }
7196                    };
7197
7198                    let sticky_buffer_header = sticky_header_excerpt.map(|sticky_header_excerpt| {
7199                        window.with_element_namespace("blocks", |window| {
7200                            self.layout_sticky_buffer_header(
7201                                sticky_header_excerpt,
7202                                scroll_position.y,
7203                                line_height,
7204                                &snapshot,
7205                                &hitbox,
7206                                &selected_buffer_ids,
7207                                &blocks,
7208                                window,
7209                                cx,
7210                            )
7211                        })
7212                    });
7213
7214                    let start_buffer_row =
7215                        MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
7216                    let end_buffer_row =
7217                        MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
7218
7219                    let scroll_max = point(
7220                        ((scroll_width - scrollbar_bounds.size.width) / em_width).max(0.0),
7221                        max_row.as_f32(),
7222                    );
7223
7224                    self.editor.update(cx, |editor, cx| {
7225                        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
7226
7227                        let autoscrolled = if autoscroll_horizontally {
7228                            editor.autoscroll_horizontally(
7229                                start_row,
7230                                editor_width - (letter_size.width / 2.0) + style.scrollbar_width,
7231                                scroll_width,
7232                                em_width,
7233                                &line_layouts,
7234                                cx,
7235                            )
7236                        } else {
7237                            false
7238                        };
7239
7240                        if clamped || autoscrolled {
7241                            snapshot = editor.snapshot(window, cx);
7242                            scroll_position = snapshot.scroll_position();
7243                        }
7244                    });
7245
7246                    let scroll_pixel_position = point(
7247                        scroll_position.x * em_width,
7248                        scroll_position.y * line_height,
7249                    );
7250
7251                    let indent_guides = self.layout_indent_guides(
7252                        content_origin,
7253                        text_hitbox.origin,
7254                        start_buffer_row..end_buffer_row,
7255                        scroll_pixel_position,
7256                        line_height,
7257                        &snapshot,
7258                        window,
7259                        cx,
7260                    );
7261
7262                    let crease_trailers =
7263                        window.with_element_namespace("crease_trailers", |window| {
7264                            self.prepaint_crease_trailers(
7265                                crease_trailers,
7266                                &line_layouts,
7267                                line_height,
7268                                content_origin,
7269                                scroll_pixel_position,
7270                                em_width,
7271                                window,
7272                                cx,
7273                            )
7274                        });
7275
7276                    let (inline_completion_popover, inline_completion_popover_origin) = self
7277                        .editor
7278                        .update(cx, |editor, cx| {
7279                            editor.render_edit_prediction_popover(
7280                                &text_hitbox.bounds,
7281                                content_origin,
7282                                &snapshot,
7283                                start_row..end_row,
7284                                scroll_position.y,
7285                                scroll_position.y + height_in_lines,
7286                                &line_layouts,
7287                                line_height,
7288                                scroll_pixel_position,
7289                                newest_selection_head,
7290                                editor_width,
7291                                &style,
7292                                window,
7293                                cx,
7294                            )
7295                        })
7296                        .unzip();
7297
7298                    let mut inline_diagnostics = self.layout_inline_diagnostics(
7299                        &line_layouts,
7300                        &crease_trailers,
7301                        content_origin,
7302                        scroll_pixel_position,
7303                        inline_completion_popover_origin,
7304                        start_row,
7305                        end_row,
7306                        line_height,
7307                        em_width,
7308                        &style,
7309                        window,
7310                        cx,
7311                    );
7312
7313                    let mut inline_blame = None;
7314                    if let Some(newest_selection_head) = newest_selection_head {
7315                        let display_row = newest_selection_head.row();
7316                        if (start_row..end_row).contains(&display_row) {
7317                            let line_ix = display_row.minus(start_row) as usize;
7318                            let row_info = &row_infos[line_ix];
7319                            let line_layout = &line_layouts[line_ix];
7320                            let crease_trailer_layout = crease_trailers[line_ix].as_ref();
7321                            inline_blame = self.layout_inline_blame(
7322                                display_row,
7323                                row_info,
7324                                line_layout,
7325                                crease_trailer_layout,
7326                                em_width,
7327                                content_origin,
7328                                scroll_pixel_position,
7329                                line_height,
7330                                window,
7331                                cx,
7332                            );
7333                            if inline_blame.is_some() {
7334                                // Blame overrides inline diagnostics
7335                                inline_diagnostics.remove(&display_row);
7336                            }
7337                        }
7338                    }
7339
7340                    let blamed_display_rows = self.layout_blame_entries(
7341                        &row_infos,
7342                        em_width,
7343                        scroll_position,
7344                        line_height,
7345                        &gutter_hitbox,
7346                        gutter_dimensions.git_blame_entries_width,
7347                        window,
7348                        cx,
7349                    );
7350
7351                    let scroll_max = point(
7352                        ((scroll_width - scrollbar_bounds.size.width) / em_width).max(0.0),
7353                        max_scroll_top,
7354                    );
7355
7356                    self.editor.update(cx, |editor, cx| {
7357                        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
7358
7359                        let autoscrolled = if autoscroll_horizontally {
7360                            editor.autoscroll_horizontally(
7361                                start_row,
7362                                editor_width - (letter_size.width / 2.0) + style.scrollbar_width,
7363                                scroll_width,
7364                                em_width,
7365                                &line_layouts,
7366                                cx,
7367                            )
7368                        } else {
7369                            false
7370                        };
7371
7372                        if clamped || autoscrolled {
7373                            snapshot = editor.snapshot(window, cx);
7374                            scroll_position = snapshot.scroll_position();
7375                        }
7376                    });
7377
7378                    let line_elements = self.prepaint_lines(
7379                        start_row,
7380                        &mut line_layouts,
7381                        line_height,
7382                        scroll_pixel_position,
7383                        content_origin,
7384                        window,
7385                        cx,
7386                    );
7387
7388                    let mut block_start_rows = HashSet::default();
7389
7390                    window.with_element_namespace("blocks", |window| {
7391                        self.layout_blocks(
7392                            &mut blocks,
7393                            &mut block_start_rows,
7394                            &hitbox,
7395                            line_height,
7396                            scroll_pixel_position,
7397                            window,
7398                            cx,
7399                        );
7400                    });
7401
7402                    let cursors = self.collect_cursors(&snapshot, cx);
7403                    let visible_row_range = start_row..end_row;
7404                    let non_visible_cursors = cursors
7405                        .iter()
7406                        .any(|c| !visible_row_range.contains(&c.0.row()));
7407
7408                    let visible_cursors = self.layout_visible_cursors(
7409                        &snapshot,
7410                        &selections,
7411                        &block_start_rows,
7412                        start_row..end_row,
7413                        &line_layouts,
7414                        &text_hitbox,
7415                        content_origin,
7416                        scroll_position,
7417                        scroll_pixel_position,
7418                        line_height,
7419                        em_width,
7420                        em_advance,
7421                        autoscroll_containing_element,
7422                        window,
7423                        cx,
7424                    );
7425
7426                    let scrollbars_layout = self.layout_scrollbars(
7427                        &snapshot,
7428                        scrollbar_range_data,
7429                        scroll_position,
7430                        non_visible_cursors,
7431                        window,
7432                        cx,
7433                    );
7434
7435                    let gutter_settings = EditorSettings::get_global(cx).gutter;
7436
7437                    let mut code_actions_indicator = None;
7438                    if let Some(newest_selection_head) = newest_selection_head {
7439                        let newest_selection_point =
7440                            newest_selection_head.to_point(&snapshot.display_snapshot);
7441
7442                        if (start_row..end_row).contains(&newest_selection_head.row()) {
7443                            self.layout_cursor_popovers(
7444                                line_height,
7445                                &text_hitbox,
7446                                content_origin,
7447                                start_row,
7448                                scroll_pixel_position,
7449                                &line_layouts,
7450                                newest_selection_head,
7451                                newest_selection_point,
7452                                &style,
7453                                window,
7454                                cx,
7455                            );
7456
7457                            let show_code_actions = snapshot
7458                                .show_code_actions
7459                                .unwrap_or(gutter_settings.code_actions);
7460                            if show_code_actions {
7461                                let newest_selection_point =
7462                                    newest_selection_head.to_point(&snapshot.display_snapshot);
7463                                if !snapshot
7464                                    .is_line_folded(MultiBufferRow(newest_selection_point.row))
7465                                {
7466                                    let buffer = snapshot.buffer_snapshot.buffer_line_for_row(
7467                                        MultiBufferRow(newest_selection_point.row),
7468                                    );
7469                                    if let Some((buffer, range)) = buffer {
7470                                        let buffer_id = buffer.remote_id();
7471                                        let row = range.start.row;
7472                                        let has_test_indicator = self
7473                                            .editor
7474                                            .read(cx)
7475                                            .tasks
7476                                            .contains_key(&(buffer_id, row));
7477
7478                                        let has_expand_indicator = row_infos
7479                                            .get(
7480                                                (newest_selection_head.row() - start_row).0
7481                                                    as usize,
7482                                            )
7483                                            .is_some_and(|row_info| row_info.expand_info.is_some());
7484
7485                                        if !has_test_indicator && !has_expand_indicator {
7486                                            code_actions_indicator = self
7487                                                .layout_code_actions_indicator(
7488                                                    line_height,
7489                                                    newest_selection_head,
7490                                                    scroll_pixel_position,
7491                                                    &gutter_dimensions,
7492                                                    &gutter_hitbox,
7493                                                    &mut breakpoint_rows,
7494                                                    &display_hunks,
7495                                                    window,
7496                                                    cx,
7497                                                );
7498                                        }
7499                                    }
7500                                }
7501                            }
7502                        }
7503                    }
7504
7505                    self.layout_gutter_menu(
7506                        line_height,
7507                        &text_hitbox,
7508                        content_origin,
7509                        scroll_pixel_position,
7510                        gutter_dimensions.width - gutter_dimensions.left_padding,
7511                        window,
7512                        cx,
7513                    );
7514
7515                    let test_indicators = if gutter_settings.runnables {
7516                        self.layout_run_indicators(
7517                            line_height,
7518                            start_row..end_row,
7519                            &row_infos,
7520                            scroll_pixel_position,
7521                            &gutter_dimensions,
7522                            &gutter_hitbox,
7523                            &display_hunks,
7524                            &snapshot,
7525                            &mut breakpoint_rows,
7526                            window,
7527                            cx,
7528                        )
7529                    } else {
7530                        Vec::new()
7531                    };
7532
7533                    let show_breakpoints = snapshot
7534                        .show_breakpoints
7535                        .unwrap_or(gutter_settings.breakpoints);
7536                    let breakpoints = if cx.has_flag::<Debugger>() && show_breakpoints {
7537                        self.layout_breakpoints(
7538                            line_height,
7539                            start_row..end_row,
7540                            scroll_pixel_position,
7541                            &gutter_dimensions,
7542                            &gutter_hitbox,
7543                            &display_hunks,
7544                            &snapshot,
7545                            breakpoint_rows,
7546                            &row_infos,
7547                            window,
7548                            cx,
7549                        )
7550                    } else {
7551                        vec![]
7552                    };
7553
7554                    self.layout_signature_help(
7555                        &hitbox,
7556                        content_origin,
7557                        scroll_pixel_position,
7558                        newest_selection_head,
7559                        start_row,
7560                        &line_layouts,
7561                        line_height,
7562                        em_width,
7563                        window,
7564                        cx,
7565                    );
7566
7567                    if !cx.has_active_drag() {
7568                        self.layout_hover_popovers(
7569                            &snapshot,
7570                            &hitbox,
7571                            &text_hitbox,
7572                            start_row..end_row,
7573                            content_origin,
7574                            scroll_pixel_position,
7575                            &line_layouts,
7576                            line_height,
7577                            em_width,
7578                            window,
7579                            cx,
7580                        );
7581                    }
7582
7583                    let mouse_context_menu = self.layout_mouse_context_menu(
7584                        &snapshot,
7585                        start_row..end_row,
7586                        content_origin,
7587                        window,
7588                        cx,
7589                    );
7590
7591                    window.with_element_namespace("crease_toggles", |window| {
7592                        self.prepaint_crease_toggles(
7593                            &mut crease_toggles,
7594                            line_height,
7595                            &gutter_dimensions,
7596                            gutter_settings,
7597                            scroll_pixel_position,
7598                            &gutter_hitbox,
7599                            window,
7600                            cx,
7601                        )
7602                    });
7603
7604                    window.with_element_namespace("expand_toggles", |window| {
7605                        self.prepaint_expand_toggles(&mut expand_toggles, window, cx)
7606                    });
7607
7608                    let invisible_symbol_font_size = font_size / 2.;
7609                    let tab_invisible = window
7610                        .text_system()
7611                        .shape_line(
7612                            "".into(),
7613                            invisible_symbol_font_size,
7614                            &[TextRun {
7615                                len: "".len(),
7616                                font: self.style.text.font(),
7617                                color: cx.theme().colors().editor_invisible,
7618                                background_color: None,
7619                                underline: None,
7620                                strikethrough: None,
7621                            }],
7622                        )
7623                        .unwrap();
7624                    let space_invisible = window
7625                        .text_system()
7626                        .shape_line(
7627                            "".into(),
7628                            invisible_symbol_font_size,
7629                            &[TextRun {
7630                                len: "".len(),
7631                                font: self.style.text.font(),
7632                                color: cx.theme().colors().editor_invisible,
7633                                background_color: None,
7634                                underline: None,
7635                                strikethrough: None,
7636                            }],
7637                        )
7638                        .unwrap();
7639
7640                    let mode = snapshot.mode;
7641
7642                    let position_map = Rc::new(PositionMap {
7643                        size: bounds.size,
7644                        visible_row_range,
7645                        scroll_pixel_position,
7646                        scroll_max,
7647                        line_layouts,
7648                        line_height,
7649                        em_width,
7650                        em_advance,
7651                        snapshot,
7652                        gutter_hitbox: gutter_hitbox.clone(),
7653                        text_hitbox: text_hitbox.clone(),
7654                    });
7655
7656                    self.editor.update(cx, |editor, _| {
7657                        editor.last_position_map = Some(position_map.clone())
7658                    });
7659
7660                    let diff_hunk_controls = self.layout_diff_hunk_controls(
7661                        start_row..end_row,
7662                        &row_infos,
7663                        &text_hitbox,
7664                        &position_map,
7665                        newest_selection_head,
7666                        line_height,
7667                        scroll_pixel_position,
7668                        &display_hunks,
7669                        self.editor.clone(),
7670                        window,
7671                        cx,
7672                    );
7673
7674                    EditorLayout {
7675                        mode,
7676                        position_map,
7677                        visible_display_row_range: start_row..end_row,
7678                        wrap_guides,
7679                        indent_guides,
7680                        hitbox,
7681                        gutter_hitbox,
7682                        display_hunks,
7683                        content_origin,
7684                        scrollbars_layout,
7685                        active_rows,
7686                        highlighted_rows,
7687                        highlighted_ranges,
7688                        highlighted_gutter_ranges,
7689                        redacted_ranges,
7690                        line_elements,
7691                        line_numbers,
7692                        blamed_display_rows,
7693                        inline_diagnostics,
7694                        inline_blame,
7695                        blocks,
7696                        cursors,
7697                        visible_cursors,
7698                        selections,
7699                        inline_completion_popover,
7700                        diff_hunk_controls,
7701                        mouse_context_menu,
7702                        test_indicators,
7703                        breakpoints,
7704                        code_actions_indicator,
7705                        crease_toggles,
7706                        crease_trailers,
7707                        tab_invisible,
7708                        space_invisible,
7709                        sticky_buffer_header,
7710                        expand_toggles,
7711                    }
7712                })
7713            })
7714        })
7715    }
7716
7717    fn paint(
7718        &mut self,
7719        _: Option<&GlobalElementId>,
7720        bounds: Bounds<gpui::Pixels>,
7721        _: &mut Self::RequestLayoutState,
7722        layout: &mut Self::PrepaintState,
7723        window: &mut Window,
7724        cx: &mut App,
7725    ) {
7726        let focus_handle = self.editor.focus_handle(cx);
7727        let key_context = self
7728            .editor
7729            .update(cx, |editor, cx| editor.key_context(window, cx));
7730
7731        window.set_key_context(key_context);
7732        window.handle_input(
7733            &focus_handle,
7734            ElementInputHandler::new(bounds, self.editor.clone()),
7735            cx,
7736        );
7737        self.register_actions(window, cx);
7738        self.register_key_listeners(window, cx, layout);
7739
7740        let text_style = TextStyleRefinement {
7741            font_size: Some(self.style.text.font_size),
7742            line_height: Some(self.style.text.line_height),
7743            ..Default::default()
7744        };
7745        let rem_size = self.rem_size(cx);
7746        window.with_rem_size(rem_size, |window| {
7747            window.with_text_style(Some(text_style), |window| {
7748                window.with_content_mask(Some(ContentMask { bounds }), |window| {
7749                    self.paint_mouse_listeners(layout, window, cx);
7750                    self.paint_background(layout, window, cx);
7751                    self.paint_indent_guides(layout, window, cx);
7752
7753                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
7754                        self.paint_blamed_display_rows(layout, window, cx);
7755                        self.paint_line_numbers(layout, window, cx);
7756                    }
7757
7758                    self.paint_text(layout, window, cx);
7759
7760                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
7761                        self.paint_gutter_highlights(layout, window, cx);
7762                        self.paint_gutter_indicators(layout, window, cx);
7763                    }
7764
7765                    if !layout.blocks.is_empty() {
7766                        window.with_element_namespace("blocks", |window| {
7767                            self.paint_blocks(layout, window, cx);
7768                        });
7769                    }
7770
7771                    window.with_element_namespace("blocks", |window| {
7772                        if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
7773                            sticky_header.paint(window, cx)
7774                        }
7775                    });
7776
7777                    self.paint_scrollbars(layout, window, cx);
7778                    self.paint_inline_completion_popover(layout, window, cx);
7779                    self.paint_mouse_context_menu(layout, window, cx);
7780                });
7781            })
7782        })
7783    }
7784}
7785
7786pub(super) fn gutter_bounds(
7787    editor_bounds: Bounds<Pixels>,
7788    gutter_dimensions: GutterDimensions,
7789) -> Bounds<Pixels> {
7790    Bounds {
7791        origin: editor_bounds.origin,
7792        size: size(gutter_dimensions.width, editor_bounds.size.height),
7793    }
7794}
7795
7796struct ScrollbarRangeData {
7797    scrollbar_bounds: Bounds<Pixels>,
7798    scroll_range: Bounds<Pixels>,
7799    letter_size: Size<Pixels>,
7800}
7801
7802impl ScrollbarRangeData {
7803    pub fn new(
7804        scrollbar_bounds: Bounds<Pixels>,
7805        letter_size: Size<Pixels>,
7806        snapshot: &EditorSnapshot,
7807        longest_line_width: Pixels,
7808        longest_line_blame_width: Pixels,
7809        style: &EditorStyle,
7810        editor_width: Pixels,
7811        cx: &mut App,
7812    ) -> ScrollbarRangeData {
7813        // TODO: Simplify this function down, it requires a lot of parameters
7814        let max_row = snapshot.max_point().row();
7815        let text_bounds_size = size(longest_line_width, max_row.0 as f32 * letter_size.height);
7816
7817        let settings = EditorSettings::get_global(cx);
7818        let scroll_beyond_last_line: Pixels = match settings.scroll_beyond_last_line {
7819            ScrollBeyondLastLine::OnePage => px(scrollbar_bounds.size.height / letter_size.height),
7820            ScrollBeyondLastLine::Off => px(1.),
7821            ScrollBeyondLastLine::VerticalScrollMargin => px(1.0 + settings.vertical_scroll_margin),
7822        };
7823
7824        let right_margin = if longest_line_width + longest_line_blame_width >= editor_width {
7825            letter_size.width + style.scrollbar_width
7826        } else {
7827            px(0.0)
7828        };
7829
7830        let overscroll = size(
7831            right_margin + longest_line_blame_width,
7832            letter_size.height * scroll_beyond_last_line,
7833        );
7834
7835        let scroll_range = Bounds {
7836            origin: scrollbar_bounds.origin,
7837            size: text_bounds_size + overscroll,
7838        };
7839
7840        ScrollbarRangeData {
7841            scrollbar_bounds,
7842            scroll_range,
7843            letter_size,
7844        }
7845    }
7846}
7847
7848impl IntoElement for EditorElement {
7849    type Element = Self;
7850
7851    fn into_element(self) -> Self::Element {
7852        self
7853    }
7854}
7855
7856pub struct EditorLayout {
7857    position_map: Rc<PositionMap>,
7858    hitbox: Hitbox,
7859    gutter_hitbox: Hitbox,
7860    content_origin: gpui::Point<Pixels>,
7861    scrollbars_layout: AxisPair<Option<ScrollbarLayout>>,
7862    mode: EditorMode,
7863    wrap_guides: SmallVec<[(Pixels, bool); 2]>,
7864    indent_guides: Option<Vec<IndentGuideLayout>>,
7865    visible_display_row_range: Range<DisplayRow>,
7866    active_rows: BTreeMap<DisplayRow, LineHighlightSpec>,
7867    highlighted_rows: BTreeMap<DisplayRow, LineHighlight>,
7868    line_elements: SmallVec<[AnyElement; 1]>,
7869    line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
7870    display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
7871    blamed_display_rows: Option<Vec<AnyElement>>,
7872    inline_diagnostics: HashMap<DisplayRow, AnyElement>,
7873    inline_blame: Option<AnyElement>,
7874    blocks: Vec<BlockLayout>,
7875    highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
7876    highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
7877    redacted_ranges: Vec<Range<DisplayPoint>>,
7878    cursors: Vec<(DisplayPoint, Hsla)>,
7879    visible_cursors: Vec<CursorLayout>,
7880    selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
7881    code_actions_indicator: Option<AnyElement>,
7882    test_indicators: Vec<AnyElement>,
7883    breakpoints: Vec<AnyElement>,
7884    crease_toggles: Vec<Option<AnyElement>>,
7885    expand_toggles: Vec<Option<(AnyElement, gpui::Point<Pixels>)>>,
7886    diff_hunk_controls: Vec<AnyElement>,
7887    crease_trailers: Vec<Option<CreaseTrailerLayout>>,
7888    inline_completion_popover: Option<AnyElement>,
7889    mouse_context_menu: Option<AnyElement>,
7890    tab_invisible: ShapedLine,
7891    space_invisible: ShapedLine,
7892    sticky_buffer_header: Option<AnyElement>,
7893}
7894
7895impl EditorLayout {
7896    fn line_end_overshoot(&self) -> Pixels {
7897        0.15 * self.position_map.line_height
7898    }
7899}
7900
7901struct LineNumberLayout {
7902    shaped_line: ShapedLine,
7903    hitbox: Option<Hitbox>,
7904}
7905
7906struct ColoredRange<T> {
7907    start: T,
7908    end: T,
7909    color: Hsla,
7910}
7911
7912#[derive(Clone)]
7913struct ScrollbarLayout {
7914    hitbox: Hitbox,
7915    visible_range: Range<f32>,
7916    visible: bool,
7917    text_unit_size: Pixels,
7918    thumb_size: Pixels,
7919    axis: Axis,
7920}
7921
7922impl ScrollbarLayout {
7923    const BORDER_WIDTH: Pixels = px(1.0);
7924    const LINE_MARKER_HEIGHT: Pixels = px(2.0);
7925    const MIN_MARKER_HEIGHT: Pixels = px(5.0);
7926    // const MIN_THUMB_HEIGHT: Pixels = px(20.0);
7927
7928    fn thumb_bounds(&self) -> Bounds<Pixels> {
7929        match self.axis {
7930            Axis::Vertical => {
7931                let thumb_top = self.y_for_row(self.visible_range.start);
7932                let thumb_bottom = thumb_top + self.thumb_size;
7933                Bounds::from_corners(
7934                    point(self.hitbox.left(), thumb_top),
7935                    point(self.hitbox.right(), thumb_bottom),
7936                )
7937            }
7938            Axis::Horizontal => {
7939                let thumb_left =
7940                    self.hitbox.left() + self.visible_range.start * self.text_unit_size;
7941                let thumb_right = thumb_left + self.thumb_size;
7942                Bounds::from_corners(
7943                    point(thumb_left, self.hitbox.top()),
7944                    point(thumb_right, self.hitbox.bottom()),
7945                )
7946            }
7947        }
7948    }
7949
7950    fn y_for_row(&self, row: f32) -> Pixels {
7951        self.hitbox.top() + row * self.text_unit_size
7952    }
7953
7954    fn marker_quads_for_ranges(
7955        &self,
7956        row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
7957        column: Option<usize>,
7958    ) -> Vec<PaintQuad> {
7959        struct MinMax {
7960            min: Pixels,
7961            max: Pixels,
7962        }
7963        let (x_range, height_limit) = if let Some(column) = column {
7964            let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
7965            let start = Self::BORDER_WIDTH + (column as f32 * column_width);
7966            let end = start + column_width;
7967            (
7968                Range { start, end },
7969                MinMax {
7970                    min: Self::MIN_MARKER_HEIGHT,
7971                    max: px(f32::MAX),
7972                },
7973            )
7974        } else {
7975            (
7976                Range {
7977                    start: Self::BORDER_WIDTH,
7978                    end: self.hitbox.size.width,
7979                },
7980                MinMax {
7981                    min: Self::LINE_MARKER_HEIGHT,
7982                    max: Self::LINE_MARKER_HEIGHT,
7983                },
7984            )
7985        };
7986
7987        let row_to_y = |row: DisplayRow| row.as_f32() * self.text_unit_size;
7988        let mut pixel_ranges = row_ranges
7989            .into_iter()
7990            .map(|range| {
7991                let start_y = row_to_y(range.start);
7992                let end_y = row_to_y(range.end)
7993                    + self
7994                        .text_unit_size
7995                        .max(height_limit.min)
7996                        .min(height_limit.max);
7997                ColoredRange {
7998                    start: start_y,
7999                    end: end_y,
8000                    color: range.color,
8001                }
8002            })
8003            .peekable();
8004
8005        let mut quads = Vec::new();
8006        while let Some(mut pixel_range) = pixel_ranges.next() {
8007            while let Some(next_pixel_range) = pixel_ranges.peek() {
8008                if pixel_range.end >= next_pixel_range.start - px(1.0)
8009                    && pixel_range.color == next_pixel_range.color
8010                {
8011                    pixel_range.end = next_pixel_range.end.max(pixel_range.end);
8012                    pixel_ranges.next();
8013                } else {
8014                    break;
8015                }
8016            }
8017
8018            let bounds = Bounds::from_corners(
8019                point(x_range.start, pixel_range.start),
8020                point(x_range.end, pixel_range.end),
8021            );
8022            quads.push(quad(
8023                bounds,
8024                Corners::default(),
8025                pixel_range.color,
8026                Edges::default(),
8027                Hsla::transparent_black(),
8028            ));
8029        }
8030
8031        quads
8032    }
8033}
8034
8035struct CreaseTrailerLayout {
8036    element: AnyElement,
8037    bounds: Bounds<Pixels>,
8038}
8039
8040pub(crate) struct PositionMap {
8041    pub size: Size<Pixels>,
8042    pub line_height: Pixels,
8043    pub scroll_pixel_position: gpui::Point<Pixels>,
8044    pub scroll_max: gpui::Point<f32>,
8045    pub em_width: Pixels,
8046    pub em_advance: Pixels,
8047    pub visible_row_range: Range<DisplayRow>,
8048    pub line_layouts: Vec<LineWithInvisibles>,
8049    pub snapshot: EditorSnapshot,
8050    pub text_hitbox: Hitbox,
8051    pub gutter_hitbox: Hitbox,
8052}
8053
8054#[derive(Debug, Copy, Clone)]
8055pub struct PointForPosition {
8056    pub previous_valid: DisplayPoint,
8057    pub next_valid: DisplayPoint,
8058    pub exact_unclipped: DisplayPoint,
8059    pub column_overshoot_after_line_end: u32,
8060}
8061
8062impl PointForPosition {
8063    pub fn as_valid(&self) -> Option<DisplayPoint> {
8064        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
8065            Some(self.previous_valid)
8066        } else {
8067            None
8068        }
8069    }
8070}
8071
8072impl PositionMap {
8073    pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
8074        let text_bounds = self.text_hitbox.bounds;
8075        let scroll_position = self.snapshot.scroll_position();
8076        let position = position - text_bounds.origin;
8077        let y = position.y.max(px(0.)).min(self.size.height);
8078        let x = position.x + (scroll_position.x * self.em_width);
8079        let row = ((y / self.line_height) + scroll_position.y) as u32;
8080
8081        let (column, x_overshoot_after_line_end) = if let Some(line) = self
8082            .line_layouts
8083            .get(row as usize - scroll_position.y as usize)
8084        {
8085            if let Some(ix) = line.index_for_x(x) {
8086                (ix as u32, px(0.))
8087            } else {
8088                (line.len as u32, px(0.).max(x - line.width))
8089            }
8090        } else {
8091            (0, x)
8092        };
8093
8094        let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
8095        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
8096        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
8097
8098        let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
8099        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
8100        PointForPosition {
8101            previous_valid,
8102            next_valid,
8103            exact_unclipped,
8104            column_overshoot_after_line_end,
8105        }
8106    }
8107}
8108
8109struct BlockLayout {
8110    id: BlockId,
8111    row: Option<DisplayRow>,
8112    element: AnyElement,
8113    available_space: Size<AvailableSpace>,
8114    style: BlockStyle,
8115    is_buffer_header: bool,
8116}
8117
8118pub fn layout_line(
8119    row: DisplayRow,
8120    snapshot: &EditorSnapshot,
8121    style: &EditorStyle,
8122    text_width: Pixels,
8123    is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
8124    window: &mut Window,
8125    cx: &mut App,
8126) -> LineWithInvisibles {
8127    let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
8128    LineWithInvisibles::from_chunks(
8129        chunks,
8130        &style,
8131        MAX_LINE_LEN,
8132        1,
8133        snapshot.mode,
8134        text_width,
8135        is_row_soft_wrapped,
8136        window,
8137        cx,
8138    )
8139    .pop()
8140    .unwrap()
8141}
8142
8143#[derive(Debug)]
8144pub struct IndentGuideLayout {
8145    origin: gpui::Point<Pixels>,
8146    length: Pixels,
8147    single_indent_width: Pixels,
8148    depth: u32,
8149    active: bool,
8150    settings: IndentGuideSettings,
8151}
8152
8153pub struct CursorLayout {
8154    origin: gpui::Point<Pixels>,
8155    block_width: Pixels,
8156    line_height: Pixels,
8157    color: Hsla,
8158    shape: CursorShape,
8159    block_text: Option<ShapedLine>,
8160    cursor_name: Option<AnyElement>,
8161}
8162
8163#[derive(Debug)]
8164pub struct CursorName {
8165    string: SharedString,
8166    color: Hsla,
8167    is_top_row: bool,
8168}
8169
8170impl CursorLayout {
8171    pub fn new(
8172        origin: gpui::Point<Pixels>,
8173        block_width: Pixels,
8174        line_height: Pixels,
8175        color: Hsla,
8176        shape: CursorShape,
8177        block_text: Option<ShapedLine>,
8178    ) -> CursorLayout {
8179        CursorLayout {
8180            origin,
8181            block_width,
8182            line_height,
8183            color,
8184            shape,
8185            block_text,
8186            cursor_name: None,
8187        }
8188    }
8189
8190    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
8191        Bounds {
8192            origin: self.origin + origin,
8193            size: size(self.block_width, self.line_height),
8194        }
8195    }
8196
8197    fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
8198        match self.shape {
8199            CursorShape::Bar => Bounds {
8200                origin: self.origin + origin,
8201                size: size(px(2.0), self.line_height),
8202            },
8203            CursorShape::Block | CursorShape::Hollow => Bounds {
8204                origin: self.origin + origin,
8205                size: size(self.block_width, self.line_height),
8206            },
8207            CursorShape::Underline => Bounds {
8208                origin: self.origin
8209                    + origin
8210                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
8211                size: size(self.block_width, px(2.0)),
8212            },
8213        }
8214    }
8215
8216    pub fn layout(
8217        &mut self,
8218        origin: gpui::Point<Pixels>,
8219        cursor_name: Option<CursorName>,
8220        window: &mut Window,
8221        cx: &mut App,
8222    ) {
8223        if let Some(cursor_name) = cursor_name {
8224            let bounds = self.bounds(origin);
8225            let text_size = self.line_height / 1.5;
8226
8227            let name_origin = if cursor_name.is_top_row {
8228                point(bounds.right() - px(1.), bounds.top())
8229            } else {
8230                match self.shape {
8231                    CursorShape::Bar => point(
8232                        bounds.right() - px(2.),
8233                        bounds.top() - text_size / 2. - px(1.),
8234                    ),
8235                    _ => point(
8236                        bounds.right() - px(1.),
8237                        bounds.top() - text_size / 2. - px(1.),
8238                    ),
8239                }
8240            };
8241            let mut name_element = div()
8242                .bg(self.color)
8243                .text_size(text_size)
8244                .px_0p5()
8245                .line_height(text_size + px(2.))
8246                .text_color(cursor_name.color)
8247                .child(cursor_name.string.clone())
8248                .into_any_element();
8249
8250            name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
8251
8252            self.cursor_name = Some(name_element);
8253        }
8254    }
8255
8256    pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
8257        let bounds = self.bounds(origin);
8258
8259        //Draw background or border quad
8260        let cursor = if matches!(self.shape, CursorShape::Hollow) {
8261            outline(bounds, self.color)
8262        } else {
8263            fill(bounds, self.color)
8264        };
8265
8266        if let Some(name) = &mut self.cursor_name {
8267            name.paint(window, cx);
8268        }
8269
8270        window.paint_quad(cursor);
8271
8272        if let Some(block_text) = &self.block_text {
8273            block_text
8274                .paint(self.origin + origin, self.line_height, window, cx)
8275                .log_err();
8276        }
8277    }
8278
8279    pub fn shape(&self) -> CursorShape {
8280        self.shape
8281    }
8282}
8283
8284#[derive(Debug)]
8285pub struct HighlightedRange {
8286    pub start_y: Pixels,
8287    pub line_height: Pixels,
8288    pub lines: Vec<HighlightedRangeLine>,
8289    pub color: Hsla,
8290    pub corner_radius: Pixels,
8291}
8292
8293#[derive(Debug)]
8294pub struct HighlightedRangeLine {
8295    pub start_x: Pixels,
8296    pub end_x: Pixels,
8297}
8298
8299impl HighlightedRange {
8300    pub fn paint(&self, bounds: Bounds<Pixels>, window: &mut Window) {
8301        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
8302            self.paint_lines(self.start_y, &self.lines[0..1], bounds, window);
8303            self.paint_lines(
8304                self.start_y + self.line_height,
8305                &self.lines[1..],
8306                bounds,
8307                window,
8308            );
8309        } else {
8310            self.paint_lines(self.start_y, &self.lines, bounds, window);
8311        }
8312    }
8313
8314    fn paint_lines(
8315        &self,
8316        start_y: Pixels,
8317        lines: &[HighlightedRangeLine],
8318        _bounds: Bounds<Pixels>,
8319        window: &mut Window,
8320    ) {
8321        if lines.is_empty() {
8322            return;
8323        }
8324
8325        let first_line = lines.first().unwrap();
8326        let last_line = lines.last().unwrap();
8327
8328        let first_top_left = point(first_line.start_x, start_y);
8329        let first_top_right = point(first_line.end_x, start_y);
8330
8331        let curve_height = point(Pixels::ZERO, self.corner_radius);
8332        let curve_width = |start_x: Pixels, end_x: Pixels| {
8333            let max = (end_x - start_x) / 2.;
8334            let width = if max < self.corner_radius {
8335                max
8336            } else {
8337                self.corner_radius
8338            };
8339
8340            point(width, Pixels::ZERO)
8341        };
8342
8343        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
8344        let mut builder = gpui::PathBuilder::fill();
8345        builder.move_to(first_top_right - top_curve_width);
8346        builder.curve_to(first_top_right + curve_height, first_top_right);
8347
8348        let mut iter = lines.iter().enumerate().peekable();
8349        while let Some((ix, line)) = iter.next() {
8350            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
8351
8352            if let Some((_, next_line)) = iter.peek() {
8353                let next_top_right = point(next_line.end_x, bottom_right.y);
8354
8355                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
8356                    Ordering::Equal => {
8357                        builder.line_to(bottom_right);
8358                    }
8359                    Ordering::Less => {
8360                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
8361                        builder.line_to(bottom_right - curve_height);
8362                        if self.corner_radius > Pixels::ZERO {
8363                            builder.curve_to(bottom_right - curve_width, bottom_right);
8364                        }
8365                        builder.line_to(next_top_right + curve_width);
8366                        if self.corner_radius > Pixels::ZERO {
8367                            builder.curve_to(next_top_right + curve_height, next_top_right);
8368                        }
8369                    }
8370                    Ordering::Greater => {
8371                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
8372                        builder.line_to(bottom_right - curve_height);
8373                        if self.corner_radius > Pixels::ZERO {
8374                            builder.curve_to(bottom_right + curve_width, bottom_right);
8375                        }
8376                        builder.line_to(next_top_right - curve_width);
8377                        if self.corner_radius > Pixels::ZERO {
8378                            builder.curve_to(next_top_right + curve_height, next_top_right);
8379                        }
8380                    }
8381                }
8382            } else {
8383                let curve_width = curve_width(line.start_x, line.end_x);
8384                builder.line_to(bottom_right - curve_height);
8385                if self.corner_radius > Pixels::ZERO {
8386                    builder.curve_to(bottom_right - curve_width, bottom_right);
8387                }
8388
8389                let bottom_left = point(line.start_x, bottom_right.y);
8390                builder.line_to(bottom_left + curve_width);
8391                if self.corner_radius > Pixels::ZERO {
8392                    builder.curve_to(bottom_left - curve_height, bottom_left);
8393                }
8394            }
8395        }
8396
8397        if first_line.start_x > last_line.start_x {
8398            let curve_width = curve_width(last_line.start_x, first_line.start_x);
8399            let second_top_left = point(last_line.start_x, start_y + self.line_height);
8400            builder.line_to(second_top_left + curve_height);
8401            if self.corner_radius > Pixels::ZERO {
8402                builder.curve_to(second_top_left + curve_width, second_top_left);
8403            }
8404            let first_bottom_left = point(first_line.start_x, second_top_left.y);
8405            builder.line_to(first_bottom_left - curve_width);
8406            if self.corner_radius > Pixels::ZERO {
8407                builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
8408            }
8409        }
8410
8411        builder.line_to(first_top_left + curve_height);
8412        if self.corner_radius > Pixels::ZERO {
8413            builder.curve_to(first_top_left + top_curve_width, first_top_left);
8414        }
8415        builder.line_to(first_top_right - top_curve_width);
8416
8417        if let Ok(path) = builder.build() {
8418            window.paint_path(path, self.color);
8419        }
8420    }
8421}
8422
8423enum CursorPopoverType {
8424    CodeContextMenu,
8425    EditPrediction,
8426}
8427
8428pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
8429    (delta.pow(1.5) / 100.0).into()
8430}
8431
8432fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
8433    (delta.pow(1.2) / 300.0).into()
8434}
8435
8436pub fn register_action<T: Action>(
8437    editor: &Entity<Editor>,
8438    window: &mut Window,
8439    listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
8440) {
8441    let editor = editor.clone();
8442    window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
8443        let action = action.downcast_ref().unwrap();
8444        if phase == DispatchPhase::Bubble {
8445            editor.update(cx, |editor, cx| {
8446                listener(editor, action, window, cx);
8447            })
8448        }
8449    })
8450}
8451
8452fn compute_auto_height_layout(
8453    editor: &mut Editor,
8454    max_lines: usize,
8455    max_line_number_width: Pixels,
8456    known_dimensions: Size<Option<Pixels>>,
8457    available_width: AvailableSpace,
8458    window: &mut Window,
8459    cx: &mut Context<Editor>,
8460) -> Option<Size<Pixels>> {
8461    let width = known_dimensions.width.or({
8462        if let AvailableSpace::Definite(available_width) = available_width {
8463            Some(available_width)
8464        } else {
8465            None
8466        }
8467    })?;
8468    if let Some(height) = known_dimensions.height {
8469        return Some(size(width, height));
8470    }
8471
8472    let style = editor.style.as_ref().unwrap();
8473    let font_id = window.text_system().resolve_font(&style.text.font());
8474    let font_size = style.text.font_size.to_pixels(window.rem_size());
8475    let line_height = style.text.line_height_in_pixels(window.rem_size());
8476    let em_width = window.text_system().em_width(font_id, font_size).unwrap();
8477
8478    let mut snapshot = editor.snapshot(window, cx);
8479    let gutter_dimensions = snapshot
8480        .gutter_dimensions(font_id, font_size, max_line_number_width, cx)
8481        .unwrap_or_default();
8482
8483    editor.gutter_dimensions = gutter_dimensions;
8484    let text_width = width - gutter_dimensions.width;
8485    let overscroll = size(em_width, px(0.));
8486
8487    let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
8488    if editor.set_wrap_width(Some(editor_width), cx) {
8489        snapshot = editor.snapshot(window, cx);
8490    }
8491
8492    let scroll_height = Pixels::from(snapshot.max_point().row().next_row().0) * line_height;
8493    let height = scroll_height
8494        .max(line_height)
8495        .min(line_height * max_lines as f32);
8496
8497    Some(size(width, height))
8498}
8499
8500#[cfg(test)]
8501mod tests {
8502    use super::*;
8503    use crate::{
8504        display_map::{BlockPlacement, BlockProperties},
8505        editor_tests::{init_test, update_test_language_settings},
8506        Editor, MultiBuffer,
8507    };
8508    use gpui::{TestAppContext, VisualTestContext};
8509    use language::language_settings;
8510    use log::info;
8511    use std::num::NonZeroU32;
8512    use util::test::sample_text;
8513
8514    #[gpui::test]
8515    fn test_shape_line_numbers(cx: &mut TestAppContext) {
8516        init_test(cx, |_| {});
8517        let window = cx.add_window(|window, cx| {
8518            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
8519            Editor::new(EditorMode::Full, buffer, None, window, cx)
8520        });
8521
8522        let editor = window.root(cx).unwrap();
8523        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
8524        let line_height = window
8525            .update(cx, |_, window, _| {
8526                style.text.line_height_in_pixels(window.rem_size())
8527            })
8528            .unwrap();
8529        let element = EditorElement::new(&editor, style);
8530        let snapshot = window
8531            .update(cx, |editor, window, cx| editor.snapshot(window, cx))
8532            .unwrap();
8533
8534        let layouts = cx
8535            .update_window(*window, |_, window, cx| {
8536                element.layout_line_numbers(
8537                    None,
8538                    GutterDimensions {
8539                        left_padding: Pixels::ZERO,
8540                        right_padding: Pixels::ZERO,
8541                        width: px(30.0),
8542                        margin: Pixels::ZERO,
8543                        git_blame_entries_width: None,
8544                    },
8545                    line_height,
8546                    gpui::Point::default(),
8547                    DisplayRow(0)..DisplayRow(6),
8548                    &(0..6)
8549                        .map(|row| RowInfo {
8550                            buffer_row: Some(row),
8551                            ..Default::default()
8552                        })
8553                        .collect::<Vec<_>>(),
8554                    &BTreeMap::default(),
8555                    Some(DisplayPoint::new(DisplayRow(0), 0)),
8556                    &snapshot,
8557                    window,
8558                    cx,
8559                )
8560            })
8561            .unwrap();
8562        assert_eq!(layouts.len(), 6);
8563
8564        let relative_rows = window
8565            .update(cx, |editor, window, cx| {
8566                let snapshot = editor.snapshot(window, cx);
8567                element.calculate_relative_line_numbers(
8568                    &snapshot,
8569                    &(DisplayRow(0)..DisplayRow(6)),
8570                    Some(DisplayRow(3)),
8571                )
8572            })
8573            .unwrap();
8574        assert_eq!(relative_rows[&DisplayRow(0)], 3);
8575        assert_eq!(relative_rows[&DisplayRow(1)], 2);
8576        assert_eq!(relative_rows[&DisplayRow(2)], 1);
8577        // current line has no relative number
8578        assert_eq!(relative_rows[&DisplayRow(4)], 1);
8579        assert_eq!(relative_rows[&DisplayRow(5)], 2);
8580
8581        // works if cursor is before screen
8582        let relative_rows = window
8583            .update(cx, |editor, window, cx| {
8584                let snapshot = editor.snapshot(window, cx);
8585                element.calculate_relative_line_numbers(
8586                    &snapshot,
8587                    &(DisplayRow(3)..DisplayRow(6)),
8588                    Some(DisplayRow(1)),
8589                )
8590            })
8591            .unwrap();
8592        assert_eq!(relative_rows.len(), 3);
8593        assert_eq!(relative_rows[&DisplayRow(3)], 2);
8594        assert_eq!(relative_rows[&DisplayRow(4)], 3);
8595        assert_eq!(relative_rows[&DisplayRow(5)], 4);
8596
8597        // works if cursor is after screen
8598        let relative_rows = window
8599            .update(cx, |editor, window, cx| {
8600                let snapshot = editor.snapshot(window, cx);
8601                element.calculate_relative_line_numbers(
8602                    &snapshot,
8603                    &(DisplayRow(0)..DisplayRow(3)),
8604                    Some(DisplayRow(6)),
8605                )
8606            })
8607            .unwrap();
8608        assert_eq!(relative_rows.len(), 3);
8609        assert_eq!(relative_rows[&DisplayRow(0)], 5);
8610        assert_eq!(relative_rows[&DisplayRow(1)], 4);
8611        assert_eq!(relative_rows[&DisplayRow(2)], 3);
8612    }
8613
8614    #[gpui::test]
8615    async fn test_vim_visual_selections(cx: &mut TestAppContext) {
8616        init_test(cx, |_| {});
8617
8618        let window = cx.add_window(|window, cx| {
8619            let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
8620            Editor::new(EditorMode::Full, buffer, None, window, cx)
8621        });
8622        let cx = &mut VisualTestContext::from_window(*window, cx);
8623        let editor = window.root(cx).unwrap();
8624        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8625
8626        window
8627            .update(cx, |editor, window, cx| {
8628                editor.cursor_shape = CursorShape::Block;
8629                editor.change_selections(None, window, cx, |s| {
8630                    s.select_ranges([
8631                        Point::new(0, 0)..Point::new(1, 0),
8632                        Point::new(3, 2)..Point::new(3, 3),
8633                        Point::new(5, 6)..Point::new(6, 0),
8634                    ]);
8635                });
8636            })
8637            .unwrap();
8638
8639        let (_, state) = cx.draw(
8640            point(px(500.), px(500.)),
8641            size(px(500.), px(500.)),
8642            |_, _| EditorElement::new(&editor, style),
8643        );
8644
8645        assert_eq!(state.selections.len(), 1);
8646        let local_selections = &state.selections[0].1;
8647        assert_eq!(local_selections.len(), 3);
8648        // moves cursor back one line
8649        assert_eq!(
8650            local_selections[0].head,
8651            DisplayPoint::new(DisplayRow(0), 6)
8652        );
8653        assert_eq!(
8654            local_selections[0].range,
8655            DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
8656        );
8657
8658        // moves cursor back one column
8659        assert_eq!(
8660            local_selections[1].range,
8661            DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
8662        );
8663        assert_eq!(
8664            local_selections[1].head,
8665            DisplayPoint::new(DisplayRow(3), 2)
8666        );
8667
8668        // leaves cursor on the max point
8669        assert_eq!(
8670            local_selections[2].range,
8671            DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
8672        );
8673        assert_eq!(
8674            local_selections[2].head,
8675            DisplayPoint::new(DisplayRow(6), 0)
8676        );
8677
8678        // active lines does not include 1 (even though the range of the selection does)
8679        assert_eq!(
8680            state.active_rows.keys().cloned().collect::<Vec<_>>(),
8681            vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
8682        );
8683    }
8684
8685    #[gpui::test]
8686    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
8687        init_test(cx, |_| {});
8688
8689        let window = cx.add_window(|window, cx| {
8690            let buffer = MultiBuffer::build_simple("", cx);
8691            Editor::new(EditorMode::Full, buffer, None, window, cx)
8692        });
8693        let cx = &mut VisualTestContext::from_window(*window, cx);
8694        let editor = window.root(cx).unwrap();
8695        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8696        window
8697            .update(cx, |editor, window, cx| {
8698                editor.set_placeholder_text("hello", cx);
8699                editor.insert_blocks(
8700                    [BlockProperties {
8701                        style: BlockStyle::Fixed,
8702                        placement: BlockPlacement::Above(Anchor::min()),
8703                        height: 3,
8704                        render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
8705                        priority: 0,
8706                    }],
8707                    None,
8708                    cx,
8709                );
8710
8711                // Blur the editor so that it displays placeholder text.
8712                window.blur();
8713            })
8714            .unwrap();
8715
8716        let (_, state) = cx.draw(
8717            point(px(500.), px(500.)),
8718            size(px(500.), px(500.)),
8719            |_, _| EditorElement::new(&editor, style),
8720        );
8721        assert_eq!(state.position_map.line_layouts.len(), 4);
8722        assert_eq!(state.line_numbers.len(), 1);
8723        assert_eq!(
8724            state
8725                .line_numbers
8726                .get(&MultiBufferRow(0))
8727                .map(|line_number| line_number.shaped_line.text.as_ref()),
8728            Some("1")
8729        );
8730    }
8731
8732    #[gpui::test]
8733    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
8734        const TAB_SIZE: u32 = 4;
8735
8736        let input_text = "\t \t|\t| a b";
8737        let expected_invisibles = vec![
8738            Invisible::Tab {
8739                line_start_offset: 0,
8740                line_end_offset: TAB_SIZE as usize,
8741            },
8742            Invisible::Whitespace {
8743                line_offset: TAB_SIZE as usize,
8744            },
8745            Invisible::Tab {
8746                line_start_offset: TAB_SIZE as usize + 1,
8747                line_end_offset: TAB_SIZE as usize * 2,
8748            },
8749            Invisible::Tab {
8750                line_start_offset: TAB_SIZE as usize * 2 + 1,
8751                line_end_offset: TAB_SIZE as usize * 3,
8752            },
8753            Invisible::Whitespace {
8754                line_offset: TAB_SIZE as usize * 3 + 1,
8755            },
8756            Invisible::Whitespace {
8757                line_offset: TAB_SIZE as usize * 3 + 3,
8758            },
8759        ];
8760        assert_eq!(
8761            expected_invisibles.len(),
8762            input_text
8763                .chars()
8764                .filter(|initial_char| initial_char.is_whitespace())
8765                .count(),
8766            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
8767        );
8768
8769        for show_line_numbers in [true, false] {
8770            init_test(cx, |s| {
8771                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8772                s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
8773            });
8774
8775            let actual_invisibles = collect_invisibles_from_new_editor(
8776                cx,
8777                EditorMode::Full,
8778                input_text,
8779                px(500.0),
8780                show_line_numbers,
8781            );
8782
8783            assert_eq!(expected_invisibles, actual_invisibles);
8784        }
8785    }
8786
8787    #[gpui::test]
8788    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
8789        init_test(cx, |s| {
8790            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8791            s.defaults.tab_size = NonZeroU32::new(4);
8792        });
8793
8794        for editor_mode_without_invisibles in [
8795            EditorMode::SingleLine { auto_width: false },
8796            EditorMode::AutoHeight { max_lines: 100 },
8797        ] {
8798            for show_line_numbers in [true, false] {
8799                let invisibles = collect_invisibles_from_new_editor(
8800                    cx,
8801                    editor_mode_without_invisibles,
8802                    "\t\t\t| | a b",
8803                    px(500.0),
8804                    show_line_numbers,
8805                );
8806                assert!(invisibles.is_empty(),
8807                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
8808            }
8809        }
8810    }
8811
8812    #[gpui::test]
8813    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
8814        let tab_size = 4;
8815        let input_text = "a\tbcd     ".repeat(9);
8816        let repeated_invisibles = [
8817            Invisible::Tab {
8818                line_start_offset: 1,
8819                line_end_offset: tab_size as usize,
8820            },
8821            Invisible::Whitespace {
8822                line_offset: tab_size as usize + 3,
8823            },
8824            Invisible::Whitespace {
8825                line_offset: tab_size as usize + 4,
8826            },
8827            Invisible::Whitespace {
8828                line_offset: tab_size as usize + 5,
8829            },
8830            Invisible::Whitespace {
8831                line_offset: tab_size as usize + 6,
8832            },
8833            Invisible::Whitespace {
8834                line_offset: tab_size as usize + 7,
8835            },
8836        ];
8837        let expected_invisibles = std::iter::once(repeated_invisibles)
8838            .cycle()
8839            .take(9)
8840            .flatten()
8841            .collect::<Vec<_>>();
8842        assert_eq!(
8843            expected_invisibles.len(),
8844            input_text
8845                .chars()
8846                .filter(|initial_char| initial_char.is_whitespace())
8847                .count(),
8848            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
8849        );
8850        info!("Expected invisibles: {expected_invisibles:?}");
8851
8852        init_test(cx, |_| {});
8853
8854        // Put the same string with repeating whitespace pattern into editors of various size,
8855        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
8856        let resize_step = 10.0;
8857        let mut editor_width = 200.0;
8858        while editor_width <= 1000.0 {
8859            for show_line_numbers in [true, false] {
8860                update_test_language_settings(cx, |s| {
8861                    s.defaults.tab_size = NonZeroU32::new(tab_size);
8862                    s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8863                    s.defaults.preferred_line_length = Some(editor_width as u32);
8864                    s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
8865                });
8866
8867                let actual_invisibles = collect_invisibles_from_new_editor(
8868                    cx,
8869                    EditorMode::Full,
8870                    &input_text,
8871                    px(editor_width),
8872                    show_line_numbers,
8873                );
8874
8875                // Whatever the editor size is, ensure it has the same invisible kinds in the same order
8876                // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
8877                let mut i = 0;
8878                for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
8879                    i = actual_index;
8880                    match expected_invisibles.get(i) {
8881                        Some(expected_invisible) => match (expected_invisible, actual_invisible) {
8882                            (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
8883                            | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
8884                            _ => {
8885                                panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
8886                            }
8887                        },
8888                        None => {
8889                            panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
8890                        }
8891                    }
8892                }
8893                let missing_expected_invisibles = &expected_invisibles[i + 1..];
8894                assert!(
8895                    missing_expected_invisibles.is_empty(),
8896                    "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
8897                );
8898
8899                editor_width += resize_step;
8900            }
8901        }
8902    }
8903
8904    fn collect_invisibles_from_new_editor(
8905        cx: &mut TestAppContext,
8906        editor_mode: EditorMode,
8907        input_text: &str,
8908        editor_width: Pixels,
8909        show_line_numbers: bool,
8910    ) -> Vec<Invisible> {
8911        info!(
8912            "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
8913            editor_width.0
8914        );
8915        let window = cx.add_window(|window, cx| {
8916            let buffer = MultiBuffer::build_simple(input_text, cx);
8917            Editor::new(editor_mode, buffer, None, window, cx)
8918        });
8919        let cx = &mut VisualTestContext::from_window(*window, cx);
8920        let editor = window.root(cx).unwrap();
8921
8922        let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8923        window
8924            .update(cx, |editor, _, cx| {
8925                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
8926                editor.set_wrap_width(Some(editor_width), cx);
8927                editor.set_show_line_numbers(show_line_numbers, cx);
8928            })
8929            .unwrap();
8930        let (_, state) = cx.draw(
8931            point(px(500.), px(500.)),
8932            size(px(500.), px(500.)),
8933            |_, _| EditorElement::new(&editor, style),
8934        );
8935        state
8936            .position_map
8937            .line_layouts
8938            .iter()
8939            .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
8940            .cloned()
8941            .collect()
8942    }
8943}
8944
8945fn diff_hunk_controls(
8946    row: u32,
8947    status: &DiffHunkStatus,
8948    hunk_range: Range<Anchor>,
8949    is_created_file: bool,
8950    line_height: Pixels,
8951    editor: &Entity<Editor>,
8952    cx: &mut App,
8953) -> AnyElement {
8954    h_flex()
8955        .h(line_height)
8956        .mr_1()
8957        .gap_1()
8958        .px_0p5()
8959        .pb_1()
8960        .border_x_1()
8961        .border_b_1()
8962        .border_color(cx.theme().colors().border_variant)
8963        .rounded_b_lg()
8964        .bg(cx.theme().colors().editor_background)
8965        .gap_1()
8966        .occlude()
8967        .shadow_md()
8968        .child(if status.has_secondary_hunk() {
8969            Button::new(("stage", row as u64), "Stage")
8970                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
8971                .tooltip({
8972                    let focus_handle = editor.focus_handle(cx);
8973                    move |window, cx| {
8974                        Tooltip::for_action_in(
8975                            "Stage Hunk",
8976                            &::git::ToggleStaged,
8977                            &focus_handle,
8978                            window,
8979                            cx,
8980                        )
8981                    }
8982                })
8983                .on_click({
8984                    let editor = editor.clone();
8985                    move |_event, _window, cx| {
8986                        editor.update(cx, |editor, cx| {
8987                            editor.stage_or_unstage_diff_hunks(
8988                                true,
8989                                vec![hunk_range.start..hunk_range.start],
8990                                cx,
8991                            );
8992                        });
8993                    }
8994                })
8995        } else {
8996            Button::new(("unstage", row as u64), "Unstage")
8997                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
8998                .tooltip({
8999                    let focus_handle = editor.focus_handle(cx);
9000                    move |window, cx| {
9001                        Tooltip::for_action_in(
9002                            "Unstage Hunk",
9003                            &::git::ToggleStaged,
9004                            &focus_handle,
9005                            window,
9006                            cx,
9007                        )
9008                    }
9009                })
9010                .on_click({
9011                    let editor = editor.clone();
9012                    move |_event, _window, cx| {
9013                        editor.update(cx, |editor, cx| {
9014                            editor.stage_or_unstage_diff_hunks(
9015                                false,
9016                                vec![hunk_range.start..hunk_range.start],
9017                                cx,
9018                            );
9019                        });
9020                    }
9021                })
9022        })
9023        .child(
9024            Button::new("restore", "Restore")
9025                .tooltip({
9026                    let focus_handle = editor.focus_handle(cx);
9027                    move |window, cx| {
9028                        Tooltip::for_action_in(
9029                            "Restore Hunk",
9030                            &::git::Restore,
9031                            &focus_handle,
9032                            window,
9033                            cx,
9034                        )
9035                    }
9036                })
9037                .on_click({
9038                    let editor = editor.clone();
9039                    move |_event, window, cx| {
9040                        editor.update(cx, |editor, cx| {
9041                            let snapshot = editor.snapshot(window, cx);
9042                            let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
9043                            editor.restore_hunks_in_ranges(vec![point..point], window, cx);
9044                        });
9045                    }
9046                })
9047                .disabled(is_created_file),
9048        )
9049        .when(
9050            !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
9051            |el| {
9052                el.child(
9053                    IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
9054                        .shape(IconButtonShape::Square)
9055                        .icon_size(IconSize::Small)
9056                        // .disabled(!has_multiple_hunks)
9057                        .tooltip({
9058                            let focus_handle = editor.focus_handle(cx);
9059                            move |window, cx| {
9060                                Tooltip::for_action_in(
9061                                    "Next Hunk",
9062                                    &GoToHunk,
9063                                    &focus_handle,
9064                                    window,
9065                                    cx,
9066                                )
9067                            }
9068                        })
9069                        .on_click({
9070                            let editor = editor.clone();
9071                            move |_event, window, cx| {
9072                                editor.update(cx, |editor, cx| {
9073                                    let snapshot = editor.snapshot(window, cx);
9074                                    let position =
9075                                        hunk_range.end.to_point(&snapshot.buffer_snapshot);
9076                                    editor.go_to_hunk_before_or_after_position(
9077                                        &snapshot,
9078                                        position,
9079                                        Direction::Next,
9080                                        window,
9081                                        cx,
9082                                    );
9083                                    editor.expand_selected_diff_hunks(cx);
9084                                });
9085                            }
9086                        }),
9087                )
9088                .child(
9089                    IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
9090                        .shape(IconButtonShape::Square)
9091                        .icon_size(IconSize::Small)
9092                        // .disabled(!has_multiple_hunks)
9093                        .tooltip({
9094                            let focus_handle = editor.focus_handle(cx);
9095                            move |window, cx| {
9096                                Tooltip::for_action_in(
9097                                    "Previous Hunk",
9098                                    &GoToPreviousHunk,
9099                                    &focus_handle,
9100                                    window,
9101                                    cx,
9102                                )
9103                            }
9104                        })
9105                        .on_click({
9106                            let editor = editor.clone();
9107                            move |_event, window, cx| {
9108                                editor.update(cx, |editor, cx| {
9109                                    let snapshot = editor.snapshot(window, cx);
9110                                    let point =
9111                                        hunk_range.start.to_point(&snapshot.buffer_snapshot);
9112                                    editor.go_to_hunk_before_or_after_position(
9113                                        &snapshot,
9114                                        point,
9115                                        Direction::Prev,
9116                                        window,
9117                                        cx,
9118                                    );
9119                                    editor.expand_selected_diff_hunks(cx);
9120                                });
9121                            }
9122                        }),
9123                )
9124            },
9125        )
9126        .into_any_element()
9127}