element.rs

   1use crate::editor_settings::ScrollBeyondLastLine;
   2use crate::{
   3    blame_entry_tooltip::{blame_entry_relative_timestamp, BlameEntryTooltip},
   4    display_map::{
   5        BlockContext, BlockStyle, DisplaySnapshot, HighlightedChunk, ToDisplayPoint, TransformBlock,
   6    },
   7    editor_settings::{
   8        CurrentLineHighlight, DoubleClickInMultibuffer, MultiCursorModifier, ShowScrollbar,
   9    },
  10    git::{
  11        blame::{CommitDetails, GitBlame},
  12        diff_hunk_to_display, DisplayDiffHunk,
  13    },
  14    hover_popover::{
  15        self, hover_at, HOVER_POPOVER_GAP, MIN_POPOVER_CHARACTER_WIDTH, MIN_POPOVER_LINE_HEIGHT,
  16    },
  17    hunk_status,
  18    items::BufferSearchHighlights,
  19    mouse_context_menu::{self, MouseContextMenu},
  20    scroll::scroll_amount::ScrollAmount,
  21    CodeActionsMenu, CursorShape, DisplayPoint, DisplayRow, DocumentHighlightRead,
  22    DocumentHighlightWrite, Editor, EditorMode, EditorSettings, EditorSnapshot, EditorStyle,
  23    ExpandExcerpts, GutterDimensions, HalfPageDown, HalfPageUp, HoveredCursor, HunkToExpand,
  24    LineDown, LineUp, OpenExcerpts, PageDown, PageUp, Point, RowExt, RowRangeExt, SelectPhase,
  25    Selection, SoftWrap, ToPoint, CURSORS_VISIBLE_FOR, MAX_LINE_LEN,
  26};
  27use client::ParticipantIndex;
  28use collections::{BTreeMap, HashMap};
  29use git::{blame::BlameEntry, diff::DiffHunkStatus, Oid};
  30use gpui::{
  31    anchored, deferred, div, fill, outline, point, px, quad, relative, size, svg,
  32    transparent_black, Action, AnchorCorner, AnyElement, AvailableSpace, Bounds, ClipboardItem,
  33    ContentMask, Corners, CursorStyle, DispatchPhase, Edges, Element, ElementInputHandler, Entity,
  34    FontId, GlobalElementId, Hitbox, Hsla, InteractiveElement, IntoElement, Length,
  35    ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PaintQuad,
  36    ParentElement, Pixels, ScrollDelta, ScrollWheelEvent, ShapedLine, SharedString, Size,
  37    StatefulInteractiveElement, Style, Styled, TextRun, TextStyle, TextStyleRefinement, View,
  38    ViewContext, WeakView, WindowContext,
  39};
  40use itertools::Itertools;
  41use language::language_settings::{
  42    IndentGuideBackgroundColoring, IndentGuideColoring, IndentGuideSettings, ShowWhitespaceSetting,
  43};
  44use lsp::DiagnosticSeverity;
  45use multi_buffer::{Anchor, MultiBufferPoint, MultiBufferRow};
  46use project::{
  47    project_settings::{GitGutterSetting, ProjectSettings},
  48    ProjectPath,
  49};
  50use settings::Settings;
  51use smallvec::{smallvec, SmallVec};
  52use std::{
  53    any::TypeId,
  54    borrow::Cow,
  55    cmp::{self, Ordering},
  56    fmt::{self, Write},
  57    iter, mem,
  58    ops::{Deref, Range},
  59    sync::Arc,
  60};
  61use sum_tree::Bias;
  62use theme::{ActiveTheme, PlayerColor};
  63use ui::prelude::*;
  64use ui::{h_flex, ButtonLike, ButtonStyle, ContextMenu, Tooltip};
  65use util::ResultExt;
  66use workspace::{item::Item, Workspace};
  67
  68struct SelectionLayout {
  69    head: DisplayPoint,
  70    cursor_shape: CursorShape,
  71    is_newest: bool,
  72    is_local: bool,
  73    range: Range<DisplayPoint>,
  74    active_rows: Range<DisplayRow>,
  75    user_name: Option<SharedString>,
  76}
  77
  78impl SelectionLayout {
  79    fn new<T: ToPoint + ToDisplayPoint + Clone>(
  80        selection: Selection<T>,
  81        line_mode: bool,
  82        cursor_shape: CursorShape,
  83        map: &DisplaySnapshot,
  84        is_newest: bool,
  85        is_local: bool,
  86        user_name: Option<SharedString>,
  87    ) -> Self {
  88        let point_selection = selection.map(|p| p.to_point(&map.buffer_snapshot));
  89        let display_selection = point_selection.map(|p| p.to_display_point(map));
  90        let mut range = display_selection.range();
  91        let mut head = display_selection.head();
  92        let mut active_rows = map.prev_line_boundary(point_selection.start).1.row()
  93            ..map.next_line_boundary(point_selection.end).1.row();
  94
  95        // vim visual line mode
  96        if line_mode {
  97            let point_range = map.expand_to_line(point_selection.range());
  98            range = point_range.start.to_display_point(map)..point_range.end.to_display_point(map);
  99        }
 100
 101        // any vim visual mode (including line mode)
 102        if (cursor_shape == CursorShape::Block || cursor_shape == CursorShape::Hollow)
 103            && !range.is_empty()
 104            && !selection.reversed
 105        {
 106            if head.column() > 0 {
 107                head = map.clip_point(DisplayPoint::new(head.row(), head.column() - 1), Bias::Left)
 108            } else if head.row().0 > 0 && head != map.max_point() {
 109                head = map.clip_point(
 110                    DisplayPoint::new(
 111                        head.row().previous_row(),
 112                        map.line_len(head.row().previous_row()),
 113                    ),
 114                    Bias::Left,
 115                );
 116                // updating range.end is a no-op unless you're cursor is
 117                // on the newline containing a multi-buffer divider
 118                // in which case the clip_point may have moved the head up
 119                // an additional row.
 120                range.end = DisplayPoint::new(head.row().next_row(), 0);
 121                active_rows.end = head.row();
 122            }
 123        }
 124
 125        Self {
 126            head,
 127            cursor_shape,
 128            is_newest,
 129            is_local,
 130            range,
 131            active_rows,
 132            user_name,
 133        }
 134    }
 135}
 136
 137pub struct EditorElement {
 138    editor: View<Editor>,
 139    style: EditorStyle,
 140}
 141
 142type DisplayRowDelta = u32;
 143
 144impl EditorElement {
 145    pub(crate) const SCROLLBAR_WIDTH: Pixels = px(13.);
 146
 147    pub fn new(editor: &View<Editor>, style: EditorStyle) -> Self {
 148        Self {
 149            editor: editor.clone(),
 150            style,
 151        }
 152    }
 153
 154    fn register_actions(&self, cx: &mut WindowContext) {
 155        let view = &self.editor;
 156        view.update(cx, |editor, cx| {
 157            for action in editor.editor_actions.borrow().values() {
 158                (action)(cx)
 159            }
 160        });
 161
 162        crate::rust_analyzer_ext::apply_related_actions(view, cx);
 163        register_action(view, cx, Editor::move_left);
 164        register_action(view, cx, Editor::move_right);
 165        register_action(view, cx, Editor::move_down);
 166        register_action(view, cx, Editor::move_down_by_lines);
 167        register_action(view, cx, Editor::select_down_by_lines);
 168        register_action(view, cx, Editor::move_up);
 169        register_action(view, cx, Editor::move_up_by_lines);
 170        register_action(view, cx, Editor::select_up_by_lines);
 171        register_action(view, cx, Editor::select_page_down);
 172        register_action(view, cx, Editor::select_page_up);
 173        register_action(view, cx, Editor::cancel);
 174        register_action(view, cx, Editor::newline);
 175        register_action(view, cx, Editor::newline_above);
 176        register_action(view, cx, Editor::newline_below);
 177        register_action(view, cx, Editor::backspace);
 178        register_action(view, cx, Editor::delete);
 179        register_action(view, cx, Editor::tab);
 180        register_action(view, cx, Editor::tab_prev);
 181        register_action(view, cx, Editor::indent);
 182        register_action(view, cx, Editor::outdent);
 183        register_action(view, cx, Editor::delete_line);
 184        register_action(view, cx, Editor::join_lines);
 185        register_action(view, cx, Editor::sort_lines_case_sensitive);
 186        register_action(view, cx, Editor::sort_lines_case_insensitive);
 187        register_action(view, cx, Editor::reverse_lines);
 188        register_action(view, cx, Editor::shuffle_lines);
 189        register_action(view, cx, Editor::convert_to_upper_case);
 190        register_action(view, cx, Editor::convert_to_lower_case);
 191        register_action(view, cx, Editor::convert_to_title_case);
 192        register_action(view, cx, Editor::convert_to_snake_case);
 193        register_action(view, cx, Editor::convert_to_kebab_case);
 194        register_action(view, cx, Editor::convert_to_upper_camel_case);
 195        register_action(view, cx, Editor::convert_to_lower_camel_case);
 196        register_action(view, cx, Editor::convert_to_opposite_case);
 197        register_action(view, cx, Editor::delete_to_previous_word_start);
 198        register_action(view, cx, Editor::delete_to_previous_subword_start);
 199        register_action(view, cx, Editor::delete_to_next_word_end);
 200        register_action(view, cx, Editor::delete_to_next_subword_end);
 201        register_action(view, cx, Editor::delete_to_beginning_of_line);
 202        register_action(view, cx, Editor::delete_to_end_of_line);
 203        register_action(view, cx, Editor::cut_to_end_of_line);
 204        register_action(view, cx, Editor::duplicate_line_up);
 205        register_action(view, cx, Editor::duplicate_line_down);
 206        register_action(view, cx, Editor::move_line_up);
 207        register_action(view, cx, Editor::move_line_down);
 208        register_action(view, cx, Editor::transpose);
 209        register_action(view, cx, Editor::cut);
 210        register_action(view, cx, Editor::copy);
 211        register_action(view, cx, Editor::paste);
 212        register_action(view, cx, Editor::undo);
 213        register_action(view, cx, Editor::redo);
 214        register_action(view, cx, Editor::move_page_up);
 215        register_action(view, cx, Editor::move_page_down);
 216        register_action(view, cx, Editor::next_screen);
 217        register_action(view, cx, Editor::scroll_cursor_top);
 218        register_action(view, cx, Editor::scroll_cursor_center);
 219        register_action(view, cx, Editor::scroll_cursor_bottom);
 220        register_action(view, cx, |editor, _: &LineDown, cx| {
 221            editor.scroll_screen(&ScrollAmount::Line(1.), cx)
 222        });
 223        register_action(view, cx, |editor, _: &LineUp, cx| {
 224            editor.scroll_screen(&ScrollAmount::Line(-1.), cx)
 225        });
 226        register_action(view, cx, |editor, _: &HalfPageDown, cx| {
 227            editor.scroll_screen(&ScrollAmount::Page(0.5), cx)
 228        });
 229        register_action(view, cx, |editor, _: &HalfPageUp, cx| {
 230            editor.scroll_screen(&ScrollAmount::Page(-0.5), cx)
 231        });
 232        register_action(view, cx, |editor, _: &PageDown, cx| {
 233            editor.scroll_screen(&ScrollAmount::Page(1.), cx)
 234        });
 235        register_action(view, cx, |editor, _: &PageUp, cx| {
 236            editor.scroll_screen(&ScrollAmount::Page(-1.), cx)
 237        });
 238        register_action(view, cx, Editor::move_to_previous_word_start);
 239        register_action(view, cx, Editor::move_to_previous_subword_start);
 240        register_action(view, cx, Editor::move_to_next_word_end);
 241        register_action(view, cx, Editor::move_to_next_subword_end);
 242        register_action(view, cx, Editor::move_to_beginning_of_line);
 243        register_action(view, cx, Editor::move_to_end_of_line);
 244        register_action(view, cx, Editor::move_to_start_of_paragraph);
 245        register_action(view, cx, Editor::move_to_end_of_paragraph);
 246        register_action(view, cx, Editor::move_to_beginning);
 247        register_action(view, cx, Editor::move_to_end);
 248        register_action(view, cx, Editor::select_up);
 249        register_action(view, cx, Editor::select_down);
 250        register_action(view, cx, Editor::select_left);
 251        register_action(view, cx, Editor::select_right);
 252        register_action(view, cx, Editor::select_to_previous_word_start);
 253        register_action(view, cx, Editor::select_to_previous_subword_start);
 254        register_action(view, cx, Editor::select_to_next_word_end);
 255        register_action(view, cx, Editor::select_to_next_subword_end);
 256        register_action(view, cx, Editor::select_to_beginning_of_line);
 257        register_action(view, cx, Editor::select_to_end_of_line);
 258        register_action(view, cx, Editor::select_to_start_of_paragraph);
 259        register_action(view, cx, Editor::select_to_end_of_paragraph);
 260        register_action(view, cx, Editor::select_to_beginning);
 261        register_action(view, cx, Editor::select_to_end);
 262        register_action(view, cx, Editor::select_all);
 263        register_action(view, cx, |editor, action, cx| {
 264            editor.select_all_matches(action, cx).log_err();
 265        });
 266        register_action(view, cx, Editor::select_line);
 267        register_action(view, cx, Editor::split_selection_into_lines);
 268        register_action(view, cx, Editor::add_selection_above);
 269        register_action(view, cx, Editor::add_selection_below);
 270        register_action(view, cx, |editor, action, cx| {
 271            editor.select_next(action, cx).log_err();
 272        });
 273        register_action(view, cx, |editor, action, cx| {
 274            editor.select_previous(action, cx).log_err();
 275        });
 276        register_action(view, cx, Editor::toggle_comments);
 277        register_action(view, cx, Editor::select_larger_syntax_node);
 278        register_action(view, cx, Editor::select_smaller_syntax_node);
 279        register_action(view, cx, Editor::select_enclosing_symbol);
 280        register_action(view, cx, Editor::move_to_enclosing_bracket);
 281        register_action(view, cx, Editor::undo_selection);
 282        register_action(view, cx, Editor::redo_selection);
 283        if !view.read(cx).is_singleton(cx) {
 284            register_action(view, cx, Editor::expand_excerpts);
 285            register_action(view, cx, Editor::expand_excerpts_up);
 286            register_action(view, cx, Editor::expand_excerpts_down);
 287        }
 288        register_action(view, cx, Editor::go_to_diagnostic);
 289        register_action(view, cx, Editor::go_to_prev_diagnostic);
 290        register_action(view, cx, Editor::go_to_hunk);
 291        register_action(view, cx, Editor::go_to_prev_hunk);
 292        register_action(view, cx, |editor, a, cx| {
 293            editor.go_to_definition(a, cx).detach_and_log_err(cx);
 294        });
 295        register_action(view, cx, |editor, a, cx| {
 296            editor.go_to_definition_split(a, cx).detach_and_log_err(cx);
 297        });
 298        register_action(view, cx, |editor, a, cx| {
 299            editor.go_to_implementation(a, cx).detach_and_log_err(cx);
 300        });
 301        register_action(view, cx, |editor, a, cx| {
 302            editor
 303                .go_to_implementation_split(a, cx)
 304                .detach_and_log_err(cx);
 305        });
 306        register_action(view, cx, |editor, a, cx| {
 307            editor.go_to_type_definition(a, cx).detach_and_log_err(cx);
 308        });
 309        register_action(view, cx, |editor, a, cx| {
 310            editor
 311                .go_to_type_definition_split(a, cx)
 312                .detach_and_log_err(cx);
 313        });
 314        register_action(view, cx, Editor::open_url);
 315        register_action(view, cx, Editor::fold);
 316        register_action(view, cx, Editor::fold_at);
 317        register_action(view, cx, Editor::unfold_lines);
 318        register_action(view, cx, Editor::unfold_at);
 319        register_action(view, cx, Editor::fold_selected_ranges);
 320        register_action(view, cx, Editor::show_completions);
 321        register_action(view, cx, Editor::toggle_code_actions);
 322        register_action(view, cx, Editor::open_excerpts);
 323        register_action(view, cx, Editor::open_excerpts_in_split);
 324        register_action(view, cx, Editor::toggle_soft_wrap);
 325        register_action(view, cx, Editor::toggle_tab_bar);
 326        register_action(view, cx, Editor::toggle_line_numbers);
 327        register_action(view, cx, Editor::toggle_indent_guides);
 328        register_action(view, cx, Editor::toggle_inlay_hints);
 329        register_action(view, cx, hover_popover::hover);
 330        register_action(view, cx, Editor::reveal_in_finder);
 331        register_action(view, cx, Editor::copy_path);
 332        register_action(view, cx, Editor::copy_relative_path);
 333        register_action(view, cx, Editor::copy_highlight_json);
 334        register_action(view, cx, Editor::copy_permalink_to_line);
 335        register_action(view, cx, Editor::open_permalink_to_line);
 336        register_action(view, cx, Editor::toggle_git_blame);
 337        register_action(view, cx, Editor::toggle_git_blame_inline);
 338        register_action(view, cx, Editor::toggle_hunk_diff);
 339        register_action(view, cx, Editor::expand_all_hunk_diffs);
 340        register_action(view, cx, |editor, action, cx| {
 341            if let Some(task) = editor.format(action, cx) {
 342                task.detach_and_log_err(cx);
 343            } else {
 344                cx.propagate();
 345            }
 346        });
 347        register_action(view, cx, Editor::restart_language_server);
 348        register_action(view, cx, Editor::cancel_language_server_work);
 349        register_action(view, cx, Editor::show_character_palette);
 350        register_action(view, cx, |editor, action, cx| {
 351            if let Some(task) = editor.confirm_completion(action, cx) {
 352                task.detach_and_log_err(cx);
 353            } else {
 354                cx.propagate();
 355            }
 356        });
 357        register_action(view, cx, |editor, action, cx| {
 358            if let Some(task) = editor.confirm_code_action(action, cx) {
 359                task.detach_and_log_err(cx);
 360            } else {
 361                cx.propagate();
 362            }
 363        });
 364        register_action(view, cx, |editor, action, cx| {
 365            if let Some(task) = editor.rename(action, cx) {
 366                task.detach_and_log_err(cx);
 367            } else {
 368                cx.propagate();
 369            }
 370        });
 371        register_action(view, cx, |editor, action, cx| {
 372            if let Some(task) = editor.confirm_rename(action, cx) {
 373                task.detach_and_log_err(cx);
 374            } else {
 375                cx.propagate();
 376            }
 377        });
 378        register_action(view, cx, |editor, action, cx| {
 379            if let Some(task) = editor.find_all_references(action, cx) {
 380                task.detach_and_log_err(cx);
 381            } else {
 382                cx.propagate();
 383            }
 384        });
 385        register_action(view, cx, Editor::next_inline_completion);
 386        register_action(view, cx, Editor::previous_inline_completion);
 387        register_action(view, cx, Editor::show_inline_completion);
 388        register_action(view, cx, Editor::context_menu_first);
 389        register_action(view, cx, Editor::context_menu_prev);
 390        register_action(view, cx, Editor::context_menu_next);
 391        register_action(view, cx, Editor::context_menu_last);
 392        register_action(view, cx, Editor::display_cursor_names);
 393        register_action(view, cx, Editor::unique_lines_case_insensitive);
 394        register_action(view, cx, Editor::unique_lines_case_sensitive);
 395        register_action(view, cx, Editor::accept_partial_inline_completion);
 396        register_action(view, cx, Editor::accept_inline_completion);
 397        register_action(view, cx, Editor::revert_selected_hunks);
 398        register_action(view, cx, Editor::open_active_item_in_terminal)
 399    }
 400
 401    fn register_key_listeners(&self, cx: &mut WindowContext, layout: &EditorLayout) {
 402        let position_map = layout.position_map.clone();
 403        cx.on_key_event({
 404            let editor = self.editor.clone();
 405            let text_hitbox = layout.text_hitbox.clone();
 406            move |event: &ModifiersChangedEvent, phase, cx| {
 407                if phase != DispatchPhase::Bubble {
 408                    return;
 409                }
 410
 411                editor.update(cx, |editor, cx| {
 412                    Self::modifiers_changed(editor, event, &position_map, &text_hitbox, cx)
 413                })
 414            }
 415        });
 416    }
 417
 418    fn modifiers_changed(
 419        editor: &mut Editor,
 420        event: &ModifiersChangedEvent,
 421        position_map: &PositionMap,
 422        text_hitbox: &Hitbox,
 423        cx: &mut ViewContext<Editor>,
 424    ) {
 425        let mouse_position = cx.mouse_position();
 426        if !text_hitbox.is_hovered(cx) {
 427            return;
 428        }
 429
 430        editor.update_hovered_link(
 431            position_map.point_for_position(text_hitbox.bounds, mouse_position),
 432            &position_map.snapshot,
 433            event.modifiers,
 434            cx,
 435        )
 436    }
 437
 438    fn mouse_left_down(
 439        editor: &mut Editor,
 440        event: &MouseDownEvent,
 441        hovered_hunk: Option<&HunkToExpand>,
 442        position_map: &PositionMap,
 443        text_hitbox: &Hitbox,
 444        gutter_hitbox: &Hitbox,
 445        cx: &mut ViewContext<Editor>,
 446    ) {
 447        if cx.default_prevented() {
 448            return;
 449        }
 450
 451        let mut click_count = event.click_count;
 452        let mut modifiers = event.modifiers;
 453
 454        if let Some(hovered_hunk) = hovered_hunk {
 455            editor.expand_diff_hunk(None, hovered_hunk, cx);
 456            cx.notify();
 457            return;
 458        } else if gutter_hitbox.is_hovered(cx) {
 459            click_count = 3; // Simulate triple-click when clicking the gutter to select lines
 460        } else if !text_hitbox.is_hovered(cx) {
 461            return;
 462        }
 463
 464        if click_count == 2 && !editor.buffer().read(cx).is_singleton() {
 465            match EditorSettings::get_global(cx).double_click_in_multibuffer {
 466                DoubleClickInMultibuffer::Select => {
 467                    // do nothing special on double click, all selection logic is below
 468                }
 469                DoubleClickInMultibuffer::Open => {
 470                    if modifiers.alt {
 471                        // if double click is made with alt, pretend it's a regular double click without opening and alt,
 472                        // and run the selection logic.
 473                        modifiers.alt = false;
 474                    } else {
 475                        // if double click is made without alt, open the corresponding excerp
 476                        editor.open_excerpts(&OpenExcerpts, cx);
 477                        return;
 478                    }
 479                }
 480            }
 481        }
 482
 483        let point_for_position =
 484            position_map.point_for_position(text_hitbox.bounds, event.position);
 485        let position = point_for_position.previous_valid;
 486        if modifiers.shift && modifiers.alt {
 487            editor.select(
 488                SelectPhase::BeginColumnar {
 489                    position,
 490                    reset: false,
 491                    goal_column: point_for_position.exact_unclipped.column(),
 492                },
 493                cx,
 494            );
 495        } else if modifiers.shift && !modifiers.control && !modifiers.alt && !modifiers.secondary()
 496        {
 497            editor.select(
 498                SelectPhase::Extend {
 499                    position,
 500                    click_count,
 501                },
 502                cx,
 503            );
 504        } else {
 505            let multi_cursor_setting = EditorSettings::get_global(cx).multi_cursor_modifier;
 506            let multi_cursor_modifier = match multi_cursor_setting {
 507                MultiCursorModifier::Alt => modifiers.alt,
 508                MultiCursorModifier::CmdOrCtrl => modifiers.secondary(),
 509            };
 510            editor.select(
 511                SelectPhase::Begin {
 512                    position,
 513                    add: multi_cursor_modifier,
 514                    click_count,
 515                },
 516                cx,
 517            );
 518        }
 519
 520        cx.stop_propagation();
 521    }
 522
 523    fn mouse_right_down(
 524        editor: &mut Editor,
 525        event: &MouseDownEvent,
 526        position_map: &PositionMap,
 527        text_hitbox: &Hitbox,
 528        cx: &mut ViewContext<Editor>,
 529    ) {
 530        if !text_hitbox.is_hovered(cx) {
 531            return;
 532        }
 533        let point_for_position =
 534            position_map.point_for_position(text_hitbox.bounds, event.position);
 535        mouse_context_menu::deploy_context_menu(
 536            editor,
 537            event.position,
 538            point_for_position.previous_valid,
 539            cx,
 540        );
 541        cx.stop_propagation();
 542    }
 543
 544    fn mouse_middle_down(
 545        editor: &mut Editor,
 546        event: &MouseDownEvent,
 547        position_map: &PositionMap,
 548        text_hitbox: &Hitbox,
 549        cx: &mut ViewContext<Editor>,
 550    ) {
 551        if !text_hitbox.is_hovered(cx) || cx.default_prevented() {
 552            return;
 553        }
 554
 555        let point_for_position =
 556            position_map.point_for_position(text_hitbox.bounds, event.position);
 557        let position = point_for_position.previous_valid;
 558
 559        editor.select(
 560            SelectPhase::BeginColumnar {
 561                position,
 562                reset: true,
 563                goal_column: point_for_position.exact_unclipped.column(),
 564            },
 565            cx,
 566        );
 567    }
 568
 569    fn mouse_up(
 570        editor: &mut Editor,
 571        event: &MouseUpEvent,
 572        position_map: &PositionMap,
 573        text_hitbox: &Hitbox,
 574        cx: &mut ViewContext<Editor>,
 575    ) {
 576        let end_selection = editor.has_pending_selection();
 577        let pending_nonempty_selections = editor.has_pending_nonempty_selection();
 578
 579        if end_selection {
 580            editor.select(SelectPhase::End, cx);
 581        }
 582
 583        let multi_cursor_setting = EditorSettings::get_global(cx).multi_cursor_modifier;
 584        let multi_cursor_modifier = match multi_cursor_setting {
 585            MultiCursorModifier::Alt => event.modifiers.secondary(),
 586            MultiCursorModifier::CmdOrCtrl => event.modifiers.alt,
 587        };
 588
 589        if !pending_nonempty_selections && multi_cursor_modifier && text_hitbox.is_hovered(cx) {
 590            let point = position_map.point_for_position(text_hitbox.bounds, event.position);
 591            editor.handle_click_hovered_link(point, event.modifiers, cx);
 592
 593            cx.stop_propagation();
 594        } else if end_selection && pending_nonempty_selections {
 595            cx.stop_propagation();
 596        } else if cfg!(target_os = "linux") && event.button == MouseButton::Middle {
 597            if !text_hitbox.is_hovered(cx) || editor.read_only(cx) {
 598                return;
 599            }
 600
 601            #[cfg(target_os = "linux")]
 602            if let Some(item) = cx.read_from_primary() {
 603                let point_for_position =
 604                    position_map.point_for_position(text_hitbox.bounds, event.position);
 605                let position = point_for_position.previous_valid;
 606
 607                editor.select(
 608                    SelectPhase::Begin {
 609                        position,
 610                        add: false,
 611                        click_count: 1,
 612                    },
 613                    cx,
 614                );
 615                editor.insert(item.text(), cx);
 616            }
 617            cx.stop_propagation()
 618        }
 619    }
 620
 621    fn mouse_dragged(
 622        editor: &mut Editor,
 623        event: &MouseMoveEvent,
 624        position_map: &PositionMap,
 625        text_bounds: Bounds<Pixels>,
 626        cx: &mut ViewContext<Editor>,
 627    ) {
 628        if !editor.has_pending_selection() {
 629            return;
 630        }
 631
 632        let point_for_position = position_map.point_for_position(text_bounds, event.position);
 633        let mut scroll_delta = gpui::Point::<f32>::default();
 634        let vertical_margin = position_map.line_height.min(text_bounds.size.height / 3.0);
 635        let top = text_bounds.origin.y + vertical_margin;
 636        let bottom = text_bounds.lower_left().y - vertical_margin;
 637        if event.position.y < top {
 638            scroll_delta.y = -scale_vertical_mouse_autoscroll_delta(top - event.position.y);
 639        }
 640        if event.position.y > bottom {
 641            scroll_delta.y = scale_vertical_mouse_autoscroll_delta(event.position.y - bottom);
 642        }
 643
 644        let horizontal_margin = position_map.line_height.min(text_bounds.size.width / 3.0);
 645        let left = text_bounds.origin.x + horizontal_margin;
 646        let right = text_bounds.upper_right().x - horizontal_margin;
 647        if event.position.x < left {
 648            scroll_delta.x = -scale_horizontal_mouse_autoscroll_delta(left - event.position.x);
 649        }
 650        if event.position.x > right {
 651            scroll_delta.x = scale_horizontal_mouse_autoscroll_delta(event.position.x - right);
 652        }
 653
 654        editor.select(
 655            SelectPhase::Update {
 656                position: point_for_position.previous_valid,
 657                goal_column: point_for_position.exact_unclipped.column(),
 658                scroll_delta,
 659            },
 660            cx,
 661        );
 662    }
 663
 664    fn mouse_moved(
 665        editor: &mut Editor,
 666        event: &MouseMoveEvent,
 667        position_map: &PositionMap,
 668        text_hitbox: &Hitbox,
 669        gutter_hitbox: &Hitbox,
 670        cx: &mut ViewContext<Editor>,
 671    ) {
 672        let modifiers = event.modifiers;
 673        let gutter_hovered = gutter_hitbox.is_hovered(cx);
 674        editor.set_gutter_hovered(gutter_hovered, cx);
 675
 676        // Don't trigger hover popover if mouse is hovering over context menu
 677        if text_hitbox.is_hovered(cx) {
 678            let point_for_position =
 679                position_map.point_for_position(text_hitbox.bounds, event.position);
 680
 681            editor.update_hovered_link(point_for_position, &position_map.snapshot, modifiers, cx);
 682
 683            if let Some(point) = point_for_position.as_valid() {
 684                let anchor = position_map
 685                    .snapshot
 686                    .buffer_snapshot
 687                    .anchor_before(point.to_offset(&position_map.snapshot, Bias::Left));
 688                hover_at(editor, Some(anchor), cx);
 689                Self::update_visible_cursor(editor, point, position_map, cx);
 690            } else {
 691                hover_at(editor, None, cx);
 692            }
 693        } else {
 694            editor.hide_hovered_link(cx);
 695            hover_at(editor, None, cx);
 696            if gutter_hovered {
 697                cx.stop_propagation();
 698            }
 699        }
 700    }
 701
 702    fn update_visible_cursor(
 703        editor: &mut Editor,
 704        point: DisplayPoint,
 705        position_map: &PositionMap,
 706        cx: &mut ViewContext<Editor>,
 707    ) {
 708        let snapshot = &position_map.snapshot;
 709        let Some(hub) = editor.collaboration_hub() else {
 710            return;
 711        };
 712        let start = snapshot.display_snapshot.clip_point(
 713            DisplayPoint::new(point.row(), point.column().saturating_sub(1)),
 714            Bias::Left,
 715        );
 716        let end = snapshot.display_snapshot.clip_point(
 717            DisplayPoint::new(
 718                point.row(),
 719                (point.column() + 1).min(snapshot.line_len(point.row())),
 720            ),
 721            Bias::Right,
 722        );
 723
 724        let range = snapshot
 725            .buffer_snapshot
 726            .anchor_at(start.to_point(&snapshot.display_snapshot), Bias::Left)
 727            ..snapshot
 728                .buffer_snapshot
 729                .anchor_at(end.to_point(&snapshot.display_snapshot), Bias::Right);
 730
 731        let Some(selection) = snapshot.remote_selections_in_range(&range, hub, cx).next() else {
 732            return;
 733        };
 734        let key = crate::HoveredCursor {
 735            replica_id: selection.replica_id,
 736            selection_id: selection.selection.id,
 737        };
 738        editor.hovered_cursors.insert(
 739            key.clone(),
 740            cx.spawn(|editor, mut cx| async move {
 741                cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 742                editor
 743                    .update(&mut cx, |editor, cx| {
 744                        editor.hovered_cursors.remove(&key);
 745                        cx.notify();
 746                    })
 747                    .ok();
 748            }),
 749        );
 750        cx.notify()
 751    }
 752
 753    fn layout_selections(
 754        &self,
 755        start_anchor: Anchor,
 756        end_anchor: Anchor,
 757        snapshot: &EditorSnapshot,
 758        start_row: DisplayRow,
 759        end_row: DisplayRow,
 760        cx: &mut WindowContext,
 761    ) -> (
 762        Vec<(PlayerColor, Vec<SelectionLayout>)>,
 763        BTreeMap<DisplayRow, bool>,
 764        Option<DisplayPoint>,
 765    ) {
 766        let mut selections: Vec<(PlayerColor, Vec<SelectionLayout>)> = Vec::new();
 767        let mut active_rows = BTreeMap::new();
 768        let mut newest_selection_head = None;
 769        let editor = self.editor.read(cx);
 770
 771        if editor.show_local_selections {
 772            let mut local_selections: Vec<Selection<Point>> = editor
 773                .selections
 774                .disjoint_in_range(start_anchor..end_anchor, cx);
 775            local_selections.extend(editor.selections.pending(cx));
 776            let mut layouts = Vec::new();
 777            let newest = editor.selections.newest(cx);
 778            for selection in local_selections.drain(..) {
 779                let is_empty = selection.start == selection.end;
 780                let is_newest = selection == newest;
 781
 782                let layout = SelectionLayout::new(
 783                    selection,
 784                    editor.selections.line_mode,
 785                    editor.cursor_shape,
 786                    &snapshot.display_snapshot,
 787                    is_newest,
 788                    editor.leader_peer_id.is_none(),
 789                    None,
 790                );
 791                if is_newest {
 792                    newest_selection_head = Some(layout.head);
 793                }
 794
 795                for row in cmp::max(layout.active_rows.start.0, start_row.0)
 796                    ..=cmp::min(layout.active_rows.end.0, end_row.0)
 797                {
 798                    let contains_non_empty_selection =
 799                        active_rows.entry(DisplayRow(row)).or_insert(!is_empty);
 800                    *contains_non_empty_selection |= !is_empty;
 801                }
 802                layouts.push(layout);
 803            }
 804
 805            let player = if editor.read_only(cx) {
 806                cx.theme().players().read_only()
 807            } else {
 808                self.style.local_player
 809            };
 810
 811            selections.push((player, layouts));
 812        }
 813
 814        if let Some(collaboration_hub) = &editor.collaboration_hub {
 815            // When following someone, render the local selections in their color.
 816            if let Some(leader_id) = editor.leader_peer_id {
 817                if let Some(collaborator) = collaboration_hub.collaborators(cx).get(&leader_id) {
 818                    if let Some(participant_index) = collaboration_hub
 819                        .user_participant_indices(cx)
 820                        .get(&collaborator.user_id)
 821                    {
 822                        if let Some((local_selection_style, _)) = selections.first_mut() {
 823                            *local_selection_style = cx
 824                                .theme()
 825                                .players()
 826                                .color_for_participant(participant_index.0);
 827                        }
 828                    }
 829                }
 830            }
 831
 832            let mut remote_selections = HashMap::default();
 833            for selection in snapshot.remote_selections_in_range(
 834                &(start_anchor..end_anchor),
 835                collaboration_hub.as_ref(),
 836                cx,
 837            ) {
 838                let selection_style = Self::get_participant_color(selection.participant_index, cx);
 839
 840                // Don't re-render the leader's selections, since the local selections
 841                // match theirs.
 842                if Some(selection.peer_id) == editor.leader_peer_id {
 843                    continue;
 844                }
 845                let key = HoveredCursor {
 846                    replica_id: selection.replica_id,
 847                    selection_id: selection.selection.id,
 848                };
 849
 850                let is_shown =
 851                    editor.show_cursor_names || editor.hovered_cursors.contains_key(&key);
 852
 853                remote_selections
 854                    .entry(selection.replica_id)
 855                    .or_insert((selection_style, Vec::new()))
 856                    .1
 857                    .push(SelectionLayout::new(
 858                        selection.selection,
 859                        selection.line_mode,
 860                        selection.cursor_shape,
 861                        &snapshot.display_snapshot,
 862                        false,
 863                        false,
 864                        if is_shown { selection.user_name } else { None },
 865                    ));
 866            }
 867
 868            selections.extend(remote_selections.into_values());
 869        } else if !editor.is_focused(cx) && editor.show_cursor_when_unfocused {
 870            let player = if editor.read_only(cx) {
 871                cx.theme().players().read_only()
 872            } else {
 873                self.style.local_player
 874            };
 875            let layouts = snapshot
 876                .buffer_snapshot
 877                .selections_in_range(&(start_anchor..end_anchor), true)
 878                .map(move |(_, line_mode, cursor_shape, selection)| {
 879                    SelectionLayout::new(
 880                        selection,
 881                        line_mode,
 882                        cursor_shape,
 883                        &snapshot.display_snapshot,
 884                        false,
 885                        false,
 886                        None,
 887                    )
 888                })
 889                .collect::<Vec<_>>();
 890            selections.push((player, layouts));
 891        }
 892        (selections, active_rows, newest_selection_head)
 893    }
 894
 895    fn collect_cursors(
 896        &self,
 897        snapshot: &EditorSnapshot,
 898        cx: &mut WindowContext,
 899    ) -> Vec<(DisplayPoint, Hsla)> {
 900        let editor = self.editor.read(cx);
 901        let mut cursors = Vec::new();
 902        let mut skip_local = false;
 903        let mut add_cursor = |anchor: Anchor, color| {
 904            cursors.push((anchor.to_display_point(&snapshot.display_snapshot), color));
 905        };
 906        // Remote cursors
 907        if let Some(collaboration_hub) = &editor.collaboration_hub {
 908            for remote_selection in snapshot.remote_selections_in_range(
 909                &(Anchor::min()..Anchor::max()),
 910                collaboration_hub.deref(),
 911                cx,
 912            ) {
 913                let color = Self::get_participant_color(remote_selection.participant_index, cx);
 914                add_cursor(remote_selection.selection.head(), color.cursor);
 915                if Some(remote_selection.peer_id) == editor.leader_peer_id {
 916                    skip_local = true;
 917                }
 918            }
 919        }
 920        // Local cursors
 921        if !skip_local {
 922            let color = cx.theme().players().local().cursor;
 923            editor.selections.disjoint.iter().for_each(|selection| {
 924                add_cursor(selection.head(), color);
 925            });
 926            if let Some(ref selection) = editor.selections.pending_anchor() {
 927                add_cursor(selection.head(), color);
 928            }
 929        }
 930        cursors
 931    }
 932
 933    #[allow(clippy::too_many_arguments)]
 934    fn layout_visible_cursors(
 935        &self,
 936        snapshot: &EditorSnapshot,
 937        selections: &[(PlayerColor, Vec<SelectionLayout>)],
 938        visible_display_row_range: Range<DisplayRow>,
 939        line_layouts: &[LineWithInvisibles],
 940        text_hitbox: &Hitbox,
 941        content_origin: gpui::Point<Pixels>,
 942        scroll_position: gpui::Point<f32>,
 943        scroll_pixel_position: gpui::Point<Pixels>,
 944        line_height: Pixels,
 945        em_width: Pixels,
 946        autoscroll_containing_element: bool,
 947        cx: &mut WindowContext,
 948    ) -> Vec<CursorLayout> {
 949        let mut autoscroll_bounds = None;
 950        let cursor_layouts = self.editor.update(cx, |editor, cx| {
 951            let mut cursors = Vec::new();
 952            for (player_color, selections) in selections {
 953                for selection in selections {
 954                    let cursor_position = selection.head;
 955
 956                    let in_range = visible_display_row_range.contains(&cursor_position.row());
 957                    if (selection.is_local && !editor.show_local_cursors(cx)) || !in_range {
 958                        continue;
 959                    }
 960
 961                    let cursor_row_layout = &line_layouts
 962                        [cursor_position.row().minus(visible_display_row_range.start) as usize];
 963                    let cursor_column = cursor_position.column() as usize;
 964
 965                    let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 966                    let mut block_width =
 967                        cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
 968                    if block_width == Pixels::ZERO {
 969                        block_width = em_width;
 970                    }
 971                    let block_text = if let CursorShape::Block = selection.cursor_shape {
 972                        snapshot.display_chars_at(cursor_position).next().and_then(
 973                            |(character, _)| {
 974                                let text = if character == '\n' {
 975                                    SharedString::from(" ")
 976                                } else {
 977                                    SharedString::from(character.to_string())
 978                                };
 979                                let len = text.len();
 980
 981                                let font = cursor_row_layout
 982                                    .font_id_for_index(cursor_column)
 983                                    .and_then(|cursor_font_id| {
 984                                        cx.text_system().get_font_for_id(cursor_font_id)
 985                                    })
 986                                    .unwrap_or(self.style.text.font());
 987
 988                                cx.text_system()
 989                                    .shape_line(
 990                                        text,
 991                                        cursor_row_layout.font_size,
 992                                        &[TextRun {
 993                                            len,
 994                                            font,
 995                                            color: self.style.background,
 996                                            background_color: None,
 997                                            strikethrough: None,
 998                                            underline: None,
 999                                        }],
1000                                    )
1001                                    .log_err()
1002                            },
1003                        )
1004                    } else {
1005                        None
1006                    };
1007
1008                    let x = cursor_character_x - scroll_pixel_position.x;
1009                    let y = (cursor_position.row().as_f32()
1010                        - scroll_pixel_position.y / line_height)
1011                        * line_height;
1012                    if selection.is_newest {
1013                        editor.pixel_position_of_newest_cursor = Some(point(
1014                            text_hitbox.origin.x + x + block_width / 2.,
1015                            text_hitbox.origin.y + y + line_height / 2.,
1016                        ));
1017
1018                        if autoscroll_containing_element {
1019                            let top = text_hitbox.origin.y
1020                                + (cursor_position.row().as_f32() - scroll_position.y - 3.).max(0.)
1021                                    * line_height;
1022                            let left = text_hitbox.origin.x
1023                                + (cursor_position.column() as f32 - scroll_position.x - 3.)
1024                                    .max(0.)
1025                                    * em_width;
1026
1027                            let bottom = text_hitbox.origin.y
1028                                + (cursor_position.row().as_f32() - scroll_position.y + 4.)
1029                                    * line_height;
1030                            let right = text_hitbox.origin.x
1031                                + (cursor_position.column() as f32 - scroll_position.x + 4.)
1032                                    * em_width;
1033
1034                            autoscroll_bounds =
1035                                Some(Bounds::from_corners(point(left, top), point(right, bottom)))
1036                        }
1037                    }
1038
1039                    let mut cursor = CursorLayout {
1040                        color: player_color.cursor,
1041                        block_width,
1042                        origin: point(x, y),
1043                        line_height,
1044                        shape: selection.cursor_shape,
1045                        block_text,
1046                        cursor_name: None,
1047                    };
1048                    let cursor_name = selection.user_name.clone().map(|name| CursorName {
1049                        string: name,
1050                        color: self.style.background,
1051                        is_top_row: cursor_position.row().0 == 0,
1052                    });
1053                    cursor.layout(content_origin, cursor_name, cx);
1054                    cursors.push(cursor);
1055                }
1056            }
1057            cursors
1058        });
1059
1060        if let Some(bounds) = autoscroll_bounds {
1061            cx.request_autoscroll(bounds);
1062        }
1063
1064        cursor_layouts
1065    }
1066
1067    fn layout_scrollbar(
1068        &self,
1069        snapshot: &EditorSnapshot,
1070        bounds: Bounds<Pixels>,
1071        scroll_position: gpui::Point<f32>,
1072        rows_per_page: f32,
1073        non_visible_cursors: bool,
1074        cx: &mut WindowContext,
1075    ) -> Option<ScrollbarLayout> {
1076        let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
1077        let show_scrollbars = match scrollbar_settings.show {
1078            ShowScrollbar::Auto => {
1079                let editor = self.editor.read(cx);
1080                let is_singleton = editor.is_singleton(cx);
1081                // Git
1082                (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_git_diffs())
1083                    ||
1084                    // Buffer Search Results
1085                    (is_singleton && scrollbar_settings.search_results && editor.has_background_highlights::<BufferSearchHighlights>())
1086                    ||
1087                    // Selected Symbol Occurrences
1088                    (is_singleton && scrollbar_settings.selected_symbol && (editor.has_background_highlights::<DocumentHighlightRead>() || editor.has_background_highlights::<DocumentHighlightWrite>()))
1089                    ||
1090                    // Diagnostics
1091                    (is_singleton && scrollbar_settings.diagnostics && snapshot.buffer_snapshot.has_diagnostics())
1092                    ||
1093                    // Cursors out of sight
1094                    non_visible_cursors
1095                    ||
1096                    // Scrollmanager
1097                    editor.scroll_manager.scrollbars_visible()
1098            }
1099            ShowScrollbar::System => self.editor.read(cx).scroll_manager.scrollbars_visible(),
1100            ShowScrollbar::Always => true,
1101            ShowScrollbar::Never => false,
1102        };
1103        if snapshot.mode != EditorMode::Full {
1104            return None;
1105        }
1106
1107        let visible_row_range = scroll_position.y..scroll_position.y + rows_per_page;
1108
1109        // If a drag took place after we started dragging the scrollbar,
1110        // cancel the scrollbar drag.
1111        if cx.has_active_drag() {
1112            self.editor.update(cx, |editor, cx| {
1113                editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
1114            });
1115        }
1116
1117        let track_bounds = Bounds::from_corners(
1118            point(self.scrollbar_left(&bounds), bounds.origin.y),
1119            point(bounds.lower_right().x, bounds.lower_left().y),
1120        );
1121
1122        let settings = EditorSettings::get_global(cx);
1123        let scroll_beyond_last_line: f32 = match settings.scroll_beyond_last_line {
1124            ScrollBeyondLastLine::OnePage => rows_per_page,
1125            ScrollBeyondLastLine::Off => 1.0,
1126            ScrollBeyondLastLine::VerticalScrollMargin => 1.0 + settings.vertical_scroll_margin,
1127        };
1128        let total_rows =
1129            (snapshot.max_point().row().as_f32() + scroll_beyond_last_line).max(rows_per_page);
1130        let height = bounds.size.height;
1131        let px_per_row = height / total_rows;
1132        let thumb_height = (rows_per_page * px_per_row).max(ScrollbarLayout::MIN_THUMB_HEIGHT);
1133        let row_height = (height - thumb_height) / (total_rows - rows_per_page).max(0.);
1134
1135        Some(ScrollbarLayout {
1136            hitbox: cx.insert_hitbox(track_bounds, false),
1137            visible_row_range,
1138            row_height,
1139            visible: show_scrollbars,
1140            thumb_height,
1141        })
1142    }
1143
1144    #[allow(clippy::too_many_arguments)]
1145    fn prepaint_gutter_fold_toggles(
1146        &self,
1147        toggles: &mut [Option<AnyElement>],
1148        line_height: Pixels,
1149        gutter_dimensions: &GutterDimensions,
1150        gutter_settings: crate::editor_settings::Gutter,
1151        scroll_pixel_position: gpui::Point<Pixels>,
1152        gutter_hitbox: &Hitbox,
1153        cx: &mut WindowContext,
1154    ) {
1155        for (ix, fold_indicator) in toggles.iter_mut().enumerate() {
1156            if let Some(fold_indicator) = fold_indicator {
1157                debug_assert!(gutter_settings.folds);
1158                let available_space = size(
1159                    AvailableSpace::MinContent,
1160                    AvailableSpace::Definite(line_height * 0.55),
1161                );
1162                let fold_indicator_size = fold_indicator.layout_as_root(available_space, cx);
1163
1164                let position = point(
1165                    gutter_dimensions.width - gutter_dimensions.right_padding,
1166                    ix as f32 * line_height - (scroll_pixel_position.y % line_height),
1167                );
1168                let centering_offset = point(
1169                    (gutter_dimensions.fold_area_width() - fold_indicator_size.width) / 2.,
1170                    (line_height - fold_indicator_size.height) / 2.,
1171                );
1172                let origin = gutter_hitbox.origin + position + centering_offset;
1173                fold_indicator.prepaint_as_root(origin, available_space, cx);
1174            }
1175        }
1176    }
1177
1178    #[allow(clippy::too_many_arguments)]
1179    fn prepaint_crease_trailers(
1180        &self,
1181        trailers: Vec<Option<AnyElement>>,
1182        lines: &[LineWithInvisibles],
1183        line_height: Pixels,
1184        content_origin: gpui::Point<Pixels>,
1185        scroll_pixel_position: gpui::Point<Pixels>,
1186        em_width: Pixels,
1187        cx: &mut WindowContext,
1188    ) -> Vec<Option<CreaseTrailerLayout>> {
1189        trailers
1190            .into_iter()
1191            .enumerate()
1192            .map(|(ix, element)| {
1193                let mut element = element?;
1194                let available_space = size(
1195                    AvailableSpace::MinContent,
1196                    AvailableSpace::Definite(line_height),
1197                );
1198                let size = element.layout_as_root(available_space, cx);
1199
1200                let line = &lines[ix];
1201                let padding = if line.width == Pixels::ZERO {
1202                    Pixels::ZERO
1203                } else {
1204                    4. * em_width
1205                };
1206                let position = point(
1207                    scroll_pixel_position.x + line.width + padding,
1208                    ix as f32 * line_height - (scroll_pixel_position.y % line_height),
1209                );
1210                let centering_offset = point(px(0.), (line_height - size.height) / 2.);
1211                let origin = content_origin + position + centering_offset;
1212                element.prepaint_as_root(origin, available_space, cx);
1213                Some(CreaseTrailerLayout {
1214                    element,
1215                    bounds: Bounds::new(origin, size),
1216                })
1217            })
1218            .collect()
1219    }
1220
1221    // Folds contained in a hunk are ignored apart from shrinking visual size
1222    // If a fold contains any hunks then that fold line is marked as modified
1223    fn layout_git_gutters(
1224        &self,
1225        line_height: Pixels,
1226        gutter_hitbox: &Hitbox,
1227        display_rows: Range<DisplayRow>,
1228        snapshot: &EditorSnapshot,
1229        cx: &mut WindowContext,
1230    ) -> Vec<(DisplayDiffHunk, Option<Hitbox>)> {
1231        let buffer_snapshot = &snapshot.buffer_snapshot;
1232
1233        let buffer_start_row = MultiBufferRow(
1234            DisplayPoint::new(display_rows.start, 0)
1235                .to_point(snapshot)
1236                .row,
1237        );
1238        let buffer_end_row = MultiBufferRow(
1239            DisplayPoint::new(display_rows.end, 0)
1240                .to_point(snapshot)
1241                .row,
1242        );
1243
1244        let expanded_hunk_display_rows = self.editor.update(cx, |editor, _| {
1245            editor
1246                .expanded_hunks
1247                .hunks(false)
1248                .map(|expanded_hunk| {
1249                    let start_row = expanded_hunk
1250                        .hunk_range
1251                        .start
1252                        .to_display_point(snapshot)
1253                        .row();
1254                    let end_row = expanded_hunk
1255                        .hunk_range
1256                        .end
1257                        .to_display_point(snapshot)
1258                        .row();
1259                    (start_row, end_row)
1260                })
1261                .collect::<HashMap<_, _>>()
1262        });
1263
1264        let git_gutter_setting = ProjectSettings::get_global(cx)
1265            .git
1266            .git_gutter
1267            .unwrap_or_default();
1268        buffer_snapshot
1269            .git_diff_hunks_in_range(buffer_start_row..buffer_end_row)
1270            .map(|hunk| diff_hunk_to_display(&hunk, snapshot))
1271            .dedup()
1272            .map(|hunk| match git_gutter_setting {
1273                GitGutterSetting::TrackedFiles => {
1274                    let hitbox = if let DisplayDiffHunk::Unfolded {
1275                        display_row_range, ..
1276                    } = &hunk
1277                    {
1278                        let was_expanded = expanded_hunk_display_rows
1279                            .get(&display_row_range.start)
1280                            .map(|expanded_end_row| expanded_end_row == &display_row_range.end)
1281                            .unwrap_or(false);
1282                        if was_expanded {
1283                            None
1284                        } else {
1285                            let hunk_bounds = Self::diff_hunk_bounds(
1286                                &snapshot,
1287                                line_height,
1288                                gutter_hitbox.bounds,
1289                                &hunk,
1290                            );
1291                            Some(cx.insert_hitbox(hunk_bounds, true))
1292                        }
1293                    } else {
1294                        None
1295                    };
1296                    (hunk, hitbox)
1297                }
1298                GitGutterSetting::Hide => (hunk, None),
1299            })
1300            .collect()
1301    }
1302
1303    #[allow(clippy::too_many_arguments)]
1304    fn layout_inline_blame(
1305        &self,
1306        display_row: DisplayRow,
1307        display_snapshot: &DisplaySnapshot,
1308        line_layout: &LineWithInvisibles,
1309        crease_trailer: Option<&CreaseTrailerLayout>,
1310        em_width: Pixels,
1311        content_origin: gpui::Point<Pixels>,
1312        scroll_pixel_position: gpui::Point<Pixels>,
1313        line_height: Pixels,
1314        cx: &mut WindowContext,
1315    ) -> Option<AnyElement> {
1316        if !self
1317            .editor
1318            .update(cx, |editor, cx| editor.render_git_blame_inline(cx))
1319        {
1320            return None;
1321        }
1322
1323        let workspace = self
1324            .editor
1325            .read(cx)
1326            .workspace
1327            .as_ref()
1328            .map(|(w, _)| w.clone());
1329
1330        let display_point = DisplayPoint::new(display_row, 0);
1331        let buffer_row = MultiBufferRow(display_point.to_point(display_snapshot).row);
1332
1333        let blame = self.editor.read(cx).blame.clone()?;
1334        let blame_entry = blame
1335            .update(cx, |blame, cx| {
1336                blame.blame_for_rows([Some(buffer_row)], cx).next()
1337            })
1338            .flatten()?;
1339
1340        let mut element =
1341            render_inline_blame_entry(&blame, blame_entry, &self.style, workspace, cx);
1342
1343        let start_y = content_origin.y
1344            + line_height * (display_row.as_f32() - scroll_pixel_position.y / line_height);
1345
1346        let start_x = {
1347            const INLINE_BLAME_PADDING_EM_WIDTHS: f32 = 6.;
1348
1349            let line_end = if let Some(crease_trailer) = crease_trailer {
1350                crease_trailer.bounds.right()
1351            } else {
1352                content_origin.x - scroll_pixel_position.x + line_layout.width
1353            };
1354            let padded_line_end = line_end + em_width * INLINE_BLAME_PADDING_EM_WIDTHS;
1355
1356            let min_column_in_pixels = ProjectSettings::get_global(cx)
1357                .git
1358                .inline_blame
1359                .and_then(|settings| settings.min_column)
1360                .map(|col| self.column_pixels(col as usize, cx))
1361                .unwrap_or(px(0.));
1362            let min_start = content_origin.x - scroll_pixel_position.x + min_column_in_pixels;
1363
1364            cmp::max(padded_line_end, min_start)
1365        };
1366
1367        let absolute_offset = point(start_x, start_y);
1368        let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1369
1370        element.prepaint_as_root(absolute_offset, available_space, cx);
1371
1372        Some(element)
1373    }
1374
1375    #[allow(clippy::too_many_arguments)]
1376    fn layout_blame_entries(
1377        &self,
1378        buffer_rows: impl Iterator<Item = Option<MultiBufferRow>>,
1379        em_width: Pixels,
1380        scroll_position: gpui::Point<f32>,
1381        line_height: Pixels,
1382        gutter_hitbox: &Hitbox,
1383        max_width: Option<Pixels>,
1384        cx: &mut WindowContext,
1385    ) -> Option<Vec<AnyElement>> {
1386        if !self
1387            .editor
1388            .update(cx, |editor, cx| editor.render_git_blame_gutter(cx))
1389        {
1390            return None;
1391        }
1392
1393        let blame = self.editor.read(cx).blame.clone()?;
1394        let blamed_rows: Vec<_> = blame.update(cx, |blame, cx| {
1395            blame.blame_for_rows(buffer_rows, cx).collect()
1396        });
1397
1398        let width = if let Some(max_width) = max_width {
1399            AvailableSpace::Definite(max_width)
1400        } else {
1401            AvailableSpace::MaxContent
1402        };
1403        let scroll_top = scroll_position.y * line_height;
1404        let start_x = em_width * 1;
1405
1406        let mut last_used_color: Option<(PlayerColor, Oid)> = None;
1407
1408        let shaped_lines = blamed_rows
1409            .into_iter()
1410            .enumerate()
1411            .flat_map(|(ix, blame_entry)| {
1412                if let Some(blame_entry) = blame_entry {
1413                    let mut element = render_blame_entry(
1414                        ix,
1415                        &blame,
1416                        blame_entry,
1417                        &self.style,
1418                        &mut last_used_color,
1419                        self.editor.clone(),
1420                        cx,
1421                    );
1422
1423                    let start_y = ix as f32 * line_height - (scroll_top % line_height);
1424                    let absolute_offset = gutter_hitbox.origin + point(start_x, start_y);
1425
1426                    element.prepaint_as_root(
1427                        absolute_offset,
1428                        size(width, AvailableSpace::MinContent),
1429                        cx,
1430                    );
1431
1432                    Some(element)
1433                } else {
1434                    None
1435                }
1436            })
1437            .collect();
1438
1439        Some(shaped_lines)
1440    }
1441
1442    #[allow(clippy::too_many_arguments)]
1443    fn layout_indent_guides(
1444        &self,
1445        content_origin: gpui::Point<Pixels>,
1446        text_origin: gpui::Point<Pixels>,
1447        visible_buffer_range: Range<MultiBufferRow>,
1448        scroll_pixel_position: gpui::Point<Pixels>,
1449        line_height: Pixels,
1450        snapshot: &DisplaySnapshot,
1451        cx: &mut WindowContext,
1452    ) -> Option<Vec<IndentGuideLayout>> {
1453        let indent_guides = self.editor.update(cx, |editor, cx| {
1454            editor.indent_guides(visible_buffer_range, snapshot, cx)
1455        })?;
1456
1457        let active_indent_guide_indices = self.editor.update(cx, |editor, cx| {
1458            editor
1459                .find_active_indent_guide_indices(&indent_guides, snapshot, cx)
1460                .unwrap_or_default()
1461        });
1462
1463        Some(
1464            indent_guides
1465                .into_iter()
1466                .enumerate()
1467                .filter_map(|(i, indent_guide)| {
1468                    let single_indent_width =
1469                        self.column_pixels(indent_guide.tab_size as usize, cx);
1470                    let total_width = single_indent_width * indent_guide.depth as f32;
1471                    let start_x = content_origin.x + total_width - scroll_pixel_position.x;
1472                    if start_x >= text_origin.x {
1473                        let (offset_y, length) = Self::calculate_indent_guide_bounds(
1474                            indent_guide.multibuffer_row_range.clone(),
1475                            line_height,
1476                            snapshot,
1477                        );
1478
1479                        let start_y = content_origin.y + offset_y - scroll_pixel_position.y;
1480
1481                        Some(IndentGuideLayout {
1482                            origin: point(start_x, start_y),
1483                            length,
1484                            single_indent_width,
1485                            depth: indent_guide.depth,
1486                            active: active_indent_guide_indices.contains(&i),
1487                            settings: indent_guide.settings,
1488                        })
1489                    } else {
1490                        None
1491                    }
1492                })
1493                .collect(),
1494        )
1495    }
1496
1497    fn calculate_indent_guide_bounds(
1498        row_range: Range<MultiBufferRow>,
1499        line_height: Pixels,
1500        snapshot: &DisplaySnapshot,
1501    ) -> (gpui::Pixels, gpui::Pixels) {
1502        let start_point = Point::new(row_range.start.0, 0);
1503        let end_point = Point::new(row_range.end.0, 0);
1504
1505        let row_range = start_point.to_display_point(snapshot).row()
1506            ..end_point.to_display_point(snapshot).row();
1507
1508        let mut prev_line = start_point;
1509        prev_line.row = prev_line.row.saturating_sub(1);
1510        let prev_line = prev_line.to_display_point(snapshot).row();
1511
1512        let mut cons_line = end_point;
1513        cons_line.row += 1;
1514        let cons_line = cons_line.to_display_point(snapshot).row();
1515
1516        let mut offset_y = row_range.start.0 as f32 * line_height;
1517        let mut length = (cons_line.0.saturating_sub(row_range.start.0)) as f32 * line_height;
1518
1519        // If we are at the end of the buffer, ensure that the indent guide extends to the end of the line.
1520        if row_range.end == cons_line {
1521            length += line_height;
1522        }
1523
1524        // If there is a block (e.g. diagnostic) in between the start of the indent guide and the line above,
1525        // we want to extend the indent guide to the start of the block.
1526        let mut block_height = 0;
1527        let mut block_offset = 0;
1528        let mut found_excerpt_header = false;
1529        for (_, block) in snapshot.blocks_in_range(prev_line..row_range.start) {
1530            if matches!(block, TransformBlock::ExcerptHeader { .. }) {
1531                found_excerpt_header = true;
1532                break;
1533            }
1534            block_offset += block.height();
1535            block_height += block.height();
1536        }
1537        if !found_excerpt_header {
1538            offset_y -= block_offset as f32 * line_height;
1539            length += block_height as f32 * line_height;
1540        }
1541
1542        // If there is a block (e.g. diagnostic) at the end of an multibuffer excerpt,
1543        // we want to ensure that the indent guide stops before the excerpt header.
1544        let mut block_height = 0;
1545        let mut found_excerpt_header = false;
1546        for (_, block) in snapshot.blocks_in_range(row_range.end..cons_line) {
1547            if matches!(block, TransformBlock::ExcerptHeader { .. }) {
1548                found_excerpt_header = true;
1549            }
1550            block_height += block.height();
1551        }
1552        if found_excerpt_header {
1553            length -= block_height as f32 * line_height;
1554        }
1555
1556        (offset_y, length)
1557    }
1558
1559    fn layout_run_indicators(
1560        &self,
1561        line_height: Pixels,
1562        scroll_pixel_position: gpui::Point<Pixels>,
1563        gutter_dimensions: &GutterDimensions,
1564        gutter_hitbox: &Hitbox,
1565        snapshot: &EditorSnapshot,
1566        cx: &mut WindowContext,
1567    ) -> Vec<AnyElement> {
1568        self.editor.update(cx, |editor, cx| {
1569            let active_task_indicator_row =
1570                if let Some(crate::ContextMenu::CodeActions(CodeActionsMenu {
1571                    deployed_from_indicator,
1572                    actions,
1573                    ..
1574                })) = editor.context_menu.read().as_ref()
1575                {
1576                    actions
1577                        .tasks
1578                        .as_ref()
1579                        .map(|tasks| tasks.position.to_display_point(snapshot).row())
1580                        .or_else(|| *deployed_from_indicator)
1581                } else {
1582                    None
1583                };
1584            editor
1585                .tasks
1586                .iter()
1587                .filter_map(|(_, tasks)| {
1588                    let multibuffer_point = tasks.offset.0.to_point(&snapshot.buffer_snapshot);
1589                    let multibuffer_row = MultiBufferRow(multibuffer_point.row);
1590                    if snapshot.is_line_folded(multibuffer_row) {
1591                        return None;
1592                    }
1593                    let display_row = multibuffer_point.to_display_point(snapshot).row();
1594                    let button = editor.render_run_indicator(
1595                        &self.style,
1596                        Some(display_row) == active_task_indicator_row,
1597                        display_row,
1598                        cx,
1599                    );
1600
1601                    let button = prepaint_gutter_button(
1602                        button,
1603                        display_row,
1604                        line_height,
1605                        gutter_dimensions,
1606                        scroll_pixel_position,
1607                        gutter_hitbox,
1608                        cx,
1609                    );
1610                    Some(button)
1611                })
1612                .collect_vec()
1613        })
1614    }
1615
1616    fn layout_code_actions_indicator(
1617        &self,
1618        line_height: Pixels,
1619        newest_selection_head: DisplayPoint,
1620        scroll_pixel_position: gpui::Point<Pixels>,
1621        gutter_dimensions: &GutterDimensions,
1622        gutter_hitbox: &Hitbox,
1623        cx: &mut WindowContext,
1624    ) -> Option<AnyElement> {
1625        let mut active = false;
1626        let mut button = None;
1627        let row = newest_selection_head.row();
1628        self.editor.update(cx, |editor, cx| {
1629            if let Some(crate::ContextMenu::CodeActions(CodeActionsMenu {
1630                deployed_from_indicator,
1631                ..
1632            })) = editor.context_menu.read().as_ref()
1633            {
1634                active = deployed_from_indicator.map_or(true, |indicator_row| indicator_row == row);
1635            };
1636            button = editor.render_code_actions_indicator(&self.style, row, active, cx);
1637        });
1638
1639        let button = prepaint_gutter_button(
1640            button?,
1641            row,
1642            line_height,
1643            gutter_dimensions,
1644            scroll_pixel_position,
1645            gutter_hitbox,
1646            cx,
1647        );
1648
1649        Some(button)
1650    }
1651
1652    fn get_participant_color(
1653        participant_index: Option<ParticipantIndex>,
1654        cx: &WindowContext,
1655    ) -> PlayerColor {
1656        if let Some(index) = participant_index {
1657            cx.theme().players().color_for_participant(index.0)
1658        } else {
1659            cx.theme().players().absent()
1660        }
1661    }
1662
1663    fn calculate_relative_line_numbers(
1664        &self,
1665        snapshot: &EditorSnapshot,
1666        rows: &Range<DisplayRow>,
1667        relative_to: Option<DisplayRow>,
1668    ) -> HashMap<DisplayRow, DisplayRowDelta> {
1669        let mut relative_rows: HashMap<DisplayRow, DisplayRowDelta> = Default::default();
1670        let Some(relative_to) = relative_to else {
1671            return relative_rows;
1672        };
1673
1674        let start = rows.start.min(relative_to);
1675        let end = rows.end.max(relative_to);
1676
1677        let buffer_rows = snapshot
1678            .buffer_rows(start)
1679            .take(1 + end.minus(start) as usize)
1680            .collect::<Vec<_>>();
1681
1682        let head_idx = relative_to.minus(start);
1683        let mut delta = 1;
1684        let mut i = head_idx + 1;
1685        while i < buffer_rows.len() as u32 {
1686            if buffer_rows[i as usize].is_some() {
1687                if rows.contains(&DisplayRow(i + start.0)) {
1688                    relative_rows.insert(DisplayRow(i + start.0), delta);
1689                }
1690                delta += 1;
1691            }
1692            i += 1;
1693        }
1694        delta = 1;
1695        i = head_idx.min(buffer_rows.len() as u32 - 1);
1696        while i > 0 && buffer_rows[i as usize].is_none() {
1697            i -= 1;
1698        }
1699
1700        while i > 0 {
1701            i -= 1;
1702            if buffer_rows[i as usize].is_some() {
1703                if rows.contains(&DisplayRow(i + start.0)) {
1704                    relative_rows.insert(DisplayRow(i + start.0), delta);
1705                }
1706                delta += 1;
1707            }
1708        }
1709
1710        relative_rows
1711    }
1712
1713    fn layout_line_numbers(
1714        &self,
1715        rows: Range<DisplayRow>,
1716        buffer_rows: impl Iterator<Item = Option<MultiBufferRow>>,
1717        active_rows: &BTreeMap<DisplayRow, bool>,
1718        newest_selection_head: Option<DisplayPoint>,
1719        snapshot: &EditorSnapshot,
1720        cx: &mut WindowContext,
1721    ) -> Vec<Option<ShapedLine>> {
1722        let include_line_numbers = snapshot.show_line_numbers.unwrap_or_else(|| {
1723            EditorSettings::get_global(cx).gutter.line_numbers && snapshot.mode == EditorMode::Full
1724        });
1725        if !include_line_numbers {
1726            return Vec::new();
1727        }
1728
1729        let editor = self.editor.read(cx);
1730        let newest_selection_head = newest_selection_head.unwrap_or_else(|| {
1731            let newest = editor.selections.newest::<Point>(cx);
1732            SelectionLayout::new(
1733                newest,
1734                editor.selections.line_mode,
1735                editor.cursor_shape,
1736                &snapshot.display_snapshot,
1737                true,
1738                true,
1739                None,
1740            )
1741            .head
1742        });
1743        let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1744
1745        let is_relative = EditorSettings::get_global(cx).relative_line_numbers;
1746        let relative_to = if is_relative {
1747            Some(newest_selection_head.row())
1748        } else {
1749            None
1750        };
1751        let relative_rows = self.calculate_relative_line_numbers(snapshot, &rows, relative_to);
1752        let mut line_number = String::new();
1753        buffer_rows
1754            .into_iter()
1755            .enumerate()
1756            .map(|(ix, multibuffer_row)| {
1757                let multibuffer_row = multibuffer_row?;
1758                let display_row = DisplayRow(rows.start.0 + ix as u32);
1759                let color = if active_rows.contains_key(&display_row) {
1760                    cx.theme().colors().editor_active_line_number
1761                } else {
1762                    cx.theme().colors().editor_line_number
1763                };
1764                line_number.clear();
1765                let default_number = multibuffer_row.0 + 1;
1766                let number = relative_rows
1767                    .get(&DisplayRow(ix as u32 + rows.start.0))
1768                    .unwrap_or(&default_number);
1769                write!(&mut line_number, "{number}").unwrap();
1770                let run = TextRun {
1771                    len: line_number.len(),
1772                    font: self.style.text.font(),
1773                    color,
1774                    background_color: None,
1775                    underline: None,
1776                    strikethrough: None,
1777                };
1778                let shaped_line = cx
1779                    .text_system()
1780                    .shape_line(line_number.clone().into(), font_size, &[run])
1781                    .unwrap();
1782                Some(shaped_line)
1783            })
1784            .collect()
1785    }
1786
1787    fn layout_gutter_fold_toggles(
1788        &self,
1789        rows: Range<DisplayRow>,
1790        buffer_rows: impl IntoIterator<Item = Option<MultiBufferRow>>,
1791        active_rows: &BTreeMap<DisplayRow, bool>,
1792        snapshot: &EditorSnapshot,
1793        cx: &mut WindowContext,
1794    ) -> Vec<Option<AnyElement>> {
1795        let include_fold_statuses = EditorSettings::get_global(cx).gutter.folds
1796            && snapshot.mode == EditorMode::Full
1797            && self.editor.read(cx).is_singleton(cx);
1798        if include_fold_statuses {
1799            buffer_rows
1800                .into_iter()
1801                .enumerate()
1802                .map(|(ix, row)| {
1803                    if let Some(multibuffer_row) = row {
1804                        let display_row = DisplayRow(rows.start.0 + ix as u32);
1805                        let active = active_rows.contains_key(&display_row);
1806                        snapshot.render_fold_toggle(
1807                            multibuffer_row,
1808                            active,
1809                            self.editor.clone(),
1810                            cx,
1811                        )
1812                    } else {
1813                        None
1814                    }
1815                })
1816                .collect()
1817        } else {
1818            Vec::new()
1819        }
1820    }
1821
1822    fn layout_crease_trailers(
1823        &self,
1824        buffer_rows: impl IntoIterator<Item = Option<MultiBufferRow>>,
1825        snapshot: &EditorSnapshot,
1826        cx: &mut WindowContext,
1827    ) -> Vec<Option<AnyElement>> {
1828        buffer_rows
1829            .into_iter()
1830            .map(|row| {
1831                if let Some(multibuffer_row) = row {
1832                    snapshot.render_crease_trailer(multibuffer_row, cx)
1833                } else {
1834                    None
1835                }
1836            })
1837            .collect()
1838    }
1839
1840    fn layout_lines(
1841        rows: Range<DisplayRow>,
1842        line_number_layouts: &[Option<ShapedLine>],
1843        snapshot: &EditorSnapshot,
1844        style: &EditorStyle,
1845        cx: &mut WindowContext,
1846    ) -> Vec<LineWithInvisibles> {
1847        if rows.start >= rows.end {
1848            return Vec::new();
1849        }
1850
1851        // Show the placeholder when the editor is empty
1852        if snapshot.is_empty() {
1853            let font_size = style.text.font_size.to_pixels(cx.rem_size());
1854            let placeholder_color = cx.theme().colors().text_placeholder;
1855            let placeholder_text = snapshot.placeholder_text();
1856
1857            let placeholder_lines = placeholder_text
1858                .as_ref()
1859                .map_or("", AsRef::as_ref)
1860                .split('\n')
1861                .skip(rows.start.0 as usize)
1862                .chain(iter::repeat(""))
1863                .take(rows.len());
1864            placeholder_lines
1865                .filter_map(move |line| {
1866                    let run = TextRun {
1867                        len: line.len(),
1868                        font: style.text.font(),
1869                        color: placeholder_color,
1870                        background_color: None,
1871                        underline: Default::default(),
1872                        strikethrough: None,
1873                    };
1874                    cx.text_system()
1875                        .shape_line(line.to_string().into(), font_size, &[run])
1876                        .log_err()
1877                })
1878                .map(|line| LineWithInvisibles {
1879                    width: line.width,
1880                    len: line.len,
1881                    fragments: smallvec![LineFragment::Text(line)],
1882                    invisibles: Vec::new(),
1883                    font_size,
1884                })
1885                .collect()
1886        } else {
1887            let chunks = snapshot.highlighted_chunks(rows.clone(), true, style);
1888            LineWithInvisibles::from_chunks(
1889                chunks,
1890                &style.text,
1891                MAX_LINE_LEN,
1892                rows.len(),
1893                line_number_layouts,
1894                snapshot.mode,
1895                cx,
1896            )
1897        }
1898    }
1899
1900    fn prepaint_lines(
1901        &self,
1902        start_row: DisplayRow,
1903        line_layouts: &mut [LineWithInvisibles],
1904        line_height: Pixels,
1905        scroll_pixel_position: gpui::Point<Pixels>,
1906        content_origin: gpui::Point<Pixels>,
1907        cx: &mut WindowContext,
1908    ) -> SmallVec<[AnyElement; 1]> {
1909        let mut line_elements = SmallVec::new();
1910        for (ix, line) in line_layouts.iter_mut().enumerate() {
1911            let row = start_row + DisplayRow(ix as u32);
1912            line.prepaint(
1913                line_height,
1914                scroll_pixel_position,
1915                row,
1916                content_origin,
1917                &mut line_elements,
1918                cx,
1919            );
1920        }
1921        line_elements
1922    }
1923
1924    #[allow(clippy::too_many_arguments)]
1925    fn build_blocks(
1926        &self,
1927        rows: Range<DisplayRow>,
1928        snapshot: &EditorSnapshot,
1929        hitbox: &Hitbox,
1930        text_hitbox: &Hitbox,
1931        scroll_width: &mut Pixels,
1932        gutter_dimensions: &GutterDimensions,
1933        em_width: Pixels,
1934        text_x: Pixels,
1935        line_height: Pixels,
1936        line_layouts: &[LineWithInvisibles],
1937        cx: &mut WindowContext,
1938    ) -> Vec<BlockLayout> {
1939        let mut block_id = 0;
1940        let (fixed_blocks, non_fixed_blocks) = snapshot
1941            .blocks_in_range(rows.clone())
1942            .partition::<Vec<_>, _>(|(_, block)| match block {
1943                TransformBlock::ExcerptHeader { .. } => false,
1944                TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
1945                TransformBlock::ExcerptFooter { .. } => false,
1946            });
1947
1948        let render_block = |block: &TransformBlock,
1949                            available_space: Size<AvailableSpace>,
1950                            block_id: usize,
1951                            block_row_start: DisplayRow,
1952                            cx: &mut WindowContext| {
1953            let mut element = match block {
1954                TransformBlock::Custom(block) => {
1955                    let align_to = block
1956                        .position()
1957                        .to_point(&snapshot.buffer_snapshot)
1958                        .to_display_point(snapshot);
1959                    let anchor_x = text_x
1960                        + if rows.contains(&align_to.row()) {
1961                            line_layouts[align_to.row().minus(rows.start) as usize]
1962                                .x_for_index(align_to.column() as usize)
1963                        } else {
1964                            layout_line(align_to.row(), snapshot, &self.style, cx)
1965                                .x_for_index(align_to.column() as usize)
1966                        };
1967
1968                    block.render(&mut BlockContext {
1969                        context: cx,
1970                        anchor_x,
1971                        gutter_dimensions,
1972                        line_height,
1973                        em_width,
1974                        block_id,
1975                        max_width: text_hitbox.size.width.max(*scroll_width),
1976                        editor_style: &self.style,
1977                    })
1978                }
1979
1980                TransformBlock::ExcerptHeader {
1981                    buffer,
1982                    range,
1983                    starts_new_buffer,
1984                    height,
1985                    id,
1986                    show_excerpt_controls,
1987                    ..
1988                } => {
1989                    let include_root = self
1990                        .editor
1991                        .read(cx)
1992                        .project
1993                        .as_ref()
1994                        .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
1995                        .unwrap_or_default();
1996
1997                    #[derive(Clone)]
1998                    struct JumpData {
1999                        position: Point,
2000                        anchor: text::Anchor,
2001                        path: ProjectPath,
2002                        line_offset_from_top: u32,
2003                    }
2004
2005                    let jump_data = project::File::from_dyn(buffer.file()).map(|file| {
2006                        let jump_path = ProjectPath {
2007                            worktree_id: file.worktree_id(cx),
2008                            path: file.path.clone(),
2009                        };
2010                        let jump_anchor = range
2011                            .primary
2012                            .as_ref()
2013                            .map_or(range.context.start, |primary| primary.start);
2014
2015                        let excerpt_start = range.context.start;
2016                        let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
2017                        let offset_from_excerpt_start = if jump_anchor == excerpt_start {
2018                            0
2019                        } else {
2020                            let excerpt_start_row =
2021                                language::ToPoint::to_point(&jump_anchor, buffer).row;
2022                            jump_position.row - excerpt_start_row
2023                        };
2024
2025                        let line_offset_from_top =
2026                            block_row_start.0 + *height as u32 + offset_from_excerpt_start
2027                                - snapshot
2028                                    .scroll_anchor
2029                                    .scroll_position(&snapshot.display_snapshot)
2030                                    .y as u32;
2031
2032                        JumpData {
2033                            position: jump_position,
2034                            anchor: jump_anchor,
2035                            path: jump_path,
2036                            line_offset_from_top,
2037                        }
2038                    });
2039
2040                    let icon_offset = gutter_dimensions.width
2041                        - (gutter_dimensions.left_padding + gutter_dimensions.margin);
2042
2043                    let element = if *starts_new_buffer {
2044                        let path = buffer.resolve_file_path(cx, include_root);
2045                        let mut filename = None;
2046                        let mut parent_path = None;
2047                        // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
2048                        if let Some(path) = path {
2049                            filename = path.file_name().map(|f| f.to_string_lossy().to_string());
2050                            parent_path = path
2051                                .parent()
2052                                .map(|p| SharedString::from(p.to_string_lossy().to_string() + "/"));
2053                        }
2054
2055                        let header_padding = px(6.0);
2056
2057                        v_flex()
2058                            .id(("path excerpt header", block_id))
2059                            .size_full()
2060                            .p(header_padding)
2061                            .child(
2062                                h_flex()
2063                                    .flex_basis(Length::Definite(DefiniteLength::Fraction(0.667)))
2064                                    .id("path header block")
2065                                    .pl(gpui::px(12.))
2066                                    .pr(gpui::px(8.))
2067                                    .rounded_md()
2068                                    .shadow_md()
2069                                    .border_1()
2070                                    .border_color(cx.theme().colors().border)
2071                                    .bg(cx.theme().colors().editor_subheader_background)
2072                                    .justify_between()
2073                                    .hover(|style| style.bg(cx.theme().colors().element_hover))
2074                                    .child(
2075                                        h_flex().gap_3().child(
2076                                            h_flex()
2077                                                .gap_2()
2078                                                .child(
2079                                                    filename
2080                                                        .map(SharedString::from)
2081                                                        .unwrap_or_else(|| "untitled".into()),
2082                                                )
2083                                                .when_some(parent_path, |then, path| {
2084                                                    then.child(
2085                                                        div().child(path).text_color(
2086                                                            cx.theme().colors().text_muted,
2087                                                        ),
2088                                                    )
2089                                                }),
2090                                        ),
2091                                    )
2092                                    .when_some(jump_data.clone(), |this, jump_data| {
2093                                        this.cursor_pointer()
2094                                            .tooltip(|cx| {
2095                                                Tooltip::for_action(
2096                                                    "Jump to File",
2097                                                    &OpenExcerpts,
2098                                                    cx,
2099                                                )
2100                                            })
2101                                            .on_mouse_down(MouseButton::Left, |_, cx| {
2102                                                cx.stop_propagation()
2103                                            })
2104                                            .on_click(cx.listener_for(&self.editor, {
2105                                                move |editor, _, cx| {
2106                                                    editor.jump(
2107                                                        jump_data.path.clone(),
2108                                                        jump_data.position,
2109                                                        jump_data.anchor,
2110                                                        jump_data.line_offset_from_top,
2111                                                        cx,
2112                                                    );
2113                                                }
2114                                            }))
2115                                    }),
2116                            )
2117                            .children(show_excerpt_controls.then(|| {
2118                                h_flex()
2119                                    .flex_basis(Length::Definite(DefiniteLength::Fraction(0.333)))
2120                                    .pt_1()
2121                                    .justify_end()
2122                                    .flex_none()
2123                                    .w(icon_offset - header_padding)
2124                                    .child(
2125                                        ButtonLike::new("expand-icon")
2126                                            .style(ButtonStyle::Transparent)
2127                                            .child(
2128                                                svg()
2129                                                    .path(IconName::ArrowUpFromLine.path())
2130                                                    .size(IconSize::XSmall.rems())
2131                                                    .text_color(
2132                                                        cx.theme().colors().editor_line_number,
2133                                                    )
2134                                                    .group("")
2135                                                    .hover(|style| {
2136                                                        style.text_color(
2137                                                            cx.theme()
2138                                                                .colors()
2139                                                                .editor_active_line_number,
2140                                                        )
2141                                                    }),
2142                                            )
2143                                            .on_click(cx.listener_for(&self.editor, {
2144                                                let id = *id;
2145                                                move |editor, _, cx| {
2146                                                    editor.expand_excerpt(
2147                                                        id,
2148                                                        multi_buffer::ExpandExcerptDirection::Up,
2149                                                        cx,
2150                                                    );
2151                                                }
2152                                            }))
2153                                            .tooltip({
2154                                                move |cx| {
2155                                                    Tooltip::for_action(
2156                                                        "Expand Excerpt",
2157                                                        &ExpandExcerpts { lines: 0 },
2158                                                        cx,
2159                                                    )
2160                                                }
2161                                            }),
2162                                    )
2163                            }))
2164                    } else {
2165                        v_flex()
2166                            .id(("excerpt header", block_id))
2167                            .size_full()
2168                            .child(
2169                                div()
2170                                    .flex()
2171                                    .v_flex()
2172                                    .justify_start()
2173                                    .id("jump to collapsed context")
2174                                    .w(relative(1.0))
2175                                    .h_full()
2176                                    .child(
2177                                        div()
2178                                            .h_px()
2179                                            .w_full()
2180                                            .bg(cx.theme().colors().border_variant)
2181                                            .group_hover("excerpt-jump-action", |style| {
2182                                                style.bg(cx.theme().colors().border)
2183                                            }),
2184                                    ),
2185                            )
2186                            .child(
2187                                h_flex()
2188                                    .justify_end()
2189                                    .flex_none()
2190                                    .w(icon_offset)
2191                                    .h_full()
2192                                    .child(
2193                                        show_excerpt_controls.then(|| {
2194                                            ButtonLike::new("expand-icon")
2195                                                .style(ButtonStyle::Transparent)
2196                                                .child(
2197                                                    svg()
2198                                                        .path(IconName::ArrowUpFromLine.path())
2199                                                        .size(IconSize::XSmall.rems())
2200                                                        .text_color(
2201                                                            cx.theme().colors().editor_line_number,
2202                                                        )
2203                                                        .group("")
2204                                                        .hover(|style| {
2205                                                            style.text_color(
2206                                                                cx.theme()
2207                                                                    .colors()
2208                                                                    .editor_active_line_number,
2209                                                            )
2210                                                        }),
2211                                                )
2212                                                .on_click(cx.listener_for(&self.editor, {
2213                                                    let id = *id;
2214                                                    move |editor, _, cx| {
2215                                                        editor.expand_excerpt(
2216                                                            id,
2217                                                            multi_buffer::ExpandExcerptDirection::Up,
2218                                                            cx,
2219                                                        );
2220                                                    }
2221                                                }))
2222                                                .tooltip({
2223                                                    move |cx| {
2224                                                        Tooltip::for_action(
2225                                                            "Expand Excerpt",
2226                                                            &ExpandExcerpts { lines: 0 },
2227                                                            cx,
2228                                                        )
2229                                                    }
2230                                                })
2231                                        }).unwrap_or_else(|| {
2232                                            ButtonLike::new("jump-icon")
2233                                                .style(ButtonStyle::Transparent)
2234                                                .child(
2235                                                    svg()
2236                                                        .path(IconName::ArrowUpRight.path())
2237                                                        .size(IconSize::XSmall.rems())
2238                                                        .text_color(
2239                                                            cx.theme().colors().border_variant,
2240                                                        )
2241                                                        .group("excerpt-jump-action")
2242                                                        .group_hover("excerpt-jump-action", |style| {
2243                                                            style.text_color(
2244                                                                cx.theme().colors().border
2245
2246                                                            )
2247                                                        })
2248                                                )
2249                                                .when_some(jump_data.clone(), |this, jump_data| {
2250                                                    this.on_click(cx.listener_for(&self.editor, {
2251                                                        let path = jump_data.path.clone();
2252                                                        move |editor, _, cx| {
2253                                                            cx.stop_propagation();
2254
2255                                                            editor.jump(
2256                                                                path.clone(),
2257                                                                jump_data.position,
2258                                                                jump_data.anchor,
2259                                                                jump_data.line_offset_from_top,
2260                                                                cx,
2261                                                            );
2262                                                        }
2263                                                    }))
2264                                                    .tooltip(move |cx| {
2265                                                        Tooltip::for_action(
2266                                                            format!(
2267                                                                "Jump to {}:L{}",
2268                                                                jump_data.path.path.display(),
2269                                                                jump_data.position.row + 1
2270                                                            ),
2271                                                            &OpenExcerpts,
2272                                                            cx,
2273                                                        )
2274                                                    })
2275                                                })
2276                                        })
2277
2278                                    ),
2279                            )
2280                            .group("excerpt-jump-action")
2281                            .cursor_pointer()
2282                            .when_some(jump_data.clone(), |this, jump_data| {
2283                                this.on_click(cx.listener_for(&self.editor, {
2284                                    let path = jump_data.path.clone();
2285                                    move |editor, _, cx| {
2286                                        cx.stop_propagation();
2287
2288                                        editor.jump(
2289                                            path.clone(),
2290                                            jump_data.position,
2291                                            jump_data.anchor,
2292                                            jump_data.line_offset_from_top,
2293                                            cx,
2294                                        );
2295                                    }
2296                                }))
2297                                .tooltip(move |cx| {
2298                                    Tooltip::for_action(
2299                                        format!(
2300                                            "Jump to {}:L{}",
2301                                            jump_data.path.path.display(),
2302                                            jump_data.position.row + 1
2303                                        ),
2304                                        &OpenExcerpts,
2305                                        cx,
2306                                    )
2307                                })
2308                            })
2309                    };
2310                    element.into_any()
2311                }
2312
2313                TransformBlock::ExcerptFooter { id, .. } => {
2314                    let element = v_flex().id(("excerpt footer", block_id)).size_full().child(
2315                        h_flex()
2316                            .justify_end()
2317                            .flex_none()
2318                            .w(gutter_dimensions.width
2319                                - (gutter_dimensions.left_padding + gutter_dimensions.margin))
2320                            .h_full()
2321                            .child(
2322                                ButtonLike::new("expand-icon")
2323                                    .style(ButtonStyle::Transparent)
2324                                    .child(
2325                                        svg()
2326                                            .path(IconName::ArrowDownFromLine.path())
2327                                            .size(IconSize::XSmall.rems())
2328                                            .text_color(cx.theme().colors().editor_line_number)
2329                                            .group("")
2330                                            .hover(|style| {
2331                                                style.text_color(
2332                                                    cx.theme().colors().editor_active_line_number,
2333                                                )
2334                                            }),
2335                                    )
2336                                    .on_click(cx.listener_for(&self.editor, {
2337                                        let id = *id;
2338                                        move |editor, _, cx| {
2339                                            editor.expand_excerpt(
2340                                                id,
2341                                                multi_buffer::ExpandExcerptDirection::Down,
2342                                                cx,
2343                                            );
2344                                        }
2345                                    }))
2346                                    .tooltip({
2347                                        move |cx| {
2348                                            Tooltip::for_action(
2349                                                "Expand Excerpt",
2350                                                &ExpandExcerpts { lines: 0 },
2351                                                cx,
2352                                            )
2353                                        }
2354                                    }),
2355                            ),
2356                    );
2357                    element.into_any()
2358                }
2359            };
2360
2361            let size = element.layout_as_root(available_space, cx);
2362            (element, size)
2363        };
2364
2365        let mut fixed_block_max_width = Pixels::ZERO;
2366        let mut blocks = Vec::new();
2367        for (row, block) in fixed_blocks {
2368            let available_space = size(
2369                AvailableSpace::MinContent,
2370                AvailableSpace::Definite(block.height() as f32 * line_height),
2371            );
2372            let (element, element_size) = render_block(block, available_space, block_id, row, cx);
2373            block_id += 1;
2374            fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
2375            blocks.push(BlockLayout {
2376                row,
2377                element,
2378                available_space,
2379                style: BlockStyle::Fixed,
2380            });
2381        }
2382        for (row, block) in non_fixed_blocks {
2383            let style = match block {
2384                TransformBlock::Custom(block) => block.style(),
2385                TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
2386                TransformBlock::ExcerptFooter { .. } => BlockStyle::Sticky,
2387            };
2388            let width = match style {
2389                BlockStyle::Sticky => hitbox.size.width,
2390                BlockStyle::Flex => hitbox
2391                    .size
2392                    .width
2393                    .max(fixed_block_max_width)
2394                    .max(gutter_dimensions.width + *scroll_width),
2395                BlockStyle::Fixed => unreachable!(),
2396            };
2397            let available_space = size(
2398                AvailableSpace::Definite(width),
2399                AvailableSpace::Definite(block.height() as f32 * line_height),
2400            );
2401            let (element, _) = render_block(block, available_space, block_id, row, cx);
2402            block_id += 1;
2403            blocks.push(BlockLayout {
2404                row,
2405                element,
2406                available_space,
2407                style,
2408            });
2409        }
2410
2411        *scroll_width = (*scroll_width).max(fixed_block_max_width - gutter_dimensions.width);
2412        blocks
2413    }
2414
2415    fn layout_blocks(
2416        &self,
2417        blocks: &mut Vec<BlockLayout>,
2418        hitbox: &Hitbox,
2419        line_height: Pixels,
2420        scroll_pixel_position: gpui::Point<Pixels>,
2421        cx: &mut WindowContext,
2422    ) {
2423        for block in blocks {
2424            let mut origin = hitbox.origin
2425                + point(
2426                    Pixels::ZERO,
2427                    block.row.as_f32() * line_height - scroll_pixel_position.y,
2428                );
2429            if !matches!(block.style, BlockStyle::Sticky) {
2430                origin += point(-scroll_pixel_position.x, Pixels::ZERO);
2431            }
2432            block
2433                .element
2434                .prepaint_as_root(origin, block.available_space, cx);
2435        }
2436    }
2437
2438    #[allow(clippy::too_many_arguments)]
2439    fn layout_context_menu(
2440        &self,
2441        line_height: Pixels,
2442        hitbox: &Hitbox,
2443        text_hitbox: &Hitbox,
2444        content_origin: gpui::Point<Pixels>,
2445        start_row: DisplayRow,
2446        scroll_pixel_position: gpui::Point<Pixels>,
2447        line_layouts: &[LineWithInvisibles],
2448        newest_selection_head: DisplayPoint,
2449        gutter_overshoot: Pixels,
2450        cx: &mut WindowContext,
2451    ) -> bool {
2452        let max_height = cmp::min(
2453            12. * line_height,
2454            cmp::max(3. * line_height, (hitbox.size.height - line_height) / 2.),
2455        );
2456        let Some((position, mut context_menu)) = self.editor.update(cx, |editor, cx| {
2457            if editor.context_menu_visible() {
2458                editor.render_context_menu(newest_selection_head, &self.style, max_height, cx)
2459            } else {
2460                None
2461            }
2462        }) else {
2463            return false;
2464        };
2465
2466        let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
2467        let context_menu_size = context_menu.layout_as_root(available_space, cx);
2468
2469        let (x, y) = match position {
2470            crate::ContextMenuOrigin::EditorPoint(point) => {
2471                let cursor_row_layout = &line_layouts[point.row().minus(start_row) as usize];
2472                let x = cursor_row_layout.x_for_index(point.column() as usize)
2473                    - scroll_pixel_position.x;
2474                let y = point.row().next_row().as_f32() * line_height - scroll_pixel_position.y;
2475                (x, y)
2476            }
2477            crate::ContextMenuOrigin::GutterIndicator(row) => {
2478                // 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
2479                // text field.
2480                let x = -gutter_overshoot;
2481                let y = row.next_row().as_f32() * line_height - scroll_pixel_position.y;
2482                (x, y)
2483            }
2484        };
2485
2486        let mut list_origin = content_origin + point(x, y);
2487        let list_width = context_menu_size.width;
2488        let list_height = context_menu_size.height;
2489
2490        // Snap the right edge of the list to the right edge of the window if
2491        // its horizontal bounds overflow.
2492        if list_origin.x + list_width > cx.viewport_size().width {
2493            list_origin.x = (cx.viewport_size().width - list_width).max(Pixels::ZERO);
2494        }
2495
2496        if list_origin.y + list_height > text_hitbox.lower_right().y {
2497            list_origin.y -= line_height + list_height;
2498        }
2499
2500        cx.defer_draw(context_menu, list_origin, 1);
2501        true
2502    }
2503
2504    fn layout_mouse_context_menu(&self, cx: &mut WindowContext) -> Option<AnyElement> {
2505        let mouse_context_menu = self.editor.read(cx).mouse_context_menu.as_ref()?;
2506        let mut element = deferred(
2507            anchored()
2508                .position(mouse_context_menu.position)
2509                .child(mouse_context_menu.context_menu.clone())
2510                .anchor(AnchorCorner::TopLeft)
2511                .snap_to_window(),
2512        )
2513        .with_priority(1)
2514        .into_any();
2515
2516        element.prepaint_as_root(gpui::Point::default(), AvailableSpace::min_size(), cx);
2517        Some(element)
2518    }
2519
2520    #[allow(clippy::too_many_arguments)]
2521    fn layout_hover_popovers(
2522        &self,
2523        snapshot: &EditorSnapshot,
2524        hitbox: &Hitbox,
2525        text_hitbox: &Hitbox,
2526        visible_display_row_range: Range<DisplayRow>,
2527        content_origin: gpui::Point<Pixels>,
2528        scroll_pixel_position: gpui::Point<Pixels>,
2529        line_layouts: &[LineWithInvisibles],
2530        line_height: Pixels,
2531        em_width: Pixels,
2532        cx: &mut WindowContext,
2533    ) {
2534        struct MeasuredHoverPopover {
2535            element: AnyElement,
2536            size: Size<Pixels>,
2537            horizontal_offset: Pixels,
2538        }
2539
2540        let max_size = size(
2541            (120. * em_width) // Default size
2542                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
2543                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2544            (16. * line_height) // Default size
2545                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
2546                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2547        );
2548
2549        let hover_popovers = self.editor.update(cx, |editor, cx| {
2550            editor.hover_state.render(
2551                &snapshot,
2552                &self.style,
2553                visible_display_row_range.clone(),
2554                max_size,
2555                editor.workspace.as_ref().map(|(w, _)| w.clone()),
2556                cx,
2557            )
2558        });
2559        let Some((position, hover_popovers)) = hover_popovers else {
2560            return;
2561        };
2562
2563        let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
2564
2565        // This is safe because we check on layout whether the required row is available
2566        let hovered_row_layout =
2567            &line_layouts[position.row().minus(visible_display_row_range.start) as usize];
2568
2569        // Compute Hovered Point
2570        let x =
2571            hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
2572        let y = position.row().as_f32() * line_height - scroll_pixel_position.y;
2573        let hovered_point = content_origin + point(x, y);
2574
2575        let mut overall_height = Pixels::ZERO;
2576        let mut measured_hover_popovers = Vec::new();
2577        for mut hover_popover in hover_popovers {
2578            let size = hover_popover.layout_as_root(available_space, cx);
2579            let horizontal_offset =
2580                (text_hitbox.upper_right().x - (hovered_point.x + size.width)).min(Pixels::ZERO);
2581
2582            overall_height += HOVER_POPOVER_GAP + size.height;
2583
2584            measured_hover_popovers.push(MeasuredHoverPopover {
2585                element: hover_popover,
2586                size,
2587                horizontal_offset,
2588            });
2589        }
2590        overall_height += HOVER_POPOVER_GAP;
2591
2592        fn draw_occluder(width: Pixels, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
2593            let mut occlusion = div()
2594                .size_full()
2595                .occlude()
2596                .on_mouse_move(|_, cx| cx.stop_propagation())
2597                .into_any_element();
2598            occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), cx);
2599            cx.defer_draw(occlusion, origin, 2);
2600        }
2601
2602        if hovered_point.y > overall_height {
2603            // There is enough space above. Render popovers above the hovered point
2604            let mut current_y = hovered_point.y;
2605            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
2606                let size = popover.size;
2607                let popover_origin = point(
2608                    hovered_point.x + popover.horizontal_offset,
2609                    current_y - size.height,
2610                );
2611
2612                cx.defer_draw(popover.element, popover_origin, 2);
2613                if position != itertools::Position::Last {
2614                    let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
2615                    draw_occluder(size.width, origin, cx);
2616                }
2617
2618                current_y = popover_origin.y - HOVER_POPOVER_GAP;
2619            }
2620        } else {
2621            // There is not enough space above. Render popovers below the hovered point
2622            let mut current_y = hovered_point.y + line_height;
2623            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
2624                let size = popover.size;
2625                let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
2626
2627                cx.defer_draw(popover.element, popover_origin, 2);
2628                if position != itertools::Position::Last {
2629                    let origin = point(popover_origin.x, popover_origin.y + size.height);
2630                    draw_occluder(size.width, origin, cx);
2631                }
2632
2633                current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
2634            }
2635        }
2636    }
2637
2638    fn paint_background(&self, layout: &EditorLayout, cx: &mut WindowContext) {
2639        cx.paint_layer(layout.hitbox.bounds, |cx| {
2640            let scroll_top = layout.position_map.snapshot.scroll_position().y;
2641            let gutter_bg = cx.theme().colors().editor_gutter_background;
2642            cx.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
2643            cx.paint_quad(fill(layout.text_hitbox.bounds, self.style.background));
2644
2645            if let EditorMode::Full = layout.mode {
2646                let mut active_rows = layout.active_rows.iter().peekable();
2647                while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
2648                    let mut end_row = start_row.0;
2649                    while active_rows
2650                        .peek()
2651                        .map_or(false, |(active_row, has_selection)| {
2652                            active_row.0 == end_row + 1
2653                                && *has_selection == contains_non_empty_selection
2654                        })
2655                    {
2656                        active_rows.next().unwrap();
2657                        end_row += 1;
2658                    }
2659
2660                    if !contains_non_empty_selection {
2661                        let highlight_h_range =
2662                            match layout.position_map.snapshot.current_line_highlight {
2663                                CurrentLineHighlight::Gutter => Some(Range {
2664                                    start: layout.hitbox.left(),
2665                                    end: layout.gutter_hitbox.right(),
2666                                }),
2667                                CurrentLineHighlight::Line => Some(Range {
2668                                    start: layout.text_hitbox.bounds.left(),
2669                                    end: layout.text_hitbox.bounds.right(),
2670                                }),
2671                                CurrentLineHighlight::All => Some(Range {
2672                                    start: layout.hitbox.left(),
2673                                    end: layout.hitbox.right(),
2674                                }),
2675                                CurrentLineHighlight::None => None,
2676                            };
2677                        if let Some(range) = highlight_h_range {
2678                            let active_line_bg = cx.theme().colors().editor_active_line_background;
2679                            let bounds = Bounds {
2680                                origin: point(
2681                                    range.start,
2682                                    layout.hitbox.origin.y
2683                                        + (start_row.as_f32() - scroll_top)
2684                                            * layout.position_map.line_height,
2685                                ),
2686                                size: size(
2687                                    range.end - range.start,
2688                                    layout.position_map.line_height
2689                                        * (end_row - start_row.0 + 1) as f32,
2690                                ),
2691                            };
2692                            cx.paint_quad(fill(bounds, active_line_bg));
2693                        }
2694                    }
2695                }
2696
2697                let mut paint_highlight =
2698                    |highlight_row_start: DisplayRow, highlight_row_end: DisplayRow, color| {
2699                        let origin = point(
2700                            layout.hitbox.origin.x,
2701                            layout.hitbox.origin.y
2702                                + (highlight_row_start.as_f32() - scroll_top)
2703                                    * layout.position_map.line_height,
2704                        );
2705                        let size = size(
2706                            layout.hitbox.size.width,
2707                            layout.position_map.line_height
2708                                * highlight_row_end.next_row().minus(highlight_row_start) as f32,
2709                        );
2710                        cx.paint_quad(fill(Bounds { origin, size }, color));
2711                    };
2712
2713                let mut current_paint: Option<(Hsla, Range<DisplayRow>)> = None;
2714                for (&new_row, &new_color) in &layout.highlighted_rows {
2715                    match &mut current_paint {
2716                        Some((current_color, current_range)) => {
2717                            let current_color = *current_color;
2718                            let new_range_started = current_color != new_color
2719                                || current_range.end.next_row() != new_row;
2720                            if new_range_started {
2721                                paint_highlight(
2722                                    current_range.start,
2723                                    current_range.end,
2724                                    current_color,
2725                                );
2726                                current_paint = Some((new_color, new_row..new_row));
2727                                continue;
2728                            } else {
2729                                current_range.end = current_range.end.next_row();
2730                            }
2731                        }
2732                        None => current_paint = Some((new_color, new_row..new_row)),
2733                    };
2734                }
2735                if let Some((color, range)) = current_paint {
2736                    paint_highlight(range.start, range.end, color);
2737                }
2738
2739                let scroll_left =
2740                    layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
2741
2742                for (wrap_position, active) in layout.wrap_guides.iter() {
2743                    let x = (layout.text_hitbox.origin.x
2744                        + *wrap_position
2745                        + layout.position_map.em_width / 2.)
2746                        - scroll_left;
2747
2748                    let show_scrollbars = layout
2749                        .scrollbar_layout
2750                        .as_ref()
2751                        .map_or(false, |scrollbar| scrollbar.visible);
2752                    if x < layout.text_hitbox.origin.x
2753                        || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
2754                    {
2755                        continue;
2756                    }
2757
2758                    let color = if *active {
2759                        cx.theme().colors().editor_active_wrap_guide
2760                    } else {
2761                        cx.theme().colors().editor_wrap_guide
2762                    };
2763                    cx.paint_quad(fill(
2764                        Bounds {
2765                            origin: point(x, layout.text_hitbox.origin.y),
2766                            size: size(px(1.), layout.text_hitbox.size.height),
2767                        },
2768                        color,
2769                    ));
2770                }
2771            }
2772        })
2773    }
2774
2775    fn paint_indent_guides(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2776        let Some(indent_guides) = &layout.indent_guides else {
2777            return;
2778        };
2779
2780        let faded_color = |color: Hsla, alpha: f32| {
2781            let mut faded = color;
2782            faded.a = alpha;
2783            faded
2784        };
2785
2786        for indent_guide in indent_guides {
2787            let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
2788            let settings = indent_guide.settings;
2789
2790            // TODO fixed for now, expose them through themes later
2791            const INDENT_AWARE_ALPHA: f32 = 0.2;
2792            const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
2793            const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
2794            const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
2795
2796            let line_color = match (settings.coloring, indent_guide.active) {
2797                (IndentGuideColoring::Disabled, _) => None,
2798                (IndentGuideColoring::Fixed, false) => {
2799                    Some(cx.theme().colors().editor_indent_guide)
2800                }
2801                (IndentGuideColoring::Fixed, true) => {
2802                    Some(cx.theme().colors().editor_indent_guide_active)
2803                }
2804                (IndentGuideColoring::IndentAware, false) => {
2805                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
2806                }
2807                (IndentGuideColoring::IndentAware, true) => {
2808                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
2809                }
2810            };
2811
2812            let background_color = match (settings.background_coloring, indent_guide.active) {
2813                (IndentGuideBackgroundColoring::Disabled, _) => None,
2814                (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
2815                    indent_accent_colors,
2816                    INDENT_AWARE_BACKGROUND_ALPHA,
2817                )),
2818                (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
2819                    indent_accent_colors,
2820                    INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
2821                )),
2822            };
2823
2824            let requested_line_width = if indent_guide.active {
2825                settings.active_line_width
2826            } else {
2827                settings.line_width
2828            }
2829            .clamp(1, 10);
2830            let mut line_indicator_width = 0.;
2831            if let Some(color) = line_color {
2832                cx.paint_quad(fill(
2833                    Bounds {
2834                        origin: indent_guide.origin,
2835                        size: size(px(requested_line_width as f32), indent_guide.length),
2836                    },
2837                    color,
2838                ));
2839                line_indicator_width = requested_line_width as f32;
2840            }
2841
2842            if let Some(color) = background_color {
2843                let width = indent_guide.single_indent_width - px(line_indicator_width);
2844                cx.paint_quad(fill(
2845                    Bounds {
2846                        origin: point(
2847                            indent_guide.origin.x + px(line_indicator_width),
2848                            indent_guide.origin.y,
2849                        ),
2850                        size: size(width, indent_guide.length),
2851                    },
2852                    color,
2853                ));
2854            }
2855        }
2856    }
2857
2858    fn paint_line_numbers(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2859        let line_height = layout.position_map.line_height;
2860        let scroll_position = layout.position_map.snapshot.scroll_position();
2861        let scroll_top = scroll_position.y * line_height;
2862
2863        cx.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
2864
2865        for (ix, line) in layout.line_numbers.iter().enumerate() {
2866            if let Some(line) = line {
2867                let line_origin = layout.gutter_hitbox.origin
2868                    + point(
2869                        layout.gutter_hitbox.size.width
2870                            - line.width
2871                            - layout.gutter_dimensions.right_padding,
2872                        ix as f32 * line_height - (scroll_top % line_height),
2873                    );
2874
2875                line.paint(line_origin, line_height, cx).log_err();
2876            }
2877        }
2878    }
2879
2880    fn paint_diff_hunks(layout: &EditorLayout, cx: &mut WindowContext) {
2881        if layout.display_hunks.is_empty() {
2882            return;
2883        }
2884
2885        let line_height = layout.position_map.line_height;
2886        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2887            for (hunk, hitbox) in &layout.display_hunks {
2888                let hunk_to_paint = match hunk {
2889                    DisplayDiffHunk::Folded { .. } => {
2890                        let hunk_bounds = Self::diff_hunk_bounds(
2891                            &layout.position_map.snapshot,
2892                            line_height,
2893                            layout.gutter_hitbox.bounds,
2894                            &hunk,
2895                        );
2896                        Some((
2897                            hunk_bounds,
2898                            cx.theme().status().modified,
2899                            Corners::all(1. * line_height),
2900                        ))
2901                    }
2902                    DisplayDiffHunk::Unfolded { status, .. } => {
2903                        hitbox.as_ref().map(|hunk_hitbox| match status {
2904                            DiffHunkStatus::Added => (
2905                                hunk_hitbox.bounds,
2906                                cx.theme().status().created,
2907                                Corners::all(0.05 * line_height),
2908                            ),
2909                            DiffHunkStatus::Modified => (
2910                                hunk_hitbox.bounds,
2911                                cx.theme().status().modified,
2912                                Corners::all(0.05 * line_height),
2913                            ),
2914                            DiffHunkStatus::Removed => (
2915                                Bounds::new(
2916                                    point(
2917                                        hunk_hitbox.origin.x - hunk_hitbox.size.width,
2918                                        hunk_hitbox.origin.y,
2919                                    ),
2920                                    size(hunk_hitbox.size.width * px(2.), hunk_hitbox.size.height),
2921                                ),
2922                                cx.theme().status().deleted,
2923                                Corners::all(1. * line_height),
2924                            ),
2925                        })
2926                    }
2927                };
2928
2929                if let Some((hunk_bounds, background_color, corner_radii)) = hunk_to_paint {
2930                    cx.paint_quad(quad(
2931                        hunk_bounds,
2932                        corner_radii,
2933                        background_color,
2934                        Edges::default(),
2935                        transparent_black(),
2936                    ));
2937                }
2938            }
2939        });
2940    }
2941
2942    fn diff_hunk_bounds(
2943        snapshot: &EditorSnapshot,
2944        line_height: Pixels,
2945        bounds: Bounds<Pixels>,
2946        hunk: &DisplayDiffHunk,
2947    ) -> Bounds<Pixels> {
2948        let scroll_position = snapshot.scroll_position();
2949        let scroll_top = scroll_position.y * line_height;
2950
2951        match hunk {
2952            DisplayDiffHunk::Folded { display_row, .. } => {
2953                let start_y = display_row.as_f32() * line_height - scroll_top;
2954                let end_y = start_y + line_height;
2955
2956                let width = 0.275 * line_height;
2957                let highlight_origin = bounds.origin + point(px(0.), start_y);
2958                let highlight_size = size(width, end_y - start_y);
2959                Bounds::new(highlight_origin, highlight_size)
2960            }
2961            DisplayDiffHunk::Unfolded {
2962                display_row_range,
2963                status,
2964                ..
2965            } => match status {
2966                DiffHunkStatus::Added | DiffHunkStatus::Modified => {
2967                    let start_row = display_row_range.start;
2968                    let end_row = display_row_range.end;
2969                    // If we're in a multibuffer, row range span might include an
2970                    // excerpt header, so if we were to draw the marker straight away,
2971                    // the hunk might include the rows of that header.
2972                    // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
2973                    // Instead, we simply check whether the range we're dealing with includes
2974                    // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
2975                    let end_row_in_current_excerpt = snapshot
2976                        .blocks_in_range(start_row..end_row)
2977                        .find_map(|(start_row, block)| {
2978                            if matches!(block, TransformBlock::ExcerptHeader { .. }) {
2979                                Some(start_row)
2980                            } else {
2981                                None
2982                            }
2983                        })
2984                        .unwrap_or(end_row);
2985
2986                    let start_y = start_row.as_f32() * line_height - scroll_top;
2987                    let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
2988
2989                    let width = 0.275 * line_height;
2990                    let highlight_origin = bounds.origin + point(px(0.), start_y);
2991                    let highlight_size = size(width, end_y - start_y);
2992                    Bounds::new(highlight_origin, highlight_size)
2993                }
2994                DiffHunkStatus::Removed => {
2995                    let row = display_row_range.start;
2996
2997                    let offset = line_height / 2.;
2998                    let start_y = row.as_f32() * line_height - offset - scroll_top;
2999                    let end_y = start_y + line_height;
3000
3001                    let width = 0.35 * line_height;
3002                    let highlight_origin = bounds.origin + point(px(0.), start_y);
3003                    let highlight_size = size(width, end_y - start_y);
3004                    Bounds::new(highlight_origin, highlight_size)
3005                }
3006            },
3007        }
3008    }
3009
3010    fn paint_gutter_indicators(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3011        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3012            cx.with_element_namespace("gutter_fold_toggles", |cx| {
3013                for fold_indicator in layout.gutter_fold_toggles.iter_mut().flatten() {
3014                    fold_indicator.paint(cx);
3015                }
3016            });
3017
3018            for test_indicators in layout.test_indicators.iter_mut() {
3019                test_indicators.paint(cx);
3020            }
3021
3022            if let Some(indicator) = layout.code_actions_indicator.as_mut() {
3023                indicator.paint(cx);
3024            }
3025        });
3026    }
3027
3028    fn paint_gutter_highlights(&self, layout: &EditorLayout, cx: &mut WindowContext) {
3029        for (_, hunk_hitbox) in &layout.display_hunks {
3030            if let Some(hunk_hitbox) = hunk_hitbox {
3031                cx.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
3032            }
3033        }
3034
3035        let show_git_gutter = layout
3036            .position_map
3037            .snapshot
3038            .show_git_diff_gutter
3039            .unwrap_or_else(|| {
3040                matches!(
3041                    ProjectSettings::get_global(cx).git.git_gutter,
3042                    Some(GitGutterSetting::TrackedFiles)
3043                )
3044            });
3045        if show_git_gutter {
3046            Self::paint_diff_hunks(layout, cx)
3047        }
3048
3049        let highlight_width = 0.275 * layout.position_map.line_height;
3050        let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
3051        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3052            for (range, color) in &layout.highlighted_gutter_ranges {
3053                let start_row = if range.start.row() < layout.visible_display_row_range.start {
3054                    layout.visible_display_row_range.start - DisplayRow(1)
3055                } else {
3056                    range.start.row()
3057                };
3058                let end_row = if range.end.row() > layout.visible_display_row_range.end {
3059                    layout.visible_display_row_range.end + DisplayRow(1)
3060                } else {
3061                    range.end.row()
3062                };
3063
3064                let start_y = layout.gutter_hitbox.top()
3065                    + start_row.0 as f32 * layout.position_map.line_height
3066                    - layout.position_map.scroll_pixel_position.y;
3067                let end_y = layout.gutter_hitbox.top()
3068                    + (end_row.0 + 1) as f32 * layout.position_map.line_height
3069                    - layout.position_map.scroll_pixel_position.y;
3070                let bounds = Bounds::from_corners(
3071                    point(layout.gutter_hitbox.left(), start_y),
3072                    point(layout.gutter_hitbox.left() + highlight_width, end_y),
3073                );
3074                cx.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
3075            }
3076        });
3077    }
3078
3079    fn paint_blamed_display_rows(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3080        let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
3081            return;
3082        };
3083
3084        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3085            for mut blame_element in blamed_display_rows.into_iter() {
3086                blame_element.paint(cx);
3087            }
3088        })
3089    }
3090
3091    fn paint_text(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3092        cx.with_content_mask(
3093            Some(ContentMask {
3094                bounds: layout.text_hitbox.bounds,
3095            }),
3096            |cx| {
3097                let cursor_style = if self
3098                    .editor
3099                    .read(cx)
3100                    .hovered_link_state
3101                    .as_ref()
3102                    .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
3103                {
3104                    CursorStyle::PointingHand
3105                } else {
3106                    CursorStyle::IBeam
3107                };
3108                cx.set_cursor_style(cursor_style, &layout.text_hitbox);
3109
3110                let invisible_display_ranges = self.paint_highlights(layout, cx);
3111                self.paint_lines(&invisible_display_ranges, layout, cx);
3112                self.paint_redactions(layout, cx);
3113                self.paint_cursors(layout, cx);
3114                self.paint_inline_blame(layout, cx);
3115                cx.with_element_namespace("crease_trailers", |cx| {
3116                    for trailer in layout.crease_trailers.iter_mut().flatten() {
3117                        trailer.element.paint(cx);
3118                    }
3119                });
3120            },
3121        )
3122    }
3123
3124    fn paint_highlights(
3125        &mut self,
3126        layout: &mut EditorLayout,
3127        cx: &mut WindowContext,
3128    ) -> SmallVec<[Range<DisplayPoint>; 32]> {
3129        cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3130            let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
3131            let line_end_overshoot = 0.15 * layout.position_map.line_height;
3132            for (range, color) in &layout.highlighted_ranges {
3133                self.paint_highlighted_range(
3134                    range.clone(),
3135                    *color,
3136                    Pixels::ZERO,
3137                    line_end_overshoot,
3138                    layout,
3139                    cx,
3140                );
3141            }
3142
3143            let corner_radius = 0.15 * layout.position_map.line_height;
3144
3145            for (player_color, selections) in &layout.selections {
3146                for selection in selections.into_iter() {
3147                    self.paint_highlighted_range(
3148                        selection.range.clone(),
3149                        player_color.selection,
3150                        corner_radius,
3151                        corner_radius * 2.,
3152                        layout,
3153                        cx,
3154                    );
3155
3156                    if selection.is_local && !selection.range.is_empty() {
3157                        invisible_display_ranges.push(selection.range.clone());
3158                    }
3159                }
3160            }
3161            invisible_display_ranges
3162        })
3163    }
3164
3165    fn paint_lines(
3166        &mut self,
3167        invisible_display_ranges: &[Range<DisplayPoint>],
3168        layout: &mut EditorLayout,
3169        cx: &mut WindowContext,
3170    ) {
3171        let whitespace_setting = self
3172            .editor
3173            .read(cx)
3174            .buffer
3175            .read(cx)
3176            .settings_at(0, cx)
3177            .show_whitespaces;
3178
3179        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
3180            let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
3181            line_with_invisibles.draw(
3182                layout,
3183                row,
3184                layout.content_origin,
3185                whitespace_setting,
3186                invisible_display_ranges,
3187                cx,
3188            )
3189        }
3190
3191        for line_element in &mut layout.line_elements {
3192            line_element.paint(cx);
3193        }
3194    }
3195
3196    fn paint_redactions(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
3197        if layout.redacted_ranges.is_empty() {
3198            return;
3199        }
3200
3201        let line_end_overshoot = layout.line_end_overshoot();
3202
3203        // A softer than perfect black
3204        let redaction_color = gpui::rgb(0x0e1111);
3205
3206        cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3207            for range in layout.redacted_ranges.iter() {
3208                self.paint_highlighted_range(
3209                    range.clone(),
3210                    redaction_color.into(),
3211                    Pixels::ZERO,
3212                    line_end_overshoot,
3213                    layout,
3214                    cx,
3215                );
3216            }
3217        });
3218    }
3219
3220    fn paint_cursors(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3221        for cursor in &mut layout.visible_cursors {
3222            cursor.paint(layout.content_origin, cx);
3223        }
3224    }
3225
3226    fn paint_scrollbar(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3227        let Some(scrollbar_layout) = layout.scrollbar_layout.as_ref() else {
3228            return;
3229        };
3230
3231        let thumb_bounds = scrollbar_layout.thumb_bounds();
3232        if scrollbar_layout.visible {
3233            cx.paint_layer(scrollbar_layout.hitbox.bounds, |cx| {
3234                cx.paint_quad(quad(
3235                    scrollbar_layout.hitbox.bounds,
3236                    Corners::default(),
3237                    cx.theme().colors().scrollbar_track_background,
3238                    Edges {
3239                        top: Pixels::ZERO,
3240                        right: Pixels::ZERO,
3241                        bottom: Pixels::ZERO,
3242                        left: ScrollbarLayout::BORDER_WIDTH,
3243                    },
3244                    cx.theme().colors().scrollbar_track_border,
3245                ));
3246
3247                let fast_markers =
3248                    self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
3249                // Refresh slow scrollbar markers in the background. Below, we paint whatever markers have already been computed.
3250                self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, cx);
3251
3252                let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
3253                for marker in markers.iter().chain(&fast_markers) {
3254                    let mut marker = marker.clone();
3255                    marker.bounds.origin += scrollbar_layout.hitbox.origin;
3256                    cx.paint_quad(marker);
3257                }
3258
3259                cx.paint_quad(quad(
3260                    thumb_bounds,
3261                    Corners::default(),
3262                    cx.theme().colors().scrollbar_thumb_background,
3263                    Edges {
3264                        top: Pixels::ZERO,
3265                        right: Pixels::ZERO,
3266                        bottom: Pixels::ZERO,
3267                        left: ScrollbarLayout::BORDER_WIDTH,
3268                    },
3269                    cx.theme().colors().scrollbar_thumb_border,
3270                ));
3271            });
3272        }
3273
3274        cx.set_cursor_style(CursorStyle::Arrow, &scrollbar_layout.hitbox);
3275
3276        let row_height = scrollbar_layout.row_height;
3277        let row_range = scrollbar_layout.visible_row_range.clone();
3278
3279        cx.on_mouse_event({
3280            let editor = self.editor.clone();
3281            let hitbox = scrollbar_layout.hitbox.clone();
3282            let mut mouse_position = cx.mouse_position();
3283            move |event: &MouseMoveEvent, phase, cx| {
3284                if phase == DispatchPhase::Capture {
3285                    return;
3286                }
3287
3288                editor.update(cx, |editor, cx| {
3289                    if event.pressed_button == Some(MouseButton::Left)
3290                        && editor.scroll_manager.is_dragging_scrollbar()
3291                    {
3292                        let y = mouse_position.y;
3293                        let new_y = event.position.y;
3294                        if (hitbox.top()..hitbox.bottom()).contains(&y) {
3295                            let mut position = editor.scroll_position(cx);
3296                            position.y += (new_y - y) / row_height;
3297                            if position.y < 0.0 {
3298                                position.y = 0.0;
3299                            }
3300                            editor.set_scroll_position(position, cx);
3301                        }
3302
3303                        cx.stop_propagation();
3304                    } else {
3305                        editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
3306                        if hitbox.is_hovered(cx) {
3307                            editor.scroll_manager.show_scrollbar(cx);
3308                        }
3309                    }
3310                    mouse_position = event.position;
3311                })
3312            }
3313        });
3314
3315        if self.editor.read(cx).scroll_manager.is_dragging_scrollbar() {
3316            cx.on_mouse_event({
3317                let editor = self.editor.clone();
3318                move |_: &MouseUpEvent, phase, cx| {
3319                    if phase == DispatchPhase::Capture {
3320                        return;
3321                    }
3322
3323                    editor.update(cx, |editor, cx| {
3324                        editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
3325                        cx.stop_propagation();
3326                    });
3327                }
3328            });
3329        } else {
3330            cx.on_mouse_event({
3331                let editor = self.editor.clone();
3332                let hitbox = scrollbar_layout.hitbox.clone();
3333                move |event: &MouseDownEvent, phase, cx| {
3334                    if phase == DispatchPhase::Capture || !hitbox.is_hovered(cx) {
3335                        return;
3336                    }
3337
3338                    editor.update(cx, |editor, cx| {
3339                        editor.scroll_manager.set_is_dragging_scrollbar(true, cx);
3340
3341                        let y = event.position.y;
3342                        if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
3343                            let center_row = ((y - hitbox.top()) / row_height).round() as u32;
3344                            let top_row = center_row
3345                                .saturating_sub((row_range.end - row_range.start) as u32 / 2);
3346                            let mut position = editor.scroll_position(cx);
3347                            position.y = top_row as f32;
3348                            editor.set_scroll_position(position, cx);
3349                        } else {
3350                            editor.scroll_manager.show_scrollbar(cx);
3351                        }
3352
3353                        cx.stop_propagation();
3354                    });
3355                }
3356            });
3357        }
3358    }
3359
3360    fn collect_fast_scrollbar_markers(
3361        &self,
3362        layout: &EditorLayout,
3363        scrollbar_layout: &ScrollbarLayout,
3364        cx: &mut WindowContext,
3365    ) -> Vec<PaintQuad> {
3366        const LIMIT: usize = 100;
3367        if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
3368            return vec![];
3369        }
3370        let cursor_ranges = layout
3371            .cursors
3372            .iter()
3373            .map(|(point, color)| ColoredRange {
3374                start: point.row(),
3375                end: point.row(),
3376                color: *color,
3377            })
3378            .collect_vec();
3379        scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
3380    }
3381
3382    fn refresh_slow_scrollbar_markers(
3383        &self,
3384        layout: &EditorLayout,
3385        scrollbar_layout: &ScrollbarLayout,
3386        cx: &mut WindowContext,
3387    ) {
3388        self.editor.update(cx, |editor, cx| {
3389            if !editor.is_singleton(cx)
3390                || !editor
3391                    .scrollbar_marker_state
3392                    .should_refresh(scrollbar_layout.hitbox.size)
3393            {
3394                return;
3395            }
3396
3397            let scrollbar_layout = scrollbar_layout.clone();
3398            let background_highlights = editor.background_highlights.clone();
3399            let snapshot = layout.position_map.snapshot.clone();
3400            let theme = cx.theme().clone();
3401            let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
3402
3403            editor.scrollbar_marker_state.dirty = false;
3404            editor.scrollbar_marker_state.pending_refresh =
3405                Some(cx.spawn(|editor, mut cx| async move {
3406                    let scrollbar_size = scrollbar_layout.hitbox.size;
3407                    let scrollbar_markers = cx
3408                        .background_executor()
3409                        .spawn(async move {
3410                            let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
3411                            let mut marker_quads = Vec::new();
3412                            if scrollbar_settings.git_diff {
3413                                let marker_row_ranges = snapshot
3414                                    .buffer_snapshot
3415                                    .git_diff_hunks_in_range(
3416                                        MultiBufferRow::MIN..MultiBufferRow::MAX,
3417                                    )
3418                                    .map(|hunk| {
3419                                        let start_display_row =
3420                                            MultiBufferPoint::new(hunk.associated_range.start.0, 0)
3421                                                .to_display_point(&snapshot.display_snapshot)
3422                                                .row();
3423                                        let mut end_display_row =
3424                                            MultiBufferPoint::new(hunk.associated_range.end.0, 0)
3425                                                .to_display_point(&snapshot.display_snapshot)
3426                                                .row();
3427                                        if end_display_row != start_display_row {
3428                                            end_display_row.0 -= 1;
3429                                        }
3430                                        let color = match hunk_status(&hunk) {
3431                                            DiffHunkStatus::Added => theme.status().created,
3432                                            DiffHunkStatus::Modified => theme.status().modified,
3433                                            DiffHunkStatus::Removed => theme.status().deleted,
3434                                        };
3435                                        ColoredRange {
3436                                            start: start_display_row,
3437                                            end: end_display_row,
3438                                            color,
3439                                        }
3440                                    });
3441
3442                                marker_quads.extend(
3443                                    scrollbar_layout
3444                                        .marker_quads_for_ranges(marker_row_ranges, Some(0)),
3445                                );
3446                            }
3447
3448                            for (background_highlight_id, (_, background_ranges)) in
3449                                background_highlights.iter()
3450                            {
3451                                let is_search_highlights = *background_highlight_id
3452                                    == TypeId::of::<BufferSearchHighlights>();
3453                                let is_symbol_occurrences = *background_highlight_id
3454                                    == TypeId::of::<DocumentHighlightRead>()
3455                                    || *background_highlight_id
3456                                        == TypeId::of::<DocumentHighlightWrite>();
3457                                if (is_search_highlights && scrollbar_settings.search_results)
3458                                    || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
3459                                {
3460                                    let mut color = theme.status().info;
3461                                    if is_symbol_occurrences {
3462                                        color.fade_out(0.5);
3463                                    }
3464                                    let marker_row_ranges =
3465                                        background_ranges.into_iter().map(|range| {
3466                                            let display_start = range
3467                                                .start
3468                                                .to_display_point(&snapshot.display_snapshot);
3469                                            let display_end = range
3470                                                .end
3471                                                .to_display_point(&snapshot.display_snapshot);
3472                                            ColoredRange {
3473                                                start: display_start.row(),
3474                                                end: display_end.row(),
3475                                                color,
3476                                            }
3477                                        });
3478                                    marker_quads.extend(
3479                                        scrollbar_layout
3480                                            .marker_quads_for_ranges(marker_row_ranges, Some(1)),
3481                                    );
3482                                }
3483                            }
3484
3485                            if scrollbar_settings.diagnostics {
3486                                let diagnostics = snapshot
3487                                    .buffer_snapshot
3488                                    .diagnostics_in_range::<_, Point>(
3489                                        Point::zero()..max_point,
3490                                        false,
3491                                    )
3492                                    // We want to sort by severity, in order to paint the most severe diagnostics last.
3493                                    .sorted_by_key(|diagnostic| {
3494                                        std::cmp::Reverse(diagnostic.diagnostic.severity)
3495                                    });
3496
3497                                let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
3498                                    let start_display = diagnostic
3499                                        .range
3500                                        .start
3501                                        .to_display_point(&snapshot.display_snapshot);
3502                                    let end_display = diagnostic
3503                                        .range
3504                                        .end
3505                                        .to_display_point(&snapshot.display_snapshot);
3506                                    let color = match diagnostic.diagnostic.severity {
3507                                        DiagnosticSeverity::ERROR => theme.status().error,
3508                                        DiagnosticSeverity::WARNING => theme.status().warning,
3509                                        DiagnosticSeverity::INFORMATION => theme.status().info,
3510                                        _ => theme.status().hint,
3511                                    };
3512                                    ColoredRange {
3513                                        start: start_display.row(),
3514                                        end: end_display.row(),
3515                                        color,
3516                                    }
3517                                });
3518                                marker_quads.extend(
3519                                    scrollbar_layout
3520                                        .marker_quads_for_ranges(marker_row_ranges, Some(2)),
3521                                );
3522                            }
3523
3524                            Arc::from(marker_quads)
3525                        })
3526                        .await;
3527
3528                    editor.update(&mut cx, |editor, cx| {
3529                        editor.scrollbar_marker_state.markers = scrollbar_markers;
3530                        editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
3531                        editor.scrollbar_marker_state.pending_refresh = None;
3532                        cx.notify();
3533                    })?;
3534
3535                    Ok(())
3536                }));
3537        });
3538    }
3539
3540    #[allow(clippy::too_many_arguments)]
3541    fn paint_highlighted_range(
3542        &self,
3543        range: Range<DisplayPoint>,
3544        color: Hsla,
3545        corner_radius: Pixels,
3546        line_end_overshoot: Pixels,
3547        layout: &EditorLayout,
3548        cx: &mut WindowContext,
3549    ) {
3550        let start_row = layout.visible_display_row_range.start;
3551        let end_row = layout.visible_display_row_range.end;
3552        if range.start != range.end {
3553            let row_range = if range.end.column() == 0 {
3554                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
3555            } else {
3556                cmp::max(range.start.row(), start_row)
3557                    ..cmp::min(range.end.row().next_row(), end_row)
3558            };
3559
3560            let highlighted_range = HighlightedRange {
3561                color,
3562                line_height: layout.position_map.line_height,
3563                corner_radius,
3564                start_y: layout.content_origin.y
3565                    + row_range.start.as_f32() * layout.position_map.line_height
3566                    - layout.position_map.scroll_pixel_position.y,
3567                lines: row_range
3568                    .iter_rows()
3569                    .map(|row| {
3570                        let line_layout =
3571                            &layout.position_map.line_layouts[row.minus(start_row) as usize];
3572                        HighlightedRangeLine {
3573                            start_x: if row == range.start.row() {
3574                                layout.content_origin.x
3575                                    + line_layout.x_for_index(range.start.column() as usize)
3576                                    - layout.position_map.scroll_pixel_position.x
3577                            } else {
3578                                layout.content_origin.x
3579                                    - layout.position_map.scroll_pixel_position.x
3580                            },
3581                            end_x: if row == range.end.row() {
3582                                layout.content_origin.x
3583                                    + line_layout.x_for_index(range.end.column() as usize)
3584                                    - layout.position_map.scroll_pixel_position.x
3585                            } else {
3586                                layout.content_origin.x + line_layout.width + line_end_overshoot
3587                                    - layout.position_map.scroll_pixel_position.x
3588                            },
3589                        }
3590                    })
3591                    .collect(),
3592            };
3593
3594            highlighted_range.paint(layout.text_hitbox.bounds, cx);
3595        }
3596    }
3597
3598    fn paint_inline_blame(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3599        if let Some(mut inline_blame) = layout.inline_blame.take() {
3600            cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3601                inline_blame.paint(cx);
3602            })
3603        }
3604    }
3605
3606    fn paint_blocks(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3607        for mut block in layout.blocks.drain(..) {
3608            block.element.paint(cx);
3609        }
3610    }
3611
3612    fn paint_mouse_context_menu(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3613        if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
3614            mouse_context_menu.paint(cx);
3615        }
3616    }
3617
3618    fn paint_scroll_wheel_listener(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
3619        cx.on_mouse_event({
3620            let position_map = layout.position_map.clone();
3621            let editor = self.editor.clone();
3622            let hitbox = layout.hitbox.clone();
3623            let mut delta = ScrollDelta::default();
3624
3625            // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
3626            // accidentally turn off their scrolling.
3627            let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
3628
3629            move |event: &ScrollWheelEvent, phase, cx| {
3630                if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
3631                    delta = delta.coalesce(event.delta);
3632                    editor.update(cx, |editor, cx| {
3633                        let position_map: &PositionMap = &position_map;
3634
3635                        let line_height = position_map.line_height;
3636                        let max_glyph_width = position_map.em_width;
3637                        let (delta, axis) = match delta {
3638                            gpui::ScrollDelta::Pixels(mut pixels) => {
3639                                //Trackpad
3640                                let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
3641                                (pixels, axis)
3642                            }
3643
3644                            gpui::ScrollDelta::Lines(lines) => {
3645                                //Not trackpad
3646                                let pixels =
3647                                    point(lines.x * max_glyph_width, lines.y * line_height);
3648                                (pixels, None)
3649                            }
3650                        };
3651
3652                        let current_scroll_position = position_map.snapshot.scroll_position();
3653                        let x = (current_scroll_position.x * max_glyph_width
3654                            - (delta.x * scroll_sensitivity))
3655                            / max_glyph_width;
3656                        let y = (current_scroll_position.y * line_height
3657                            - (delta.y * scroll_sensitivity))
3658                            / line_height;
3659                        let mut scroll_position =
3660                            point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
3661                        let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
3662                        if forbid_vertical_scroll {
3663                            scroll_position.y = current_scroll_position.y;
3664                        }
3665
3666                        if scroll_position != current_scroll_position {
3667                            editor.scroll(scroll_position, axis, cx);
3668                            cx.stop_propagation();
3669                        } else if y < 0. {
3670                            // Due to clamping, we may fail to detect cases of overscroll to the top;
3671                            // We want the scroll manager to get an update in such cases and detect the change of direction
3672                            // on the next frame.
3673                            cx.notify();
3674                        }
3675                    });
3676                }
3677            }
3678        });
3679    }
3680
3681    fn paint_mouse_listeners(
3682        &mut self,
3683        layout: &EditorLayout,
3684        hovered_hunk: Option<HunkToExpand>,
3685        cx: &mut WindowContext,
3686    ) {
3687        self.paint_scroll_wheel_listener(layout, cx);
3688
3689        cx.on_mouse_event({
3690            let position_map = layout.position_map.clone();
3691            let editor = self.editor.clone();
3692            let text_hitbox = layout.text_hitbox.clone();
3693            let gutter_hitbox = layout.gutter_hitbox.clone();
3694
3695            move |event: &MouseDownEvent, phase, cx| {
3696                if phase == DispatchPhase::Bubble {
3697                    match event.button {
3698                        MouseButton::Left => editor.update(cx, |editor, cx| {
3699                            Self::mouse_left_down(
3700                                editor,
3701                                event,
3702                                hovered_hunk.as_ref(),
3703                                &position_map,
3704                                &text_hitbox,
3705                                &gutter_hitbox,
3706                                cx,
3707                            );
3708                        }),
3709                        MouseButton::Right => editor.update(cx, |editor, cx| {
3710                            Self::mouse_right_down(editor, event, &position_map, &text_hitbox, cx);
3711                        }),
3712                        MouseButton::Middle => editor.update(cx, |editor, cx| {
3713                            Self::mouse_middle_down(editor, event, &position_map, &text_hitbox, cx);
3714                        }),
3715                        _ => {}
3716                    };
3717                }
3718            }
3719        });
3720
3721        cx.on_mouse_event({
3722            let editor = self.editor.clone();
3723            let position_map = layout.position_map.clone();
3724            let text_hitbox = layout.text_hitbox.clone();
3725
3726            move |event: &MouseUpEvent, phase, cx| {
3727                if phase == DispatchPhase::Bubble {
3728                    editor.update(cx, |editor, cx| {
3729                        Self::mouse_up(editor, event, &position_map, &text_hitbox, cx)
3730                    });
3731                }
3732            }
3733        });
3734        cx.on_mouse_event({
3735            let position_map = layout.position_map.clone();
3736            let editor = self.editor.clone();
3737            let text_hitbox = layout.text_hitbox.clone();
3738            let gutter_hitbox = layout.gutter_hitbox.clone();
3739
3740            move |event: &MouseMoveEvent, phase, cx| {
3741                if phase == DispatchPhase::Bubble {
3742                    editor.update(cx, |editor, cx| {
3743                        if event.pressed_button == Some(MouseButton::Left)
3744                            || event.pressed_button == Some(MouseButton::Middle)
3745                        {
3746                            Self::mouse_dragged(
3747                                editor,
3748                                event,
3749                                &position_map,
3750                                text_hitbox.bounds,
3751                                cx,
3752                            )
3753                        }
3754
3755                        Self::mouse_moved(
3756                            editor,
3757                            event,
3758                            &position_map,
3759                            &text_hitbox,
3760                            &gutter_hitbox,
3761                            cx,
3762                        )
3763                    });
3764                }
3765            }
3766        });
3767    }
3768
3769    fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
3770        bounds.upper_right().x - self.style.scrollbar_width
3771    }
3772
3773    fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
3774        let style = &self.style;
3775        let font_size = style.text.font_size.to_pixels(cx.rem_size());
3776        let layout = cx
3777            .text_system()
3778            .shape_line(
3779                SharedString::from(" ".repeat(column)),
3780                font_size,
3781                &[TextRun {
3782                    len: column,
3783                    font: style.text.font(),
3784                    color: Hsla::default(),
3785                    background_color: None,
3786                    underline: None,
3787                    strikethrough: None,
3788                }],
3789            )
3790            .unwrap();
3791
3792        layout.width
3793    }
3794
3795    fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
3796        let digit_count = snapshot
3797            .max_buffer_row()
3798            .next_row()
3799            .as_f32()
3800            .log10()
3801            .floor() as usize
3802            + 1;
3803        self.column_pixels(digit_count, cx)
3804    }
3805}
3806
3807fn prepaint_gutter_button(
3808    button: IconButton,
3809    row: DisplayRow,
3810    line_height: Pixels,
3811    gutter_dimensions: &GutterDimensions,
3812    scroll_pixel_position: gpui::Point<Pixels>,
3813    gutter_hitbox: &Hitbox,
3814    cx: &mut WindowContext<'_>,
3815) -> AnyElement {
3816    let mut button = button.into_any_element();
3817    let available_space = size(
3818        AvailableSpace::MinContent,
3819        AvailableSpace::Definite(line_height),
3820    );
3821    let indicator_size = button.layout_as_root(available_space, cx);
3822
3823    let blame_width = gutter_dimensions
3824        .git_blame_entries_width
3825        .unwrap_or(Pixels::ZERO);
3826
3827    let mut x = blame_width;
3828    let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
3829        - indicator_size.width
3830        - blame_width;
3831    x += available_width / 2.;
3832
3833    let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
3834    y += (line_height - indicator_size.height) / 2.;
3835
3836    button.prepaint_as_root(gutter_hitbox.origin + point(x, y), available_space, cx);
3837    button
3838}
3839
3840fn render_inline_blame_entry(
3841    blame: &gpui::Model<GitBlame>,
3842    blame_entry: BlameEntry,
3843    style: &EditorStyle,
3844    workspace: Option<WeakView<Workspace>>,
3845    cx: &mut WindowContext<'_>,
3846) -> AnyElement {
3847    let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
3848
3849    let author = blame_entry.author.as_deref().unwrap_or_default();
3850    let text = format!("{}, {}", author, relative_timestamp);
3851
3852    let details = blame.read(cx).details_for_entry(&blame_entry);
3853
3854    let tooltip = cx.new_view(|_| BlameEntryTooltip::new(blame_entry, details, style, workspace));
3855
3856    h_flex()
3857        .id("inline-blame")
3858        .w_full()
3859        .font_family(style.text.font().family)
3860        .text_color(cx.theme().status().hint)
3861        .line_height(style.text.line_height)
3862        .child(Icon::new(IconName::FileGit).color(Color::Hint))
3863        .child(text)
3864        .gap_2()
3865        .hoverable_tooltip(move |_| tooltip.clone().into())
3866        .into_any()
3867}
3868
3869fn render_blame_entry(
3870    ix: usize,
3871    blame: &gpui::Model<GitBlame>,
3872    blame_entry: BlameEntry,
3873    style: &EditorStyle,
3874    last_used_color: &mut Option<(PlayerColor, Oid)>,
3875    editor: View<Editor>,
3876    cx: &mut WindowContext<'_>,
3877) -> AnyElement {
3878    let mut sha_color = cx
3879        .theme()
3880        .players()
3881        .color_for_participant(blame_entry.sha.into());
3882    // If the last color we used is the same as the one we get for this line, but
3883    // the commit SHAs are different, then we try again to get a different color.
3884    match *last_used_color {
3885        Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
3886            let index: u32 = blame_entry.sha.into();
3887            sha_color = cx.theme().players().color_for_participant(index + 1);
3888        }
3889        _ => {}
3890    };
3891    last_used_color.replace((sha_color, blame_entry.sha));
3892
3893    let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
3894
3895    let short_commit_id = blame_entry.sha.display_short();
3896
3897    let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
3898    let name = util::truncate_and_trailoff(author_name, 20);
3899
3900    let details = blame.read(cx).details_for_entry(&blame_entry);
3901
3902    let workspace = editor.read(cx).workspace.as_ref().map(|(w, _)| w.clone());
3903
3904    let tooltip = cx.new_view(|_| {
3905        BlameEntryTooltip::new(blame_entry.clone(), details.clone(), style, workspace)
3906    });
3907
3908    h_flex()
3909        .w_full()
3910        .font_family(style.text.font().family)
3911        .line_height(style.text.line_height)
3912        .id(("blame", ix))
3913        .children([
3914            div()
3915                .text_color(sha_color.cursor)
3916                .child(short_commit_id)
3917                .mr_2(),
3918            div()
3919                .w_full()
3920                .h_flex()
3921                .justify_between()
3922                .text_color(cx.theme().status().hint)
3923                .child(name)
3924                .child(relative_timestamp),
3925        ])
3926        .on_mouse_down(MouseButton::Right, {
3927            let blame_entry = blame_entry.clone();
3928            let details = details.clone();
3929            move |event, cx| {
3930                deploy_blame_entry_context_menu(
3931                    &blame_entry,
3932                    details.as_ref(),
3933                    editor.clone(),
3934                    event.position,
3935                    cx,
3936                );
3937            }
3938        })
3939        .hover(|style| style.bg(cx.theme().colors().element_hover))
3940        .when_some(
3941            details.and_then(|details| details.permalink),
3942            |this, url| {
3943                let url = url.clone();
3944                this.cursor_pointer().on_click(move |_, cx| {
3945                    cx.stop_propagation();
3946                    cx.open_url(url.as_str())
3947                })
3948            },
3949        )
3950        .hoverable_tooltip(move |_| tooltip.clone().into())
3951        .into_any()
3952}
3953
3954fn deploy_blame_entry_context_menu(
3955    blame_entry: &BlameEntry,
3956    details: Option<&CommitDetails>,
3957    editor: View<Editor>,
3958    position: gpui::Point<Pixels>,
3959    cx: &mut WindowContext<'_>,
3960) {
3961    let context_menu = ContextMenu::build(cx, move |this, _| {
3962        let sha = format!("{}", blame_entry.sha);
3963        this.entry("Copy commit SHA", None, move |cx| {
3964            cx.write_to_clipboard(ClipboardItem::new(sha.clone()));
3965        })
3966        .when_some(
3967            details.and_then(|details| details.permalink.clone()),
3968            |this, url| this.entry("Open permalink", None, move |cx| cx.open_url(url.as_str())),
3969        )
3970    });
3971
3972    editor.update(cx, move |editor, cx| {
3973        editor.mouse_context_menu = Some(MouseContextMenu::new(position, context_menu, cx));
3974        cx.notify();
3975    });
3976}
3977
3978#[derive(Debug)]
3979pub(crate) struct LineWithInvisibles {
3980    fragments: SmallVec<[LineFragment; 1]>,
3981    invisibles: Vec<Invisible>,
3982    len: usize,
3983    width: Pixels,
3984    font_size: Pixels,
3985}
3986
3987#[allow(clippy::large_enum_variant)]
3988enum LineFragment {
3989    Text(ShapedLine),
3990    Element {
3991        element: Option<AnyElement>,
3992        size: Size<Pixels>,
3993        len: usize,
3994    },
3995}
3996
3997impl fmt::Debug for LineFragment {
3998    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3999        match self {
4000            LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
4001            LineFragment::Element { size, len, .. } => f
4002                .debug_struct("Element")
4003                .field("size", size)
4004                .field("len", len)
4005                .finish(),
4006        }
4007    }
4008}
4009
4010impl LineWithInvisibles {
4011    fn from_chunks<'a>(
4012        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
4013        text_style: &TextStyle,
4014        max_line_len: usize,
4015        max_line_count: usize,
4016        line_number_layouts: &[Option<ShapedLine>],
4017        editor_mode: EditorMode,
4018        cx: &mut WindowContext,
4019    ) -> Vec<Self> {
4020        let mut layouts = Vec::with_capacity(max_line_count);
4021        let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
4022        let mut line = String::new();
4023        let mut invisibles = Vec::new();
4024        let mut width = Pixels::ZERO;
4025        let mut len = 0;
4026        let mut styles = Vec::new();
4027        let mut non_whitespace_added = false;
4028        let mut row = 0;
4029        let mut line_exceeded_max_len = false;
4030        let font_size = text_style.font_size.to_pixels(cx.rem_size());
4031
4032        let ellipsis = SharedString::from("");
4033
4034        for highlighted_chunk in chunks.chain([HighlightedChunk {
4035            text: "\n",
4036            style: None,
4037            is_tab: false,
4038            renderer: None,
4039        }]) {
4040            if let Some(renderer) = highlighted_chunk.renderer {
4041                if !line.is_empty() {
4042                    let shaped_line = cx
4043                        .text_system()
4044                        .shape_line(line.clone().into(), font_size, &styles)
4045                        .unwrap();
4046                    width += shaped_line.width;
4047                    len += shaped_line.len;
4048                    fragments.push(LineFragment::Text(shaped_line));
4049                    line.clear();
4050                    styles.clear();
4051                }
4052
4053                let available_width = if renderer.constrain_width {
4054                    let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
4055                        ellipsis.clone()
4056                    } else {
4057                        SharedString::from(Arc::from(highlighted_chunk.text))
4058                    };
4059                    let shaped_line = cx
4060                        .text_system()
4061                        .shape_line(
4062                            chunk,
4063                            font_size,
4064                            &[text_style.to_run(highlighted_chunk.text.len())],
4065                        )
4066                        .unwrap();
4067                    AvailableSpace::Definite(shaped_line.width)
4068                } else {
4069                    AvailableSpace::MinContent
4070                };
4071
4072                let mut element = (renderer.render)(cx);
4073                let line_height = text_style.line_height_in_pixels(cx.rem_size());
4074                let size = element.layout_as_root(
4075                    size(available_width, AvailableSpace::Definite(line_height)),
4076                    cx,
4077                );
4078
4079                width += size.width;
4080                len += highlighted_chunk.text.len();
4081                fragments.push(LineFragment::Element {
4082                    element: Some(element),
4083                    size,
4084                    len: highlighted_chunk.text.len(),
4085                });
4086            } else {
4087                for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
4088                    if ix > 0 {
4089                        let shaped_line = cx
4090                            .text_system()
4091                            .shape_line(line.clone().into(), font_size, &styles)
4092                            .unwrap();
4093                        width += shaped_line.width;
4094                        len += shaped_line.len;
4095                        fragments.push(LineFragment::Text(shaped_line));
4096                        layouts.push(Self {
4097                            width: mem::take(&mut width),
4098                            len: mem::take(&mut len),
4099                            fragments: mem::take(&mut fragments),
4100                            invisibles: std::mem::take(&mut invisibles),
4101                            font_size,
4102                        });
4103
4104                        line.clear();
4105                        styles.clear();
4106                        row += 1;
4107                        line_exceeded_max_len = false;
4108                        non_whitespace_added = false;
4109                        if row == max_line_count {
4110                            return layouts;
4111                        }
4112                    }
4113
4114                    if !line_chunk.is_empty() && !line_exceeded_max_len {
4115                        let text_style = if let Some(style) = highlighted_chunk.style {
4116                            Cow::Owned(text_style.clone().highlight(style))
4117                        } else {
4118                            Cow::Borrowed(text_style)
4119                        };
4120
4121                        if line.len() + line_chunk.len() > max_line_len {
4122                            let mut chunk_len = max_line_len - line.len();
4123                            while !line_chunk.is_char_boundary(chunk_len) {
4124                                chunk_len -= 1;
4125                            }
4126                            line_chunk = &line_chunk[..chunk_len];
4127                            line_exceeded_max_len = true;
4128                        }
4129
4130                        styles.push(TextRun {
4131                            len: line_chunk.len(),
4132                            font: text_style.font(),
4133                            color: text_style.color,
4134                            background_color: text_style.background_color,
4135                            underline: text_style.underline,
4136                            strikethrough: text_style.strikethrough,
4137                        });
4138
4139                        if editor_mode == EditorMode::Full {
4140                            // Line wrap pads its contents with fake whitespaces,
4141                            // avoid printing them
4142                            let inside_wrapped_string = line_number_layouts
4143                                .get(row)
4144                                .and_then(|layout| layout.as_ref())
4145                                .is_none();
4146                            if highlighted_chunk.is_tab {
4147                                if non_whitespace_added || !inside_wrapped_string {
4148                                    invisibles.push(Invisible::Tab {
4149                                        line_start_offset: line.len(),
4150                                        line_end_offset: line.len() + line_chunk.len(),
4151                                    });
4152                                }
4153                            } else {
4154                                invisibles.extend(
4155                                    line_chunk
4156                                        .bytes()
4157                                        .enumerate()
4158                                        .filter(|(_, line_byte)| {
4159                                            let is_whitespace =
4160                                                (*line_byte as char).is_whitespace();
4161                                            non_whitespace_added |= !is_whitespace;
4162                                            is_whitespace
4163                                                && (non_whitespace_added || !inside_wrapped_string)
4164                                        })
4165                                        .map(|(whitespace_index, _)| Invisible::Whitespace {
4166                                            line_offset: line.len() + whitespace_index,
4167                                        }),
4168                                )
4169                            }
4170                        }
4171
4172                        line.push_str(line_chunk);
4173                    }
4174                }
4175            }
4176        }
4177
4178        layouts
4179    }
4180
4181    fn prepaint(
4182        &mut self,
4183        line_height: Pixels,
4184        scroll_pixel_position: gpui::Point<Pixels>,
4185        row: DisplayRow,
4186        content_origin: gpui::Point<Pixels>,
4187        line_elements: &mut SmallVec<[AnyElement; 1]>,
4188        cx: &mut WindowContext,
4189    ) {
4190        let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
4191        let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
4192        for fragment in &mut self.fragments {
4193            match fragment {
4194                LineFragment::Text(line) => {
4195                    fragment_origin.x += line.width;
4196                }
4197                LineFragment::Element { element, size, .. } => {
4198                    let mut element = element
4199                        .take()
4200                        .expect("you can't prepaint LineWithInvisibles twice");
4201
4202                    // Center the element vertically within the line.
4203                    let mut element_origin = fragment_origin;
4204                    element_origin.y += (line_height - size.height) / 2.;
4205                    element.prepaint_at(element_origin, cx);
4206                    line_elements.push(element);
4207
4208                    fragment_origin.x += size.width;
4209                }
4210            }
4211        }
4212    }
4213
4214    fn draw(
4215        &self,
4216        layout: &EditorLayout,
4217        row: DisplayRow,
4218        content_origin: gpui::Point<Pixels>,
4219        whitespace_setting: ShowWhitespaceSetting,
4220        selection_ranges: &[Range<DisplayPoint>],
4221        cx: &mut WindowContext,
4222    ) {
4223        let line_height = layout.position_map.line_height;
4224        let line_y = line_height
4225            * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
4226
4227        let mut fragment_origin =
4228            content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
4229
4230        for fragment in &self.fragments {
4231            match fragment {
4232                LineFragment::Text(line) => {
4233                    line.paint(fragment_origin, line_height, cx).log_err();
4234                    fragment_origin.x += line.width;
4235                }
4236                LineFragment::Element { size, .. } => {
4237                    fragment_origin.x += size.width;
4238                }
4239            }
4240        }
4241
4242        self.draw_invisibles(
4243            &selection_ranges,
4244            layout,
4245            content_origin,
4246            line_y,
4247            row,
4248            line_height,
4249            whitespace_setting,
4250            cx,
4251        );
4252    }
4253
4254    #[allow(clippy::too_many_arguments)]
4255    fn draw_invisibles(
4256        &self,
4257        selection_ranges: &[Range<DisplayPoint>],
4258        layout: &EditorLayout,
4259        content_origin: gpui::Point<Pixels>,
4260        line_y: Pixels,
4261        row: DisplayRow,
4262        line_height: Pixels,
4263        whitespace_setting: ShowWhitespaceSetting,
4264        cx: &mut WindowContext,
4265    ) {
4266        let extract_whitespace_info = |invisible: &Invisible| {
4267            let (token_offset, token_end_offset, invisible_symbol) = match invisible {
4268                Invisible::Tab {
4269                    line_start_offset,
4270                    line_end_offset,
4271                } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
4272                Invisible::Whitespace { line_offset } => {
4273                    (*line_offset, line_offset + 1, &layout.space_invisible)
4274                }
4275            };
4276
4277            let x_offset = self.x_for_index(token_offset);
4278            let invisible_offset =
4279                (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
4280            let origin = content_origin
4281                + gpui::point(
4282                    x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
4283                    line_y,
4284                );
4285
4286            (
4287                [token_offset, token_end_offset],
4288                Box::new(move |cx: &mut WindowContext| {
4289                    invisible_symbol.paint(origin, line_height, cx).log_err();
4290                }),
4291            )
4292        };
4293
4294        let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
4295        match whitespace_setting {
4296            ShowWhitespaceSetting::None => return,
4297            ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(cx)),
4298            ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
4299                let invisible_point = DisplayPoint::new(row, start as u32);
4300                if !selection_ranges
4301                    .iter()
4302                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
4303                {
4304                    return;
4305                }
4306
4307                paint(cx);
4308            }),
4309
4310            // For a whitespace to be on a boundary, any of the following conditions need to be met:
4311            // - It is a tab
4312            // - It is adjacent to an edge (start or end)
4313            // - It is adjacent to a whitespace (left or right)
4314            ShowWhitespaceSetting::Boundary => {
4315                // 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
4316                // the above cases.
4317                // Note: We zip in the original `invisibles` to check for tab equality
4318                let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut WindowContext)>)> = None;
4319                for (([start, end], paint), invisible) in
4320                    invisible_iter.zip_eq(self.invisibles.iter())
4321                {
4322                    let should_render = match (&last_seen, invisible) {
4323                        (_, Invisible::Tab { .. }) => true,
4324                        (Some((_, last_end, _)), _) => *last_end == start,
4325                        _ => false,
4326                    };
4327
4328                    if should_render || start == 0 || end == self.len {
4329                        paint(cx);
4330
4331                        // Since we are scanning from the left, we will skip over the first available whitespace that is part
4332                        // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
4333                        if let Some((should_render_last, last_end, paint_last)) = last_seen {
4334                            // Note that we need to make sure that the last one is actually adjacent
4335                            if !should_render_last && last_end == start {
4336                                paint_last(cx);
4337                            }
4338                        }
4339                    }
4340
4341                    // Manually render anything within a selection
4342                    let invisible_point = DisplayPoint::new(row, start as u32);
4343                    if selection_ranges.iter().any(|region| {
4344                        region.start <= invisible_point && invisible_point < region.end
4345                    }) {
4346                        paint(cx);
4347                    }
4348
4349                    last_seen = Some((should_render, end, paint));
4350                }
4351            }
4352        };
4353    }
4354
4355    pub fn x_for_index(&self, index: usize) -> Pixels {
4356        let mut fragment_start_x = Pixels::ZERO;
4357        let mut fragment_start_index = 0;
4358
4359        for fragment in &self.fragments {
4360            match fragment {
4361                LineFragment::Text(shaped_line) => {
4362                    let fragment_end_index = fragment_start_index + shaped_line.len;
4363                    if index < fragment_end_index {
4364                        return fragment_start_x
4365                            + shaped_line.x_for_index(index - fragment_start_index);
4366                    }
4367                    fragment_start_x += shaped_line.width;
4368                    fragment_start_index = fragment_end_index;
4369                }
4370                LineFragment::Element { len, size, .. } => {
4371                    let fragment_end_index = fragment_start_index + len;
4372                    if index < fragment_end_index {
4373                        return fragment_start_x;
4374                    }
4375                    fragment_start_x += size.width;
4376                    fragment_start_index = fragment_end_index;
4377                }
4378            }
4379        }
4380
4381        fragment_start_x
4382    }
4383
4384    pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
4385        let mut fragment_start_x = Pixels::ZERO;
4386        let mut fragment_start_index = 0;
4387
4388        for fragment in &self.fragments {
4389            match fragment {
4390                LineFragment::Text(shaped_line) => {
4391                    let fragment_end_x = fragment_start_x + shaped_line.width;
4392                    if x < fragment_end_x {
4393                        return Some(
4394                            fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
4395                        );
4396                    }
4397                    fragment_start_x = fragment_end_x;
4398                    fragment_start_index += shaped_line.len;
4399                }
4400                LineFragment::Element { len, size, .. } => {
4401                    let fragment_end_x = fragment_start_x + size.width;
4402                    if x < fragment_end_x {
4403                        return Some(fragment_start_index);
4404                    }
4405                    fragment_start_index += len;
4406                    fragment_start_x = fragment_end_x;
4407                }
4408            }
4409        }
4410
4411        None
4412    }
4413
4414    pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
4415        let mut fragment_start_index = 0;
4416
4417        for fragment in &self.fragments {
4418            match fragment {
4419                LineFragment::Text(shaped_line) => {
4420                    let fragment_end_index = fragment_start_index + shaped_line.len;
4421                    if index < fragment_end_index {
4422                        return shaped_line.font_id_for_index(index - fragment_start_index);
4423                    }
4424                    fragment_start_index = fragment_end_index;
4425                }
4426                LineFragment::Element { len, .. } => {
4427                    let fragment_end_index = fragment_start_index + len;
4428                    if index < fragment_end_index {
4429                        return None;
4430                    }
4431                    fragment_start_index = fragment_end_index;
4432                }
4433            }
4434        }
4435
4436        None
4437    }
4438}
4439
4440#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4441enum Invisible {
4442    /// A tab character
4443    ///
4444    /// A tab character is internally represented by spaces (configured by the user's tab width)
4445    /// aligned to the nearest column, so it's necessary to store the start and end offset for
4446    /// adjacency checks.
4447    Tab {
4448        line_start_offset: usize,
4449        line_end_offset: usize,
4450    },
4451    Whitespace {
4452        line_offset: usize,
4453    },
4454}
4455
4456impl EditorElement {
4457    /// Returns the rem size to use when rendering the [`EditorElement`].
4458    ///
4459    /// This allows UI elements to scale based on the `buffer_font_size`.
4460    fn rem_size(&self, cx: &WindowContext) -> Option<Pixels> {
4461        match self.editor.read(cx).mode {
4462            EditorMode::Full => {
4463                let buffer_font_size = self.style.text.font_size;
4464                match buffer_font_size {
4465                    AbsoluteLength::Pixels(pixels) => {
4466                        let rem_size_scale = {
4467                            // Our default UI font size is 14px on a 16px base scale.
4468                            // This means the default UI font size is 0.875rems.
4469                            let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
4470
4471                            // We then determine the delta between a single rem and the default font
4472                            // size scale.
4473                            let default_font_size_delta = 1. - default_font_size_scale;
4474
4475                            // Finally, we add this delta to 1rem to get the scale factor that
4476                            // should be used to scale up the UI.
4477                            1. + default_font_size_delta
4478                        };
4479
4480                        Some(pixels * rem_size_scale)
4481                    }
4482                    AbsoluteLength::Rems(rems) => {
4483                        Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
4484                    }
4485                }
4486            }
4487            // We currently use single-line and auto-height editors in UI contexts,
4488            // so we don't want to scale everything with the buffer font size, as it
4489            // ends up looking off.
4490            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => None,
4491        }
4492    }
4493}
4494
4495impl Element for EditorElement {
4496    type RequestLayoutState = ();
4497    type PrepaintState = EditorLayout;
4498
4499    fn id(&self) -> Option<ElementId> {
4500        None
4501    }
4502
4503    fn request_layout(
4504        &mut self,
4505        _: Option<&GlobalElementId>,
4506        cx: &mut WindowContext,
4507    ) -> (gpui::LayoutId, ()) {
4508        let rem_size = self.rem_size(cx);
4509        cx.with_rem_size(rem_size, |cx| {
4510            self.editor.update(cx, |editor, cx| {
4511                editor.set_style(self.style.clone(), cx);
4512
4513                let layout_id = match editor.mode {
4514                    EditorMode::SingleLine { auto_width } => {
4515                        let rem_size = cx.rem_size();
4516
4517                        let height = self.style.text.line_height_in_pixels(rem_size);
4518                        if auto_width {
4519                            let editor_handle = cx.view().clone();
4520                            let style = self.style.clone();
4521                            cx.request_measured_layout(Style::default(), move |_, _, cx| {
4522                                let editor_snapshot =
4523                                    editor_handle.update(cx, |editor, cx| editor.snapshot(cx));
4524                                let line = Self::layout_lines(
4525                                    DisplayRow(0)..DisplayRow(1),
4526                                    &[],
4527                                    &editor_snapshot,
4528                                    &style,
4529                                    cx,
4530                                )
4531                                .pop()
4532                                .unwrap();
4533
4534                                let font_id = cx.text_system().resolve_font(&style.text.font());
4535                                let font_size = style.text.font_size.to_pixels(cx.rem_size());
4536                                let em_width = cx
4537                                    .text_system()
4538                                    .typographic_bounds(font_id, font_size, 'm')
4539                                    .unwrap()
4540                                    .size
4541                                    .width;
4542
4543                                size(line.width + em_width, height)
4544                            })
4545                        } else {
4546                            let mut style = Style::default();
4547                            style.size.height = height.into();
4548                            style.size.width = relative(1.).into();
4549                            cx.request_layout(style, None)
4550                        }
4551                    }
4552                    EditorMode::AutoHeight { max_lines } => {
4553                        let editor_handle = cx.view().clone();
4554                        let max_line_number_width =
4555                            self.max_line_number_width(&editor.snapshot(cx), cx);
4556                        cx.request_measured_layout(
4557                            Style::default(),
4558                            move |known_dimensions, available_space, cx| {
4559                                editor_handle
4560                                    .update(cx, |editor, cx| {
4561                                        compute_auto_height_layout(
4562                                            editor,
4563                                            max_lines,
4564                                            max_line_number_width,
4565                                            known_dimensions,
4566                                            available_space.width,
4567                                            cx,
4568                                        )
4569                                    })
4570                                    .unwrap_or_default()
4571                            },
4572                        )
4573                    }
4574                    EditorMode::Full => {
4575                        let mut style = Style::default();
4576                        style.size.width = relative(1.).into();
4577                        style.size.height = relative(1.).into();
4578                        cx.request_layout(style, None)
4579                    }
4580                };
4581
4582                (layout_id, ())
4583            })
4584        })
4585    }
4586
4587    fn prepaint(
4588        &mut self,
4589        _: Option<&GlobalElementId>,
4590        bounds: Bounds<Pixels>,
4591        _: &mut Self::RequestLayoutState,
4592        cx: &mut WindowContext,
4593    ) -> Self::PrepaintState {
4594        let text_style = TextStyleRefinement {
4595            font_size: Some(self.style.text.font_size),
4596            line_height: Some(self.style.text.line_height),
4597            ..Default::default()
4598        };
4599        cx.set_view_id(self.editor.entity_id());
4600
4601        let rem_size = self.rem_size(cx);
4602        cx.with_rem_size(rem_size, |cx| {
4603            cx.with_text_style(Some(text_style), |cx| {
4604                cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
4605                    let mut snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
4606                    let style = self.style.clone();
4607
4608                    let font_id = cx.text_system().resolve_font(&style.text.font());
4609                    let font_size = style.text.font_size.to_pixels(cx.rem_size());
4610                    let line_height = style.text.line_height_in_pixels(cx.rem_size());
4611                    let em_width = cx
4612                        .text_system()
4613                        .typographic_bounds(font_id, font_size, 'm')
4614                        .unwrap()
4615                        .size
4616                        .width;
4617                    let em_advance = cx
4618                        .text_system()
4619                        .advance(font_id, font_size, 'm')
4620                        .unwrap()
4621                        .width;
4622
4623                    let gutter_dimensions = snapshot.gutter_dimensions(
4624                        font_id,
4625                        font_size,
4626                        em_width,
4627                        self.max_line_number_width(&snapshot, cx),
4628                        cx,
4629                    );
4630                    let text_width = bounds.size.width - gutter_dimensions.width;
4631
4632                    let right_margin = if snapshot.mode == EditorMode::Full {
4633                        EditorElement::SCROLLBAR_WIDTH
4634                    } else {
4635                        px(0.)
4636                    };
4637                    let overscroll = size(em_width + right_margin, px(0.));
4638
4639                    snapshot = self.editor.update(cx, |editor, cx| {
4640                        editor.last_bounds = Some(bounds);
4641                        editor.gutter_dimensions = gutter_dimensions;
4642                        editor.set_visible_line_count(bounds.size.height / line_height, cx);
4643
4644                        let editor_width =
4645                            text_width - gutter_dimensions.margin - overscroll.width - em_width;
4646                        let wrap_width = match editor.soft_wrap_mode(cx) {
4647                            SoftWrap::None => None,
4648                            SoftWrap::PreferLine => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
4649                            SoftWrap::EditorWidth => Some(editor_width),
4650                            SoftWrap::Column(column) => {
4651                                Some(editor_width.min(column as f32 * em_advance))
4652                            }
4653                        };
4654
4655                        if editor.set_wrap_width(wrap_width, cx) {
4656                            editor.snapshot(cx)
4657                        } else {
4658                            snapshot
4659                        }
4660                    });
4661
4662                    let wrap_guides = self
4663                        .editor
4664                        .read(cx)
4665                        .wrap_guides(cx)
4666                        .iter()
4667                        .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
4668                        .collect::<SmallVec<[_; 2]>>();
4669
4670                    let hitbox = cx.insert_hitbox(bounds, false);
4671                    let gutter_hitbox = cx.insert_hitbox(
4672                        Bounds {
4673                            origin: bounds.origin,
4674                            size: size(gutter_dimensions.width, bounds.size.height),
4675                        },
4676                        false,
4677                    );
4678                    let text_hitbox = cx.insert_hitbox(
4679                        Bounds {
4680                            origin: gutter_hitbox.upper_right(),
4681                            size: size(text_width, bounds.size.height),
4682                        },
4683                        false,
4684                    );
4685                    // Offset the content_bounds from the text_bounds by the gutter margin (which
4686                    // is roughly half a character wide) to make hit testing work more like how we want.
4687                    let content_origin =
4688                        text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
4689
4690                    let height_in_lines = bounds.size.height / line_height;
4691                    let max_row = snapshot.max_point().row().as_f32();
4692                    let max_scroll_top = if matches!(snapshot.mode, EditorMode::AutoHeight { .. }) {
4693                        (max_row - height_in_lines + 1.).max(0.)
4694                    } else {
4695                        let settings = EditorSettings::get_global(cx);
4696                        match settings.scroll_beyond_last_line {
4697                            ScrollBeyondLastLine::OnePage => max_row,
4698                            ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
4699                            ScrollBeyondLastLine::VerticalScrollMargin => {
4700                                (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
4701                                    .max(0.)
4702                            }
4703                        }
4704                    };
4705
4706                    let mut autoscroll_containing_element = false;
4707                    let mut autoscroll_horizontally = false;
4708                    self.editor.update(cx, |editor, cx| {
4709                        autoscroll_containing_element =
4710                            editor.autoscroll_requested() || editor.has_pending_selection();
4711                        autoscroll_horizontally =
4712                            editor.autoscroll_vertically(bounds, line_height, max_scroll_top, cx);
4713                        snapshot = editor.snapshot(cx);
4714                    });
4715
4716                    let mut scroll_position = snapshot.scroll_position();
4717                    // The scroll position is a fractional point, the whole number of which represents
4718                    // the top of the window in terms of display rows.
4719                    let start_row = DisplayRow(scroll_position.y as u32);
4720                    let max_row = snapshot.max_point().row();
4721                    let end_row = cmp::min(
4722                        (scroll_position.y + height_in_lines).ceil() as u32,
4723                        max_row.next_row().0,
4724                    );
4725                    let end_row = DisplayRow(end_row);
4726
4727                    let buffer_rows = snapshot
4728                        .buffer_rows(start_row)
4729                        .take((start_row..end_row).len())
4730                        .collect::<Vec<_>>();
4731
4732                    let start_anchor = if start_row == Default::default() {
4733                        Anchor::min()
4734                    } else {
4735                        snapshot.buffer_snapshot.anchor_before(
4736                            DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
4737                        )
4738                    };
4739                    let end_anchor = if end_row > max_row {
4740                        Anchor::max()
4741                    } else {
4742                        snapshot.buffer_snapshot.anchor_before(
4743                            DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
4744                        )
4745                    };
4746
4747                    let highlighted_rows = self
4748                        .editor
4749                        .update(cx, |editor, cx| editor.highlighted_display_rows(cx));
4750                    let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
4751                        start_anchor..end_anchor,
4752                        &snapshot.display_snapshot,
4753                        cx.theme().colors(),
4754                    );
4755                    let highlighted_gutter_ranges =
4756                        self.editor.read(cx).gutter_highlights_in_range(
4757                            start_anchor..end_anchor,
4758                            &snapshot.display_snapshot,
4759                            cx,
4760                        );
4761
4762                    let redacted_ranges = self.editor.read(cx).redacted_ranges(
4763                        start_anchor..end_anchor,
4764                        &snapshot.display_snapshot,
4765                        cx,
4766                    );
4767
4768                    let (selections, active_rows, newest_selection_head) = self.layout_selections(
4769                        start_anchor,
4770                        end_anchor,
4771                        &snapshot,
4772                        start_row,
4773                        end_row,
4774                        cx,
4775                    );
4776
4777                    let line_numbers = self.layout_line_numbers(
4778                        start_row..end_row,
4779                        buffer_rows.iter().copied(),
4780                        &active_rows,
4781                        newest_selection_head,
4782                        &snapshot,
4783                        cx,
4784                    );
4785
4786                    let mut gutter_fold_toggles =
4787                        cx.with_element_namespace("gutter_fold_toggles", |cx| {
4788                            self.layout_gutter_fold_toggles(
4789                                start_row..end_row,
4790                                buffer_rows.iter().copied(),
4791                                &active_rows,
4792                                &snapshot,
4793                                cx,
4794                            )
4795                        });
4796                    let crease_trailers = cx.with_element_namespace("crease_trailers", |cx| {
4797                        self.layout_crease_trailers(buffer_rows.iter().copied(), &snapshot, cx)
4798                    });
4799
4800                    let display_hunks = self.layout_git_gutters(
4801                        line_height,
4802                        &gutter_hitbox,
4803                        start_row..end_row,
4804                        &snapshot,
4805                        cx,
4806                    );
4807
4808                    let mut max_visible_line_width = Pixels::ZERO;
4809                    let mut line_layouts = Self::layout_lines(
4810                        start_row..end_row,
4811                        &line_numbers,
4812                        &snapshot,
4813                        &self.style,
4814                        cx,
4815                    );
4816                    for line_with_invisibles in &line_layouts {
4817                        if line_with_invisibles.width > max_visible_line_width {
4818                            max_visible_line_width = line_with_invisibles.width;
4819                        }
4820                    }
4821
4822                    let longest_line_width =
4823                        layout_line(snapshot.longest_row(), &snapshot, &style, cx).width;
4824                    let mut scroll_width =
4825                        longest_line_width.max(max_visible_line_width) + overscroll.width;
4826
4827                    let mut blocks = cx.with_element_namespace("blocks", |cx| {
4828                        self.build_blocks(
4829                            start_row..end_row,
4830                            &snapshot,
4831                            &hitbox,
4832                            &text_hitbox,
4833                            &mut scroll_width,
4834                            &gutter_dimensions,
4835                            em_width,
4836                            gutter_dimensions.full_width(),
4837                            line_height,
4838                            &line_layouts,
4839                            cx,
4840                        )
4841                    });
4842
4843                    let start_buffer_row =
4844                        MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
4845                    let end_buffer_row =
4846                        MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
4847
4848                    let scroll_max = point(
4849                        ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
4850                        max_row.as_f32(),
4851                    );
4852
4853                    self.editor.update(cx, |editor, cx| {
4854                        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
4855
4856                        let autoscrolled = if autoscroll_horizontally {
4857                            editor.autoscroll_horizontally(
4858                                start_row,
4859                                text_hitbox.size.width,
4860                                scroll_width,
4861                                em_width,
4862                                &line_layouts,
4863                                cx,
4864                            )
4865                        } else {
4866                            false
4867                        };
4868
4869                        if clamped || autoscrolled {
4870                            snapshot = editor.snapshot(cx);
4871                            scroll_position = snapshot.scroll_position();
4872                        }
4873                    });
4874
4875                    let scroll_pixel_position = point(
4876                        scroll_position.x * em_width,
4877                        scroll_position.y * line_height,
4878                    );
4879
4880                    let indent_guides = self.layout_indent_guides(
4881                        content_origin,
4882                        text_hitbox.origin,
4883                        start_buffer_row..end_buffer_row,
4884                        scroll_pixel_position,
4885                        line_height,
4886                        &snapshot,
4887                        cx,
4888                    );
4889
4890                    let crease_trailers = cx.with_element_namespace("crease_trailers", |cx| {
4891                        self.prepaint_crease_trailers(
4892                            crease_trailers,
4893                            &line_layouts,
4894                            line_height,
4895                            content_origin,
4896                            scroll_pixel_position,
4897                            em_width,
4898                            cx,
4899                        )
4900                    });
4901
4902                    let mut inline_blame = None;
4903                    if let Some(newest_selection_head) = newest_selection_head {
4904                        let display_row = newest_selection_head.row();
4905                        if (start_row..end_row).contains(&display_row) {
4906                            let line_ix = display_row.minus(start_row) as usize;
4907                            let line_layout = &line_layouts[line_ix];
4908                            let crease_trailer_layout = crease_trailers[line_ix].as_ref();
4909                            inline_blame = self.layout_inline_blame(
4910                                display_row,
4911                                &snapshot.display_snapshot,
4912                                line_layout,
4913                                crease_trailer_layout,
4914                                em_width,
4915                                content_origin,
4916                                scroll_pixel_position,
4917                                line_height,
4918                                cx,
4919                            );
4920                        }
4921                    }
4922
4923                    let blamed_display_rows = self.layout_blame_entries(
4924                        buffer_rows.into_iter(),
4925                        em_width,
4926                        scroll_position,
4927                        line_height,
4928                        &gutter_hitbox,
4929                        gutter_dimensions.git_blame_entries_width,
4930                        cx,
4931                    );
4932
4933                    let scroll_max = point(
4934                        ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
4935                        max_scroll_top,
4936                    );
4937
4938                    self.editor.update(cx, |editor, cx| {
4939                        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
4940
4941                        let autoscrolled = if autoscroll_horizontally {
4942                            editor.autoscroll_horizontally(
4943                                start_row,
4944                                text_hitbox.size.width,
4945                                scroll_width,
4946                                em_width,
4947                                &line_layouts,
4948                                cx,
4949                            )
4950                        } else {
4951                            false
4952                        };
4953
4954                        if clamped || autoscrolled {
4955                            snapshot = editor.snapshot(cx);
4956                            scroll_position = snapshot.scroll_position();
4957                        }
4958                    });
4959
4960                    let line_elements = self.prepaint_lines(
4961                        start_row,
4962                        &mut line_layouts,
4963                        line_height,
4964                        scroll_pixel_position,
4965                        content_origin,
4966                        cx,
4967                    );
4968
4969                    cx.with_element_namespace("blocks", |cx| {
4970                        self.layout_blocks(
4971                            &mut blocks,
4972                            &hitbox,
4973                            line_height,
4974                            scroll_pixel_position,
4975                            cx,
4976                        );
4977                    });
4978
4979                    let cursors = self.collect_cursors(&snapshot, cx);
4980                    let visible_row_range = start_row..end_row;
4981                    let non_visible_cursors = cursors
4982                        .iter()
4983                        .any(move |c| !visible_row_range.contains(&c.0.row()));
4984
4985                    let visible_cursors = self.layout_visible_cursors(
4986                        &snapshot,
4987                        &selections,
4988                        start_row..end_row,
4989                        &line_layouts,
4990                        &text_hitbox,
4991                        content_origin,
4992                        scroll_position,
4993                        scroll_pixel_position,
4994                        line_height,
4995                        em_width,
4996                        autoscroll_containing_element,
4997                        cx,
4998                    );
4999
5000                    let scrollbar_layout = self.layout_scrollbar(
5001                        &snapshot,
5002                        bounds,
5003                        scroll_position,
5004                        height_in_lines,
5005                        non_visible_cursors,
5006                        cx,
5007                    );
5008
5009                    let gutter_settings = EditorSettings::get_global(cx).gutter;
5010
5011                    let mut _context_menu_visible = false;
5012                    let mut code_actions_indicator = None;
5013                    if let Some(newest_selection_head) = newest_selection_head {
5014                        if (start_row..end_row).contains(&newest_selection_head.row()) {
5015                            _context_menu_visible = self.layout_context_menu(
5016                                line_height,
5017                                &hitbox,
5018                                &text_hitbox,
5019                                content_origin,
5020                                start_row,
5021                                scroll_pixel_position,
5022                                &line_layouts,
5023                                newest_selection_head,
5024                                gutter_dimensions.width - gutter_dimensions.left_padding,
5025                                cx,
5026                            );
5027
5028                            let show_code_actions = snapshot
5029                                .show_code_actions
5030                                .unwrap_or_else(|| gutter_settings.code_actions);
5031                            if show_code_actions {
5032                                let newest_selection_point =
5033                                    newest_selection_head.to_point(&snapshot.display_snapshot);
5034                                let buffer = snapshot.buffer_snapshot.buffer_line_for_row(
5035                                    MultiBufferRow(newest_selection_point.row),
5036                                );
5037                                if let Some((buffer, range)) = buffer {
5038                                    let buffer_id = buffer.remote_id();
5039                                    let row = range.start.row;
5040                                    let has_test_indicator =
5041                                        self.editor.read(cx).tasks.contains_key(&(buffer_id, row));
5042
5043                                    if !has_test_indicator {
5044                                        code_actions_indicator = self
5045                                            .layout_code_actions_indicator(
5046                                                line_height,
5047                                                newest_selection_head,
5048                                                scroll_pixel_position,
5049                                                &gutter_dimensions,
5050                                                &gutter_hitbox,
5051                                                cx,
5052                                            );
5053                                    }
5054                                }
5055                            }
5056                        }
5057                    }
5058
5059                    let test_indicators = if gutter_settings.runnables {
5060                        self.layout_run_indicators(
5061                            line_height,
5062                            scroll_pixel_position,
5063                            &gutter_dimensions,
5064                            &gutter_hitbox,
5065                            &snapshot,
5066                            cx,
5067                        )
5068                    } else {
5069                        vec![]
5070                    };
5071
5072                    if !cx.has_active_drag() {
5073                        self.layout_hover_popovers(
5074                            &snapshot,
5075                            &hitbox,
5076                            &text_hitbox,
5077                            start_row..end_row,
5078                            content_origin,
5079                            scroll_pixel_position,
5080                            &line_layouts,
5081                            line_height,
5082                            em_width,
5083                            cx,
5084                        );
5085                    }
5086
5087                    let mouse_context_menu = self.layout_mouse_context_menu(cx);
5088
5089                    cx.with_element_namespace("gutter_fold_toggles", |cx| {
5090                        self.prepaint_gutter_fold_toggles(
5091                            &mut gutter_fold_toggles,
5092                            line_height,
5093                            &gutter_dimensions,
5094                            gutter_settings,
5095                            scroll_pixel_position,
5096                            &gutter_hitbox,
5097                            cx,
5098                        )
5099                    });
5100
5101                    let invisible_symbol_font_size = font_size / 2.;
5102                    let tab_invisible = cx
5103                        .text_system()
5104                        .shape_line(
5105                            "".into(),
5106                            invisible_symbol_font_size,
5107                            &[TextRun {
5108                                len: "".len(),
5109                                font: self.style.text.font(),
5110                                color: cx.theme().colors().editor_invisible,
5111                                background_color: None,
5112                                underline: None,
5113                                strikethrough: None,
5114                            }],
5115                        )
5116                        .unwrap();
5117                    let space_invisible = cx
5118                        .text_system()
5119                        .shape_line(
5120                            "".into(),
5121                            invisible_symbol_font_size,
5122                            &[TextRun {
5123                                len: "".len(),
5124                                font: self.style.text.font(),
5125                                color: cx.theme().colors().editor_invisible,
5126                                background_color: None,
5127                                underline: None,
5128                                strikethrough: None,
5129                            }],
5130                        )
5131                        .unwrap();
5132
5133                    EditorLayout {
5134                        mode: snapshot.mode,
5135                        position_map: Arc::new(PositionMap {
5136                            size: bounds.size,
5137                            scroll_pixel_position,
5138                            scroll_max,
5139                            line_layouts,
5140                            line_height,
5141                            em_width,
5142                            em_advance,
5143                            snapshot,
5144                        }),
5145                        visible_display_row_range: start_row..end_row,
5146                        wrap_guides,
5147                        indent_guides,
5148                        hitbox,
5149                        text_hitbox,
5150                        gutter_hitbox,
5151                        gutter_dimensions,
5152                        content_origin,
5153                        scrollbar_layout,
5154                        active_rows,
5155                        highlighted_rows,
5156                        highlighted_ranges,
5157                        highlighted_gutter_ranges,
5158                        redacted_ranges,
5159                        line_elements,
5160                        line_numbers,
5161                        display_hunks,
5162                        blamed_display_rows,
5163                        inline_blame,
5164                        blocks,
5165                        cursors,
5166                        visible_cursors,
5167                        selections,
5168                        mouse_context_menu,
5169                        test_indicators,
5170                        code_actions_indicator,
5171                        gutter_fold_toggles,
5172                        crease_trailers,
5173                        tab_invisible,
5174                        space_invisible,
5175                    }
5176                })
5177            })
5178        })
5179    }
5180
5181    fn paint(
5182        &mut self,
5183        _: Option<&GlobalElementId>,
5184        bounds: Bounds<gpui::Pixels>,
5185        _: &mut Self::RequestLayoutState,
5186        layout: &mut Self::PrepaintState,
5187        cx: &mut WindowContext,
5188    ) {
5189        let focus_handle = self.editor.focus_handle(cx);
5190        let key_context = self.editor.read(cx).key_context(cx);
5191        cx.set_focus_handle(&focus_handle);
5192        cx.set_key_context(key_context);
5193        cx.handle_input(
5194            &focus_handle,
5195            ElementInputHandler::new(bounds, self.editor.clone()),
5196        );
5197        self.register_actions(cx);
5198        self.register_key_listeners(cx, layout);
5199
5200        let text_style = TextStyleRefinement {
5201            font_size: Some(self.style.text.font_size),
5202            line_height: Some(self.style.text.line_height),
5203            ..Default::default()
5204        };
5205        let mouse_position = cx.mouse_position();
5206        let hovered_hunk = layout
5207            .display_hunks
5208            .iter()
5209            .find_map(|(hunk, hunk_hitbox)| match hunk {
5210                DisplayDiffHunk::Folded { .. } => None,
5211                DisplayDiffHunk::Unfolded {
5212                    diff_base_byte_range,
5213                    multi_buffer_range,
5214                    status,
5215                    ..
5216                } => {
5217                    if hunk_hitbox
5218                        .as_ref()
5219                        .map(|hitbox| hitbox.contains(&mouse_position))
5220                        .unwrap_or(false)
5221                    {
5222                        Some(HunkToExpand {
5223                            status: *status,
5224                            multi_buffer_range: multi_buffer_range.clone(),
5225                            diff_base_byte_range: diff_base_byte_range.clone(),
5226                        })
5227                    } else {
5228                        None
5229                    }
5230                }
5231            });
5232        let rem_size = self.rem_size(cx);
5233        cx.with_rem_size(rem_size, |cx| {
5234            cx.with_text_style(Some(text_style), |cx| {
5235                cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
5236                    self.paint_mouse_listeners(layout, hovered_hunk, cx);
5237                    self.paint_background(layout, cx);
5238                    self.paint_indent_guides(layout, cx);
5239
5240                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
5241                        self.paint_blamed_display_rows(layout, cx);
5242                        self.paint_line_numbers(layout, cx);
5243                    }
5244
5245                    self.paint_text(layout, cx);
5246
5247                    if !layout.blocks.is_empty() {
5248                        cx.with_element_namespace("blocks", |cx| {
5249                            self.paint_blocks(layout, cx);
5250                        });
5251                    }
5252
5253                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
5254                        self.paint_gutter_highlights(layout, cx);
5255                        self.paint_gutter_indicators(layout, cx);
5256                    }
5257
5258                    self.paint_scrollbar(layout, cx);
5259                    self.paint_mouse_context_menu(layout, cx);
5260                });
5261            })
5262        })
5263    }
5264}
5265
5266impl IntoElement for EditorElement {
5267    type Element = Self;
5268
5269    fn into_element(self) -> Self::Element {
5270        self
5271    }
5272}
5273
5274pub struct EditorLayout {
5275    position_map: Arc<PositionMap>,
5276    hitbox: Hitbox,
5277    text_hitbox: Hitbox,
5278    gutter_hitbox: Hitbox,
5279    gutter_dimensions: GutterDimensions,
5280    content_origin: gpui::Point<Pixels>,
5281    scrollbar_layout: Option<ScrollbarLayout>,
5282    mode: EditorMode,
5283    wrap_guides: SmallVec<[(Pixels, bool); 2]>,
5284    indent_guides: Option<Vec<IndentGuideLayout>>,
5285    visible_display_row_range: Range<DisplayRow>,
5286    active_rows: BTreeMap<DisplayRow, bool>,
5287    highlighted_rows: BTreeMap<DisplayRow, Hsla>,
5288    line_elements: SmallVec<[AnyElement; 1]>,
5289    line_numbers: Vec<Option<ShapedLine>>,
5290    display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
5291    blamed_display_rows: Option<Vec<AnyElement>>,
5292    inline_blame: Option<AnyElement>,
5293    blocks: Vec<BlockLayout>,
5294    highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
5295    highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
5296    redacted_ranges: Vec<Range<DisplayPoint>>,
5297    cursors: Vec<(DisplayPoint, Hsla)>,
5298    visible_cursors: Vec<CursorLayout>,
5299    selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
5300    code_actions_indicator: Option<AnyElement>,
5301    test_indicators: Vec<AnyElement>,
5302    gutter_fold_toggles: Vec<Option<AnyElement>>,
5303    crease_trailers: Vec<Option<CreaseTrailerLayout>>,
5304    mouse_context_menu: Option<AnyElement>,
5305    tab_invisible: ShapedLine,
5306    space_invisible: ShapedLine,
5307}
5308
5309impl EditorLayout {
5310    fn line_end_overshoot(&self) -> Pixels {
5311        0.15 * self.position_map.line_height
5312    }
5313}
5314
5315struct ColoredRange<T> {
5316    start: T,
5317    end: T,
5318    color: Hsla,
5319}
5320
5321#[derive(Clone)]
5322struct ScrollbarLayout {
5323    hitbox: Hitbox,
5324    visible_row_range: Range<f32>,
5325    visible: bool,
5326    row_height: Pixels,
5327    thumb_height: Pixels,
5328}
5329
5330impl ScrollbarLayout {
5331    const BORDER_WIDTH: Pixels = px(1.0);
5332    const LINE_MARKER_HEIGHT: Pixels = px(2.0);
5333    const MIN_MARKER_HEIGHT: Pixels = px(5.0);
5334    const MIN_THUMB_HEIGHT: Pixels = px(20.0);
5335
5336    fn thumb_bounds(&self) -> Bounds<Pixels> {
5337        let thumb_top = self.y_for_row(self.visible_row_range.start);
5338        let thumb_bottom = thumb_top + self.thumb_height;
5339        Bounds::from_corners(
5340            point(self.hitbox.left(), thumb_top),
5341            point(self.hitbox.right(), thumb_bottom),
5342        )
5343    }
5344
5345    fn y_for_row(&self, row: f32) -> Pixels {
5346        self.hitbox.top() + row * self.row_height
5347    }
5348
5349    fn marker_quads_for_ranges(
5350        &self,
5351        row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
5352        column: Option<usize>,
5353    ) -> Vec<PaintQuad> {
5354        struct MinMax {
5355            min: Pixels,
5356            max: Pixels,
5357        }
5358        let (x_range, height_limit) = if let Some(column) = column {
5359            let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
5360            let start = Self::BORDER_WIDTH + (column as f32 * column_width);
5361            let end = start + column_width;
5362            (
5363                Range { start, end },
5364                MinMax {
5365                    min: Self::MIN_MARKER_HEIGHT,
5366                    max: px(f32::MAX),
5367                },
5368            )
5369        } else {
5370            (
5371                Range {
5372                    start: Self::BORDER_WIDTH,
5373                    end: self.hitbox.size.width,
5374                },
5375                MinMax {
5376                    min: Self::LINE_MARKER_HEIGHT,
5377                    max: Self::LINE_MARKER_HEIGHT,
5378                },
5379            )
5380        };
5381
5382        let row_to_y = |row: DisplayRow| row.as_f32() * self.row_height;
5383        let mut pixel_ranges = row_ranges
5384            .into_iter()
5385            .map(|range| {
5386                let start_y = row_to_y(range.start);
5387                let end_y = row_to_y(range.end)
5388                    + self.row_height.max(height_limit.min).min(height_limit.max);
5389                ColoredRange {
5390                    start: start_y,
5391                    end: end_y,
5392                    color: range.color,
5393                }
5394            })
5395            .peekable();
5396
5397        let mut quads = Vec::new();
5398        while let Some(mut pixel_range) = pixel_ranges.next() {
5399            while let Some(next_pixel_range) = pixel_ranges.peek() {
5400                if pixel_range.end >= next_pixel_range.start - px(1.0)
5401                    && pixel_range.color == next_pixel_range.color
5402                {
5403                    pixel_range.end = next_pixel_range.end.max(pixel_range.end);
5404                    pixel_ranges.next();
5405                } else {
5406                    break;
5407                }
5408            }
5409
5410            let bounds = Bounds::from_corners(
5411                point(x_range.start, pixel_range.start),
5412                point(x_range.end, pixel_range.end),
5413            );
5414            quads.push(quad(
5415                bounds,
5416                Corners::default(),
5417                pixel_range.color,
5418                Edges::default(),
5419                Hsla::transparent_black(),
5420            ));
5421        }
5422
5423        quads
5424    }
5425}
5426
5427struct CreaseTrailerLayout {
5428    element: AnyElement,
5429    bounds: Bounds<Pixels>,
5430}
5431
5432struct PositionMap {
5433    size: Size<Pixels>,
5434    line_height: Pixels,
5435    scroll_pixel_position: gpui::Point<Pixels>,
5436    scroll_max: gpui::Point<f32>,
5437    em_width: Pixels,
5438    em_advance: Pixels,
5439    line_layouts: Vec<LineWithInvisibles>,
5440    snapshot: EditorSnapshot,
5441}
5442
5443#[derive(Debug, Copy, Clone)]
5444pub struct PointForPosition {
5445    pub previous_valid: DisplayPoint,
5446    pub next_valid: DisplayPoint,
5447    pub exact_unclipped: DisplayPoint,
5448    pub column_overshoot_after_line_end: u32,
5449}
5450
5451impl PointForPosition {
5452    pub fn as_valid(&self) -> Option<DisplayPoint> {
5453        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
5454            Some(self.previous_valid)
5455        } else {
5456            None
5457        }
5458    }
5459}
5460
5461impl PositionMap {
5462    fn point_for_position(
5463        &self,
5464        text_bounds: Bounds<Pixels>,
5465        position: gpui::Point<Pixels>,
5466    ) -> PointForPosition {
5467        let scroll_position = self.snapshot.scroll_position();
5468        let position = position - text_bounds.origin;
5469        let y = position.y.max(px(0.)).min(self.size.height);
5470        let x = position.x + (scroll_position.x * self.em_width);
5471        let row = ((y / self.line_height) + scroll_position.y) as u32;
5472
5473        let (column, x_overshoot_after_line_end) = if let Some(line) = self
5474            .line_layouts
5475            .get(row as usize - scroll_position.y as usize)
5476        {
5477            if let Some(ix) = line.index_for_x(x) {
5478                (ix as u32, px(0.))
5479            } else {
5480                (line.len as u32, px(0.).max(x - line.width))
5481            }
5482        } else {
5483            (0, x)
5484        };
5485
5486        let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
5487        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
5488        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
5489
5490        let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
5491        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
5492        PointForPosition {
5493            previous_valid,
5494            next_valid,
5495            exact_unclipped,
5496            column_overshoot_after_line_end,
5497        }
5498    }
5499}
5500
5501struct BlockLayout {
5502    row: DisplayRow,
5503    element: AnyElement,
5504    available_space: Size<AvailableSpace>,
5505    style: BlockStyle,
5506}
5507
5508fn layout_line(
5509    row: DisplayRow,
5510    snapshot: &EditorSnapshot,
5511    style: &EditorStyle,
5512    cx: &mut WindowContext,
5513) -> LineWithInvisibles {
5514    let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
5515    LineWithInvisibles::from_chunks(chunks, &style.text, MAX_LINE_LEN, 1, &[], snapshot.mode, cx)
5516        .pop()
5517        .unwrap()
5518}
5519
5520#[derive(Debug)]
5521pub struct IndentGuideLayout {
5522    origin: gpui::Point<Pixels>,
5523    length: Pixels,
5524    single_indent_width: Pixels,
5525    depth: u32,
5526    active: bool,
5527    settings: IndentGuideSettings,
5528}
5529
5530pub struct CursorLayout {
5531    origin: gpui::Point<Pixels>,
5532    block_width: Pixels,
5533    line_height: Pixels,
5534    color: Hsla,
5535    shape: CursorShape,
5536    block_text: Option<ShapedLine>,
5537    cursor_name: Option<AnyElement>,
5538}
5539
5540#[derive(Debug)]
5541pub struct CursorName {
5542    string: SharedString,
5543    color: Hsla,
5544    is_top_row: bool,
5545}
5546
5547impl CursorLayout {
5548    pub fn new(
5549        origin: gpui::Point<Pixels>,
5550        block_width: Pixels,
5551        line_height: Pixels,
5552        color: Hsla,
5553        shape: CursorShape,
5554        block_text: Option<ShapedLine>,
5555    ) -> CursorLayout {
5556        CursorLayout {
5557            origin,
5558            block_width,
5559            line_height,
5560            color,
5561            shape,
5562            block_text,
5563            cursor_name: None,
5564        }
5565    }
5566
5567    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
5568        Bounds {
5569            origin: self.origin + origin,
5570            size: size(self.block_width, self.line_height),
5571        }
5572    }
5573
5574    fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
5575        match self.shape {
5576            CursorShape::Bar => Bounds {
5577                origin: self.origin + origin,
5578                size: size(px(2.0), self.line_height),
5579            },
5580            CursorShape::Block | CursorShape::Hollow => Bounds {
5581                origin: self.origin + origin,
5582                size: size(self.block_width, self.line_height),
5583            },
5584            CursorShape::Underscore => Bounds {
5585                origin: self.origin
5586                    + origin
5587                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
5588                size: size(self.block_width, px(2.0)),
5589            },
5590        }
5591    }
5592
5593    pub fn layout(
5594        &mut self,
5595        origin: gpui::Point<Pixels>,
5596        cursor_name: Option<CursorName>,
5597        cx: &mut WindowContext,
5598    ) {
5599        if let Some(cursor_name) = cursor_name {
5600            let bounds = self.bounds(origin);
5601            let text_size = self.line_height / 1.5;
5602
5603            let name_origin = if cursor_name.is_top_row {
5604                point(bounds.right() - px(1.), bounds.top())
5605            } else {
5606                point(bounds.left(), bounds.top() - text_size / 2. - px(1.))
5607            };
5608            let mut name_element = div()
5609                .bg(self.color)
5610                .text_size(text_size)
5611                .px_0p5()
5612                .line_height(text_size + px(2.))
5613                .text_color(cursor_name.color)
5614                .child(cursor_name.string.clone())
5615                .into_any_element();
5616
5617            name_element.prepaint_as_root(
5618                name_origin,
5619                size(AvailableSpace::MinContent, AvailableSpace::MinContent),
5620                cx,
5621            );
5622
5623            self.cursor_name = Some(name_element);
5624        }
5625    }
5626
5627    pub fn paint(&mut self, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
5628        let bounds = self.bounds(origin);
5629
5630        //Draw background or border quad
5631        let cursor = if matches!(self.shape, CursorShape::Hollow) {
5632            outline(bounds, self.color)
5633        } else {
5634            fill(bounds, self.color)
5635        };
5636
5637        if let Some(name) = &mut self.cursor_name {
5638            name.paint(cx);
5639        }
5640
5641        cx.paint_quad(cursor);
5642
5643        if let Some(block_text) = &self.block_text {
5644            block_text
5645                .paint(self.origin + origin, self.line_height, cx)
5646                .log_err();
5647        }
5648    }
5649
5650    pub fn shape(&self) -> CursorShape {
5651        self.shape
5652    }
5653}
5654
5655#[derive(Debug)]
5656pub struct HighlightedRange {
5657    pub start_y: Pixels,
5658    pub line_height: Pixels,
5659    pub lines: Vec<HighlightedRangeLine>,
5660    pub color: Hsla,
5661    pub corner_radius: Pixels,
5662}
5663
5664#[derive(Debug)]
5665pub struct HighlightedRangeLine {
5666    pub start_x: Pixels,
5667    pub end_x: Pixels,
5668}
5669
5670impl HighlightedRange {
5671    pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut WindowContext) {
5672        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
5673            self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
5674            self.paint_lines(
5675                self.start_y + self.line_height,
5676                &self.lines[1..],
5677                bounds,
5678                cx,
5679            );
5680        } else {
5681            self.paint_lines(self.start_y, &self.lines, bounds, cx);
5682        }
5683    }
5684
5685    fn paint_lines(
5686        &self,
5687        start_y: Pixels,
5688        lines: &[HighlightedRangeLine],
5689        _bounds: Bounds<Pixels>,
5690        cx: &mut WindowContext,
5691    ) {
5692        if lines.is_empty() {
5693            return;
5694        }
5695
5696        let first_line = lines.first().unwrap();
5697        let last_line = lines.last().unwrap();
5698
5699        let first_top_left = point(first_line.start_x, start_y);
5700        let first_top_right = point(first_line.end_x, start_y);
5701
5702        let curve_height = point(Pixels::ZERO, self.corner_radius);
5703        let curve_width = |start_x: Pixels, end_x: Pixels| {
5704            let max = (end_x - start_x) / 2.;
5705            let width = if max < self.corner_radius {
5706                max
5707            } else {
5708                self.corner_radius
5709            };
5710
5711            point(width, Pixels::ZERO)
5712        };
5713
5714        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
5715        let mut path = gpui::Path::new(first_top_right - top_curve_width);
5716        path.curve_to(first_top_right + curve_height, first_top_right);
5717
5718        let mut iter = lines.iter().enumerate().peekable();
5719        while let Some((ix, line)) = iter.next() {
5720            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
5721
5722            if let Some((_, next_line)) = iter.peek() {
5723                let next_top_right = point(next_line.end_x, bottom_right.y);
5724
5725                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
5726                    Ordering::Equal => {
5727                        path.line_to(bottom_right);
5728                    }
5729                    Ordering::Less => {
5730                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
5731                        path.line_to(bottom_right - curve_height);
5732                        if self.corner_radius > Pixels::ZERO {
5733                            path.curve_to(bottom_right - curve_width, bottom_right);
5734                        }
5735                        path.line_to(next_top_right + curve_width);
5736                        if self.corner_radius > Pixels::ZERO {
5737                            path.curve_to(next_top_right + curve_height, next_top_right);
5738                        }
5739                    }
5740                    Ordering::Greater => {
5741                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
5742                        path.line_to(bottom_right - curve_height);
5743                        if self.corner_radius > Pixels::ZERO {
5744                            path.curve_to(bottom_right + curve_width, bottom_right);
5745                        }
5746                        path.line_to(next_top_right - curve_width);
5747                        if self.corner_radius > Pixels::ZERO {
5748                            path.curve_to(next_top_right + curve_height, next_top_right);
5749                        }
5750                    }
5751                }
5752            } else {
5753                let curve_width = curve_width(line.start_x, line.end_x);
5754                path.line_to(bottom_right - curve_height);
5755                if self.corner_radius > Pixels::ZERO {
5756                    path.curve_to(bottom_right - curve_width, bottom_right);
5757                }
5758
5759                let bottom_left = point(line.start_x, bottom_right.y);
5760                path.line_to(bottom_left + curve_width);
5761                if self.corner_radius > Pixels::ZERO {
5762                    path.curve_to(bottom_left - curve_height, bottom_left);
5763                }
5764            }
5765        }
5766
5767        if first_line.start_x > last_line.start_x {
5768            let curve_width = curve_width(last_line.start_x, first_line.start_x);
5769            let second_top_left = point(last_line.start_x, start_y + self.line_height);
5770            path.line_to(second_top_left + curve_height);
5771            if self.corner_radius > Pixels::ZERO {
5772                path.curve_to(second_top_left + curve_width, second_top_left);
5773            }
5774            let first_bottom_left = point(first_line.start_x, second_top_left.y);
5775            path.line_to(first_bottom_left - curve_width);
5776            if self.corner_radius > Pixels::ZERO {
5777                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
5778            }
5779        }
5780
5781        path.line_to(first_top_left + curve_height);
5782        if self.corner_radius > Pixels::ZERO {
5783            path.curve_to(first_top_left + top_curve_width, first_top_left);
5784        }
5785        path.line_to(first_top_right - top_curve_width);
5786
5787        cx.paint_path(path, self.color);
5788    }
5789}
5790
5791pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
5792    (delta.pow(1.5) / 100.0).into()
5793}
5794
5795fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
5796    (delta.pow(1.2) / 300.0).into()
5797}
5798
5799#[cfg(test)]
5800mod tests {
5801    use super::*;
5802    use crate::{
5803        display_map::{BlockDisposition, BlockProperties},
5804        editor_tests::{init_test, update_test_language_settings},
5805        Editor, MultiBuffer,
5806    };
5807    use gpui::{TestAppContext, VisualTestContext};
5808    use language::language_settings;
5809    use log::info;
5810    use std::num::NonZeroU32;
5811    use ui::Context;
5812    use util::test::sample_text;
5813
5814    #[gpui::test]
5815    fn test_shape_line_numbers(cx: &mut TestAppContext) {
5816        init_test(cx, |_| {});
5817        let window = cx.add_window(|cx| {
5818            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
5819            Editor::new(EditorMode::Full, buffer, None, true, cx)
5820        });
5821
5822        let editor = window.root(cx).unwrap();
5823        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5824        let element = EditorElement::new(&editor, style);
5825        let snapshot = window.update(cx, |editor, cx| editor.snapshot(cx)).unwrap();
5826
5827        let layouts = cx
5828            .update_window(*window, |_, cx| {
5829                element.layout_line_numbers(
5830                    DisplayRow(0)..DisplayRow(6),
5831                    (0..6).map(MultiBufferRow).map(Some),
5832                    &Default::default(),
5833                    Some(DisplayPoint::new(DisplayRow(0), 0)),
5834                    &snapshot,
5835                    cx,
5836                )
5837            })
5838            .unwrap();
5839        assert_eq!(layouts.len(), 6);
5840
5841        let relative_rows = window
5842            .update(cx, |editor, cx| {
5843                let snapshot = editor.snapshot(cx);
5844                element.calculate_relative_line_numbers(
5845                    &snapshot,
5846                    &(DisplayRow(0)..DisplayRow(6)),
5847                    Some(DisplayRow(3)),
5848                )
5849            })
5850            .unwrap();
5851        assert_eq!(relative_rows[&DisplayRow(0)], 3);
5852        assert_eq!(relative_rows[&DisplayRow(1)], 2);
5853        assert_eq!(relative_rows[&DisplayRow(2)], 1);
5854        // current line has no relative number
5855        assert_eq!(relative_rows[&DisplayRow(4)], 1);
5856        assert_eq!(relative_rows[&DisplayRow(5)], 2);
5857
5858        // works if cursor is before screen
5859        let relative_rows = window
5860            .update(cx, |editor, cx| {
5861                let snapshot = editor.snapshot(cx);
5862                element.calculate_relative_line_numbers(
5863                    &snapshot,
5864                    &(DisplayRow(3)..DisplayRow(6)),
5865                    Some(DisplayRow(1)),
5866                )
5867            })
5868            .unwrap();
5869        assert_eq!(relative_rows.len(), 3);
5870        assert_eq!(relative_rows[&DisplayRow(3)], 2);
5871        assert_eq!(relative_rows[&DisplayRow(4)], 3);
5872        assert_eq!(relative_rows[&DisplayRow(5)], 4);
5873
5874        // works if cursor is after screen
5875        let relative_rows = window
5876            .update(cx, |editor, cx| {
5877                let snapshot = editor.snapshot(cx);
5878                element.calculate_relative_line_numbers(
5879                    &snapshot,
5880                    &(DisplayRow(0)..DisplayRow(3)),
5881                    Some(DisplayRow(6)),
5882                )
5883            })
5884            .unwrap();
5885        assert_eq!(relative_rows.len(), 3);
5886        assert_eq!(relative_rows[&DisplayRow(0)], 5);
5887        assert_eq!(relative_rows[&DisplayRow(1)], 4);
5888        assert_eq!(relative_rows[&DisplayRow(2)], 3);
5889    }
5890
5891    #[gpui::test]
5892    async fn test_vim_visual_selections(cx: &mut TestAppContext) {
5893        init_test(cx, |_| {});
5894
5895        let window = cx.add_window(|cx| {
5896            let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
5897            Editor::new(EditorMode::Full, buffer, None, true, cx)
5898        });
5899        let cx = &mut VisualTestContext::from_window(*window, cx);
5900        let editor = window.root(cx).unwrap();
5901        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5902
5903        window
5904            .update(cx, |editor, cx| {
5905                editor.cursor_shape = CursorShape::Block;
5906                editor.change_selections(None, cx, |s| {
5907                    s.select_ranges([
5908                        Point::new(0, 0)..Point::new(1, 0),
5909                        Point::new(3, 2)..Point::new(3, 3),
5910                        Point::new(5, 6)..Point::new(6, 0),
5911                    ]);
5912                });
5913            })
5914            .unwrap();
5915
5916        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
5917            EditorElement::new(&editor, style)
5918        });
5919
5920        assert_eq!(state.selections.len(), 1);
5921        let local_selections = &state.selections[0].1;
5922        assert_eq!(local_selections.len(), 3);
5923        // moves cursor back one line
5924        assert_eq!(
5925            local_selections[0].head,
5926            DisplayPoint::new(DisplayRow(0), 6)
5927        );
5928        assert_eq!(
5929            local_selections[0].range,
5930            DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
5931        );
5932
5933        // moves cursor back one column
5934        assert_eq!(
5935            local_selections[1].range,
5936            DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
5937        );
5938        assert_eq!(
5939            local_selections[1].head,
5940            DisplayPoint::new(DisplayRow(3), 2)
5941        );
5942
5943        // leaves cursor on the max point
5944        assert_eq!(
5945            local_selections[2].range,
5946            DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
5947        );
5948        assert_eq!(
5949            local_selections[2].head,
5950            DisplayPoint::new(DisplayRow(6), 0)
5951        );
5952
5953        // active lines does not include 1 (even though the range of the selection does)
5954        assert_eq!(
5955            state.active_rows.keys().cloned().collect::<Vec<_>>(),
5956            vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
5957        );
5958
5959        // multi-buffer support
5960        // in DisplayPoint coordinates, this is what we're dealing with:
5961        //  0: [[file
5962        //  1:   header
5963        //  2:   section]]
5964        //  3: aaaaaa
5965        //  4: bbbbbb
5966        //  5: cccccc
5967        //  6:
5968        //  7: [[footer]]
5969        //  8: [[header]]
5970        //  9: ffffff
5971        // 10: gggggg
5972        // 11: hhhhhh
5973        // 12:
5974        // 13: [[footer]]
5975        // 14: [[file
5976        // 15:   header
5977        // 16:   section]]
5978        // 17: bbbbbb
5979        // 18: cccccc
5980        // 19: dddddd
5981        // 20: [[footer]]
5982        let window = cx.add_window(|cx| {
5983            let buffer = MultiBuffer::build_multi(
5984                [
5985                    (
5986                        &(sample_text(8, 6, 'a') + "\n"),
5987                        vec![
5988                            Point::new(0, 0)..Point::new(3, 0),
5989                            Point::new(4, 0)..Point::new(7, 0),
5990                        ],
5991                    ),
5992                    (
5993                        &(sample_text(8, 6, 'a') + "\n"),
5994                        vec![Point::new(1, 0)..Point::new(3, 0)],
5995                    ),
5996                ],
5997                cx,
5998            );
5999            Editor::new(EditorMode::Full, buffer, None, true, cx)
6000        });
6001        let editor = window.root(cx).unwrap();
6002        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6003        let _state = window.update(cx, |editor, cx| {
6004            editor.cursor_shape = CursorShape::Block;
6005            editor.change_selections(None, cx, |s| {
6006                s.select_display_ranges([
6007                    DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0),
6008                    DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0),
6009                ]);
6010            });
6011        });
6012
6013        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6014            EditorElement::new(&editor, style)
6015        });
6016        assert_eq!(state.selections.len(), 1);
6017        let local_selections = &state.selections[0].1;
6018        assert_eq!(local_selections.len(), 2);
6019
6020        // moves cursor on excerpt boundary back a line
6021        // and doesn't allow selection to bleed through
6022        assert_eq!(
6023            local_selections[0].range,
6024            DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0)
6025        );
6026        assert_eq!(
6027            local_selections[0].head,
6028            DisplayPoint::new(DisplayRow(6), 0)
6029        );
6030        // moves cursor on buffer boundary back two lines
6031        // and doesn't allow selection to bleed through
6032        assert_eq!(
6033            local_selections[1].range,
6034            DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0)
6035        );
6036        assert_eq!(
6037            local_selections[1].head,
6038            DisplayPoint::new(DisplayRow(12), 0)
6039        );
6040    }
6041
6042    #[gpui::test]
6043    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
6044        init_test(cx, |_| {});
6045
6046        let window = cx.add_window(|cx| {
6047            let buffer = MultiBuffer::build_simple("", cx);
6048            Editor::new(EditorMode::Full, buffer, None, true, cx)
6049        });
6050        let cx = &mut VisualTestContext::from_window(*window, cx);
6051        let editor = window.root(cx).unwrap();
6052        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6053        window
6054            .update(cx, |editor, cx| {
6055                editor.set_placeholder_text("hello", cx);
6056                editor.insert_blocks(
6057                    [BlockProperties {
6058                        style: BlockStyle::Fixed,
6059                        disposition: BlockDisposition::Above,
6060                        height: 3,
6061                        position: Anchor::min(),
6062                        render: Box::new(|_| div().into_any()),
6063                    }],
6064                    None,
6065                    cx,
6066                );
6067
6068                // Blur the editor so that it displays placeholder text.
6069                cx.blur();
6070            })
6071            .unwrap();
6072
6073        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6074            EditorElement::new(&editor, style)
6075        });
6076        assert_eq!(state.position_map.line_layouts.len(), 4);
6077        assert_eq!(
6078            state
6079                .line_numbers
6080                .iter()
6081                .map(Option::is_some)
6082                .collect::<Vec<_>>(),
6083            &[false, false, false, true]
6084        );
6085    }
6086
6087    #[gpui::test]
6088    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
6089        const TAB_SIZE: u32 = 4;
6090
6091        let input_text = "\t \t|\t| a b";
6092        let expected_invisibles = vec![
6093            Invisible::Tab {
6094                line_start_offset: 0,
6095                line_end_offset: TAB_SIZE as usize,
6096            },
6097            Invisible::Whitespace {
6098                line_offset: TAB_SIZE as usize,
6099            },
6100            Invisible::Tab {
6101                line_start_offset: TAB_SIZE as usize + 1,
6102                line_end_offset: TAB_SIZE as usize * 2,
6103            },
6104            Invisible::Tab {
6105                line_start_offset: TAB_SIZE as usize * 2 + 1,
6106                line_end_offset: TAB_SIZE as usize * 3,
6107            },
6108            Invisible::Whitespace {
6109                line_offset: TAB_SIZE as usize * 3 + 1,
6110            },
6111            Invisible::Whitespace {
6112                line_offset: TAB_SIZE as usize * 3 + 3,
6113            },
6114        ];
6115        assert_eq!(
6116            expected_invisibles.len(),
6117            input_text
6118                .chars()
6119                .filter(|initial_char| initial_char.is_whitespace())
6120                .count(),
6121            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
6122        );
6123
6124        init_test(cx, |s| {
6125            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6126            s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
6127        });
6128
6129        let actual_invisibles =
6130            collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, px(500.0));
6131
6132        assert_eq!(expected_invisibles, actual_invisibles);
6133    }
6134
6135    #[gpui::test]
6136    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
6137        init_test(cx, |s| {
6138            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6139            s.defaults.tab_size = NonZeroU32::new(4);
6140        });
6141
6142        for editor_mode_without_invisibles in [
6143            EditorMode::SingleLine { auto_width: false },
6144            EditorMode::AutoHeight { max_lines: 100 },
6145        ] {
6146            let invisibles = collect_invisibles_from_new_editor(
6147                cx,
6148                editor_mode_without_invisibles,
6149                "\t\t\t| | a b",
6150                px(500.0),
6151            );
6152            assert!(invisibles.is_empty(),
6153                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
6154        }
6155    }
6156
6157    #[gpui::test]
6158    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
6159        let tab_size = 4;
6160        let input_text = "a\tbcd     ".repeat(9);
6161        let repeated_invisibles = [
6162            Invisible::Tab {
6163                line_start_offset: 1,
6164                line_end_offset: tab_size as usize,
6165            },
6166            Invisible::Whitespace {
6167                line_offset: tab_size as usize + 3,
6168            },
6169            Invisible::Whitespace {
6170                line_offset: tab_size as usize + 4,
6171            },
6172            Invisible::Whitespace {
6173                line_offset: tab_size as usize + 5,
6174            },
6175            Invisible::Whitespace {
6176                line_offset: tab_size as usize + 6,
6177            },
6178            Invisible::Whitespace {
6179                line_offset: tab_size as usize + 7,
6180            },
6181        ];
6182        let expected_invisibles = std::iter::once(repeated_invisibles)
6183            .cycle()
6184            .take(9)
6185            .flatten()
6186            .collect::<Vec<_>>();
6187        assert_eq!(
6188            expected_invisibles.len(),
6189            input_text
6190                .chars()
6191                .filter(|initial_char| initial_char.is_whitespace())
6192                .count(),
6193            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
6194        );
6195        info!("Expected invisibles: {expected_invisibles:?}");
6196
6197        init_test(cx, |_| {});
6198
6199        // Put the same string with repeating whitespace pattern into editors of various size,
6200        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
6201        let resize_step = 10.0;
6202        let mut editor_width = 200.0;
6203        while editor_width <= 1000.0 {
6204            update_test_language_settings(cx, |s| {
6205                s.defaults.tab_size = NonZeroU32::new(tab_size);
6206                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6207                s.defaults.preferred_line_length = Some(editor_width as u32);
6208                s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
6209            });
6210
6211            let actual_invisibles = collect_invisibles_from_new_editor(
6212                cx,
6213                EditorMode::Full,
6214                &input_text,
6215                px(editor_width),
6216            );
6217
6218            // Whatever the editor size is, ensure it has the same invisible kinds in the same order
6219            // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
6220            let mut i = 0;
6221            for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
6222                i = actual_index;
6223                match expected_invisibles.get(i) {
6224                    Some(expected_invisible) => match (expected_invisible, actual_invisible) {
6225                        (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
6226                        | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
6227                        _ => {
6228                            panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
6229                        }
6230                    },
6231                    None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
6232                }
6233            }
6234            let missing_expected_invisibles = &expected_invisibles[i + 1..];
6235            assert!(
6236                missing_expected_invisibles.is_empty(),
6237                "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
6238            );
6239
6240            editor_width += resize_step;
6241        }
6242    }
6243
6244    fn collect_invisibles_from_new_editor(
6245        cx: &mut TestAppContext,
6246        editor_mode: EditorMode,
6247        input_text: &str,
6248        editor_width: Pixels,
6249    ) -> Vec<Invisible> {
6250        info!(
6251            "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
6252            editor_width.0
6253        );
6254        let window = cx.add_window(|cx| {
6255            let buffer = MultiBuffer::build_simple(&input_text, cx);
6256            Editor::new(editor_mode, buffer, None, true, cx)
6257        });
6258        let cx = &mut VisualTestContext::from_window(*window, cx);
6259        let editor = window.root(cx).unwrap();
6260        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6261        window
6262            .update(cx, |editor, cx| {
6263                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
6264                editor.set_wrap_width(Some(editor_width), cx);
6265            })
6266            .unwrap();
6267        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6268            EditorElement::new(&editor, style)
6269        });
6270        state
6271            .position_map
6272            .line_layouts
6273            .iter()
6274            .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
6275            .cloned()
6276            .collect()
6277    }
6278}
6279
6280pub fn register_action<T: Action>(
6281    view: &View<Editor>,
6282    cx: &mut WindowContext,
6283    listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
6284) {
6285    let view = view.clone();
6286    cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
6287        let action = action.downcast_ref().unwrap();
6288        if phase == DispatchPhase::Bubble {
6289            view.update(cx, |editor, cx| {
6290                listener(editor, action, cx);
6291            })
6292        }
6293    })
6294}
6295
6296fn compute_auto_height_layout(
6297    editor: &mut Editor,
6298    max_lines: usize,
6299    max_line_number_width: Pixels,
6300    known_dimensions: Size<Option<Pixels>>,
6301    available_width: AvailableSpace,
6302    cx: &mut ViewContext<Editor>,
6303) -> Option<Size<Pixels>> {
6304    let width = known_dimensions.width.or_else(|| {
6305        if let AvailableSpace::Definite(available_width) = available_width {
6306            Some(available_width)
6307        } else {
6308            None
6309        }
6310    })?;
6311    if let Some(height) = known_dimensions.height {
6312        return Some(size(width, height));
6313    }
6314
6315    let style = editor.style.as_ref().unwrap();
6316    let font_id = cx.text_system().resolve_font(&style.text.font());
6317    let font_size = style.text.font_size.to_pixels(cx.rem_size());
6318    let line_height = style.text.line_height_in_pixels(cx.rem_size());
6319    let em_width = cx
6320        .text_system()
6321        .typographic_bounds(font_id, font_size, 'm')
6322        .unwrap()
6323        .size
6324        .width;
6325
6326    let mut snapshot = editor.snapshot(cx);
6327    let gutter_dimensions =
6328        snapshot.gutter_dimensions(font_id, font_size, em_width, max_line_number_width, cx);
6329
6330    editor.gutter_dimensions = gutter_dimensions;
6331    let text_width = width - gutter_dimensions.width;
6332    let overscroll = size(em_width, px(0.));
6333
6334    let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
6335    if editor.set_wrap_width(Some(editor_width), cx) {
6336        snapshot = editor.snapshot(cx);
6337    }
6338
6339    let scroll_height = Pixels::from(snapshot.max_point().row().next_row().0) * line_height;
6340    let height = scroll_height
6341        .max(line_height)
6342        .min(line_height * max_lines as f32);
6343
6344    Some(size(width, height))
6345}