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