element.rs

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