element.rs

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