element.rs

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