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