element.rs

   1use crate::{
   2    blame_entry_tooltip::{blame_entry_relative_timestamp, BlameEntryTooltip},
   3    code_context_menus::CodeActionsMenu,
   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_offset = match context_menu_origin {
2905            crate::ContextMenuOrigin::EditorPoint(display_point) => {
2906                let cursor_row_layout =
2907                    &line_layouts[display_point.row().minus(start_row) as usize];
2908                gpui::Point {
2909                    x: cursor_row_layout.x_for_index(display_point.column() as usize)
2910                        - scroll_pixel_position.x,
2911                    y: display_point.row().next_row().as_f32() * line_height
2912                        - scroll_pixel_position.y,
2913                }
2914            }
2915            crate::ContextMenuOrigin::GutterIndicator(row) => {
2916                // 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
2917                // text field.
2918                gpui::Point {
2919                    x: -gutter_overshoot,
2920                    y: row.next_row().as_f32() * line_height - scroll_pixel_position.y,
2921                }
2922            }
2923        };
2924
2925        // If the context menu's max height won't fit below, then flip it above the line and display
2926        // it in reverse order. If the available space above is less than below.
2927        let unconstrained_max_height = line_height * 12. + POPOVER_Y_PADDING;
2928        let min_height = line_height * 3. + POPOVER_Y_PADDING;
2929        let target_position = content_origin + target_offset;
2930        let y_overflows_below = target_position.y + unconstrained_max_height > text_hitbox.bottom();
2931        let bottom_y_when_flipped = target_position.y - line_height;
2932        let available_above = bottom_y_when_flipped - text_hitbox.top();
2933        let available_below = text_hitbox.bottom() - target_position.y;
2934        let mut y_is_flipped = y_overflows_below && available_above > available_below;
2935        let mut max_height = cmp::min(
2936            unconstrained_max_height,
2937            if y_is_flipped {
2938                available_above
2939            } else {
2940                available_below
2941            },
2942        );
2943
2944        // If less than 3 lines fit within the text bounds, instead fit within the window.
2945        if max_height < 3. * line_height {
2946            let available_above = bottom_y_when_flipped;
2947            let available_below = cx.viewport_size().height - target_position.y;
2948            if available_below > 3. * line_height {
2949                y_is_flipped = false;
2950                max_height = min_height;
2951            } else if available_above > 3. * line_height {
2952                y_is_flipped = true;
2953                max_height = min_height;
2954            } else if available_above > available_below {
2955                y_is_flipped = true;
2956                max_height = available_above;
2957            } else {
2958                y_is_flipped = false;
2959                max_height = available_below;
2960            }
2961        }
2962
2963        let max_height_in_lines = ((max_height - POPOVER_Y_PADDING) / line_height).floor() as u32;
2964
2965        let Some(mut menu) = self.editor.update(cx, |editor, cx| {
2966            editor.render_context_menu(&self.style, max_height_in_lines, cx)
2967        }) else {
2968            return;
2969        };
2970
2971        let menu_size = menu.layout_as_root(AvailableSpace::min_size(), cx);
2972        let menu_position = gpui::Point {
2973            x: if target_position.x + menu_size.width > cx.viewport_size().width {
2974                // Snap the right edge of the list to the right edge of the window if its horizontal bounds
2975                // overflow.
2976                (cx.viewport_size().width - menu_size.width).max(Pixels::ZERO)
2977            } else {
2978                target_position.x
2979            },
2980            y: if y_is_flipped {
2981                bottom_y_when_flipped - menu_size.height
2982            } else {
2983                target_position.y
2984            },
2985        };
2986
2987        cx.defer_draw(menu, menu_position, 1);
2988    }
2989
2990    #[allow(clippy::too_many_arguments)]
2991    fn layout_inline_completion_popover(
2992        &self,
2993        text_bounds: &Bounds<Pixels>,
2994        editor_snapshot: &EditorSnapshot,
2995        visible_row_range: Range<DisplayRow>,
2996        scroll_top: f32,
2997        scroll_bottom: f32,
2998        line_layouts: &[LineWithInvisibles],
2999        line_height: Pixels,
3000        scroll_pixel_position: gpui::Point<Pixels>,
3001        editor_width: Pixels,
3002        style: &EditorStyle,
3003        cx: &mut WindowContext,
3004    ) -> Option<AnyElement> {
3005        const PADDING_X: Pixels = Pixels(24.);
3006        const PADDING_Y: Pixels = Pixels(2.);
3007
3008        let active_inline_completion = self.editor.read(cx).active_inline_completion.as_ref()?;
3009
3010        match &active_inline_completion.completion {
3011            InlineCompletion::Move(target_position) => {
3012                let tab_kbd = h_flex()
3013                    .px_0p5()
3014                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
3015                    .text_size(TextSize::XSmall.rems(cx))
3016                    .text_color(cx.theme().colors().text.opacity(0.8))
3017                    .child("tab");
3018
3019                let icon_container = div().mt(px(2.5)); // For optical alignment
3020
3021                let container_element = h_flex()
3022                    .items_center()
3023                    .py_0p5()
3024                    .px_1()
3025                    .gap_1()
3026                    .bg(cx.theme().colors().editor_subheader_background)
3027                    .border_1()
3028                    .border_color(cx.theme().colors().text_accent.opacity(0.2))
3029                    .rounded_md()
3030                    .shadow_sm();
3031
3032                let target_display_point = target_position.to_display_point(editor_snapshot);
3033                if target_display_point.row().as_f32() < scroll_top {
3034                    let mut element = container_element
3035                        .child(tab_kbd)
3036                        .child(Label::new("Jump to Edit").size(LabelSize::Small))
3037                        .child(
3038                            icon_container
3039                                .child(Icon::new(IconName::ArrowUp).size(IconSize::Small)),
3040                        )
3041                        .into_any();
3042                    let size = element.layout_as_root(AvailableSpace::min_size(), cx);
3043                    let offset = point((text_bounds.size.width - size.width) / 2., PADDING_Y);
3044                    element.prepaint_at(text_bounds.origin + offset, cx);
3045                    Some(element)
3046                } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
3047                    let mut element = container_element
3048                        .child(tab_kbd)
3049                        .child(Label::new("Jump to Edit").size(LabelSize::Small))
3050                        .child(
3051                            icon_container
3052                                .child(Icon::new(IconName::ArrowDown).size(IconSize::Small)),
3053                        )
3054                        .into_any();
3055                    let size = element.layout_as_root(AvailableSpace::min_size(), cx);
3056                    let offset = point(
3057                        (text_bounds.size.width - size.width) / 2.,
3058                        text_bounds.size.height - size.height - PADDING_Y,
3059                    );
3060                    element.prepaint_at(text_bounds.origin + offset, cx);
3061                    Some(element)
3062                } else {
3063                    let mut element = container_element
3064                        .child(tab_kbd)
3065                        .child(Label::new("Jump to Edit").size(LabelSize::Small))
3066                        .into_any();
3067
3068                    let target_line_end = DisplayPoint::new(
3069                        target_display_point.row(),
3070                        editor_snapshot.line_len(target_display_point.row()),
3071                    );
3072                    let origin = self.editor.update(cx, |editor, cx| {
3073                        editor.display_to_pixel_point(target_line_end, editor_snapshot, cx)
3074                    })?;
3075                    element.prepaint_as_root(
3076                        text_bounds.origin + origin + point(PADDING_X, px(0.)),
3077                        AvailableSpace::min_size(),
3078                        cx,
3079                    );
3080                    Some(element)
3081                }
3082            }
3083            InlineCompletion::Edit(edits) => {
3084                if self.editor.read(cx).has_active_completions_menu() {
3085                    return None;
3086                }
3087
3088                let edit_start = edits
3089                    .first()
3090                    .unwrap()
3091                    .0
3092                    .start
3093                    .to_display_point(editor_snapshot);
3094                let edit_end = edits
3095                    .last()
3096                    .unwrap()
3097                    .0
3098                    .end
3099                    .to_display_point(editor_snapshot);
3100
3101                let is_visible = visible_row_range.contains(&edit_start.row())
3102                    || visible_row_range.contains(&edit_end.row());
3103                if !is_visible {
3104                    return None;
3105                }
3106
3107                if all_edits_insertions_or_deletions(edits, &editor_snapshot.buffer_snapshot) {
3108                    return None;
3109                }
3110
3111                let crate::InlineCompletionText::Edit { text, highlights } =
3112                    crate::inline_completion_edit_text(editor_snapshot, edits, cx)
3113                else {
3114                    return None;
3115                };
3116                let line_count = text.lines().count() + 1;
3117
3118                let longest_row =
3119                    editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
3120                let longest_line_width = if visible_row_range.contains(&longest_row) {
3121                    line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
3122                } else {
3123                    layout_line(
3124                        longest_row,
3125                        editor_snapshot,
3126                        style,
3127                        editor_width,
3128                        |_| false,
3129                        cx,
3130                    )
3131                    .width
3132                };
3133
3134                let styled_text =
3135                    gpui::StyledText::new(text.clone()).with_highlights(&style.text, highlights);
3136
3137                let mut element = div()
3138                    .bg(cx.theme().colors().editor_background)
3139                    .border_1()
3140                    .border_color(cx.theme().colors().border)
3141                    .rounded_md()
3142                    .px_1()
3143                    .child(styled_text)
3144                    .into_any();
3145
3146                let element_bounds = element.layout_as_root(AvailableSpace::min_size(), cx);
3147                let is_fully_visible =
3148                    editor_width >= longest_line_width + PADDING_X + element_bounds.width;
3149
3150                let origin = if is_fully_visible {
3151                    text_bounds.origin
3152                        + point(
3153                            longest_line_width + PADDING_X - scroll_pixel_position.x,
3154                            edit_start.row().as_f32() * line_height - scroll_pixel_position.y,
3155                        )
3156                } else {
3157                    let target_above =
3158                        DisplayRow(edit_start.row().0.saturating_sub(line_count as u32));
3159                    let row_target = if visible_row_range
3160                        .contains(&DisplayRow(target_above.0.saturating_sub(1)))
3161                    {
3162                        target_above
3163                    } else {
3164                        DisplayRow(edit_end.row().0 + 1)
3165                    };
3166
3167                    text_bounds.origin
3168                        + point(
3169                            -scroll_pixel_position.x,
3170                            row_target.as_f32() * line_height - scroll_pixel_position.y,
3171                        )
3172                };
3173
3174                element.prepaint_as_root(origin, element_bounds.into(), cx);
3175                Some(element)
3176            }
3177        }
3178    }
3179
3180    fn layout_mouse_context_menu(
3181        &self,
3182        editor_snapshot: &EditorSnapshot,
3183        visible_range: Range<DisplayRow>,
3184        content_origin: gpui::Point<Pixels>,
3185        cx: &mut WindowContext,
3186    ) -> Option<AnyElement> {
3187        let position = self.editor.update(cx, |editor, cx| {
3188            let visible_start_point = editor.display_to_pixel_point(
3189                DisplayPoint::new(visible_range.start, 0),
3190                editor_snapshot,
3191                cx,
3192            )?;
3193            let visible_end_point = editor.display_to_pixel_point(
3194                DisplayPoint::new(visible_range.end, 0),
3195                editor_snapshot,
3196                cx,
3197            )?;
3198
3199            let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
3200            let (source_display_point, position) = match mouse_context_menu.position {
3201                MenuPosition::PinnedToScreen(point) => (None, point),
3202                MenuPosition::PinnedToEditor { source, offset } => {
3203                    let source_display_point = source.to_display_point(editor_snapshot);
3204                    let source_point = editor.to_pixel_point(source, editor_snapshot, cx)?;
3205                    let position = content_origin + source_point + offset;
3206                    (Some(source_display_point), position)
3207                }
3208            };
3209
3210            let source_included = source_display_point.map_or(true, |source_display_point| {
3211                visible_range
3212                    .to_inclusive()
3213                    .contains(&source_display_point.row())
3214            });
3215            let position_included =
3216                visible_start_point.y <= position.y && position.y <= visible_end_point.y;
3217            if !source_included && !position_included {
3218                None
3219            } else {
3220                Some(position)
3221            }
3222        })?;
3223
3224        let mut element = self.editor.update(cx, |editor, _| {
3225            let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
3226            let context_menu = mouse_context_menu.context_menu.clone();
3227
3228            Some(
3229                deferred(
3230                    anchored()
3231                        .position(position)
3232                        .child(context_menu)
3233                        .anchor(Corner::TopLeft)
3234                        .snap_to_window_with_margin(px(8.)),
3235                )
3236                .with_priority(1)
3237                .into_any(),
3238            )
3239        })?;
3240
3241        element.prepaint_as_root(position, AvailableSpace::min_size(), cx);
3242        Some(element)
3243    }
3244
3245    #[allow(clippy::too_many_arguments)]
3246    fn layout_hover_popovers(
3247        &self,
3248        snapshot: &EditorSnapshot,
3249        hitbox: &Hitbox,
3250        text_hitbox: &Hitbox,
3251        visible_display_row_range: Range<DisplayRow>,
3252        content_origin: gpui::Point<Pixels>,
3253        scroll_pixel_position: gpui::Point<Pixels>,
3254        line_layouts: &[LineWithInvisibles],
3255        line_height: Pixels,
3256        em_width: Pixels,
3257        cx: &mut WindowContext,
3258    ) {
3259        struct MeasuredHoverPopover {
3260            element: AnyElement,
3261            size: Size<Pixels>,
3262            horizontal_offset: Pixels,
3263        }
3264
3265        let max_size = size(
3266            (120. * em_width) // Default size
3267                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
3268                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
3269            (16. * line_height) // Default size
3270                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
3271                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
3272        );
3273
3274        let hover_popovers = self.editor.update(cx, |editor, cx| {
3275            editor
3276                .hover_state
3277                .render(snapshot, visible_display_row_range.clone(), max_size, cx)
3278        });
3279        let Some((position, hover_popovers)) = hover_popovers else {
3280            return;
3281        };
3282
3283        // This is safe because we check on layout whether the required row is available
3284        let hovered_row_layout =
3285            &line_layouts[position.row().minus(visible_display_row_range.start) as usize];
3286
3287        // Compute Hovered Point
3288        let x =
3289            hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
3290        let y = position.row().as_f32() * line_height - scroll_pixel_position.y;
3291        let hovered_point = content_origin + point(x, y);
3292
3293        let mut overall_height = Pixels::ZERO;
3294        let mut measured_hover_popovers = Vec::new();
3295        for mut hover_popover in hover_popovers {
3296            let size = hover_popover.layout_as_root(AvailableSpace::min_size(), cx);
3297            let horizontal_offset =
3298                (text_hitbox.top_right().x - (hovered_point.x + size.width)).min(Pixels::ZERO);
3299
3300            overall_height += HOVER_POPOVER_GAP + size.height;
3301
3302            measured_hover_popovers.push(MeasuredHoverPopover {
3303                element: hover_popover,
3304                size,
3305                horizontal_offset,
3306            });
3307        }
3308        overall_height += HOVER_POPOVER_GAP;
3309
3310        fn draw_occluder(width: Pixels, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
3311            let mut occlusion = div()
3312                .size_full()
3313                .occlude()
3314                .on_mouse_move(|_, cx| cx.stop_propagation())
3315                .into_any_element();
3316            occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), cx);
3317            cx.defer_draw(occlusion, origin, 2);
3318        }
3319
3320        if hovered_point.y > overall_height {
3321            // There is enough space above. Render popovers above the hovered point
3322            let mut current_y = hovered_point.y;
3323            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
3324                let size = popover.size;
3325                let popover_origin = point(
3326                    hovered_point.x + popover.horizontal_offset,
3327                    current_y - size.height,
3328                );
3329
3330                cx.defer_draw(popover.element, popover_origin, 2);
3331                if position != itertools::Position::Last {
3332                    let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
3333                    draw_occluder(size.width, origin, cx);
3334                }
3335
3336                current_y = popover_origin.y - HOVER_POPOVER_GAP;
3337            }
3338        } else {
3339            // There is not enough space above. Render popovers below the hovered point
3340            let mut current_y = hovered_point.y + line_height;
3341            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
3342                let size = popover.size;
3343                let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
3344
3345                cx.defer_draw(popover.element, popover_origin, 2);
3346                if position != itertools::Position::Last {
3347                    let origin = point(popover_origin.x, popover_origin.y + size.height);
3348                    draw_occluder(size.width, origin, cx);
3349                }
3350
3351                current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
3352            }
3353        }
3354    }
3355
3356    #[allow(clippy::too_many_arguments)]
3357    fn layout_signature_help(
3358        &self,
3359        hitbox: &Hitbox,
3360        content_origin: gpui::Point<Pixels>,
3361        scroll_pixel_position: gpui::Point<Pixels>,
3362        newest_selection_head: Option<DisplayPoint>,
3363        start_row: DisplayRow,
3364        line_layouts: &[LineWithInvisibles],
3365        line_height: Pixels,
3366        em_width: Pixels,
3367        cx: &mut WindowContext,
3368    ) {
3369        if !self.editor.focus_handle(cx).is_focused(cx) {
3370            return;
3371        }
3372        let Some(newest_selection_head) = newest_selection_head else {
3373            return;
3374        };
3375        let selection_row = newest_selection_head.row();
3376        if selection_row < start_row {
3377            return;
3378        }
3379        let Some(cursor_row_layout) = line_layouts.get(selection_row.minus(start_row) as usize)
3380        else {
3381            return;
3382        };
3383
3384        let start_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
3385            - scroll_pixel_position.x
3386            + content_origin.x;
3387        let start_y =
3388            selection_row.as_f32() * line_height + content_origin.y - scroll_pixel_position.y;
3389
3390        let max_size = size(
3391            (120. * em_width) // Default size
3392                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
3393                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
3394            (16. * line_height) // Default size
3395                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
3396                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
3397        );
3398
3399        let maybe_element = self.editor.update(cx, |editor, cx| {
3400            if let Some(popover) = editor.signature_help_state.popover_mut() {
3401                let element = popover.render(
3402                    &self.style,
3403                    max_size,
3404                    editor.workspace.as_ref().map(|(w, _)| w.clone()),
3405                    cx,
3406                );
3407                Some(element)
3408            } else {
3409                None
3410            }
3411        });
3412        if let Some(mut element) = maybe_element {
3413            let window_size = cx.viewport_size();
3414            let size = element.layout_as_root(Size::<AvailableSpace>::default(), cx);
3415            let mut point = point(start_x, start_y - size.height);
3416
3417            // Adjusting to ensure the popover does not overflow in the X-axis direction.
3418            if point.x + size.width >= window_size.width {
3419                point.x = window_size.width - size.width;
3420            }
3421
3422            cx.defer_draw(element, point, 1)
3423        }
3424    }
3425
3426    fn paint_background(&self, layout: &EditorLayout, cx: &mut WindowContext) {
3427        cx.paint_layer(layout.hitbox.bounds, |cx| {
3428            let scroll_top = layout.position_map.snapshot.scroll_position().y;
3429            let gutter_bg = cx.theme().colors().editor_gutter_background;
3430            cx.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
3431            cx.paint_quad(fill(layout.text_hitbox.bounds, self.style.background));
3432
3433            if let EditorMode::Full = layout.mode {
3434                let mut active_rows = layout.active_rows.iter().peekable();
3435                while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
3436                    let mut end_row = start_row.0;
3437                    while active_rows
3438                        .peek()
3439                        .map_or(false, |(active_row, has_selection)| {
3440                            active_row.0 == end_row + 1
3441                                && *has_selection == contains_non_empty_selection
3442                        })
3443                    {
3444                        active_rows.next().unwrap();
3445                        end_row += 1;
3446                    }
3447
3448                    if !contains_non_empty_selection {
3449                        let highlight_h_range =
3450                            match layout.position_map.snapshot.current_line_highlight {
3451                                CurrentLineHighlight::Gutter => Some(Range {
3452                                    start: layout.hitbox.left(),
3453                                    end: layout.gutter_hitbox.right(),
3454                                }),
3455                                CurrentLineHighlight::Line => Some(Range {
3456                                    start: layout.text_hitbox.bounds.left(),
3457                                    end: layout.text_hitbox.bounds.right(),
3458                                }),
3459                                CurrentLineHighlight::All => Some(Range {
3460                                    start: layout.hitbox.left(),
3461                                    end: layout.hitbox.right(),
3462                                }),
3463                                CurrentLineHighlight::None => None,
3464                            };
3465                        if let Some(range) = highlight_h_range {
3466                            let active_line_bg = cx.theme().colors().editor_active_line_background;
3467                            let bounds = Bounds {
3468                                origin: point(
3469                                    range.start,
3470                                    layout.hitbox.origin.y
3471                                        + (start_row.as_f32() - scroll_top)
3472                                            * layout.position_map.line_height,
3473                                ),
3474                                size: size(
3475                                    range.end - range.start,
3476                                    layout.position_map.line_height
3477                                        * (end_row - start_row.0 + 1) as f32,
3478                                ),
3479                            };
3480                            cx.paint_quad(fill(bounds, active_line_bg));
3481                        }
3482                    }
3483                }
3484
3485                let mut paint_highlight =
3486                    |highlight_row_start: DisplayRow, highlight_row_end: DisplayRow, color| {
3487                        let origin = point(
3488                            layout.hitbox.origin.x,
3489                            layout.hitbox.origin.y
3490                                + (highlight_row_start.as_f32() - scroll_top)
3491                                    * layout.position_map.line_height,
3492                        );
3493                        let size = size(
3494                            layout.hitbox.size.width,
3495                            layout.position_map.line_height
3496                                * highlight_row_end.next_row().minus(highlight_row_start) as f32,
3497                        );
3498                        cx.paint_quad(fill(Bounds { origin, size }, color));
3499                    };
3500
3501                let mut current_paint: Option<(Hsla, Range<DisplayRow>)> = None;
3502                for (&new_row, &new_color) in &layout.highlighted_rows {
3503                    match &mut current_paint {
3504                        Some((current_color, current_range)) => {
3505                            let current_color = *current_color;
3506                            let new_range_started = current_color != new_color
3507                                || current_range.end.next_row() != new_row;
3508                            if new_range_started {
3509                                paint_highlight(
3510                                    current_range.start,
3511                                    current_range.end,
3512                                    current_color,
3513                                );
3514                                current_paint = Some((new_color, new_row..new_row));
3515                                continue;
3516                            } else {
3517                                current_range.end = current_range.end.next_row();
3518                            }
3519                        }
3520                        None => current_paint = Some((new_color, new_row..new_row)),
3521                    };
3522                }
3523                if let Some((color, range)) = current_paint {
3524                    paint_highlight(range.start, range.end, color);
3525                }
3526
3527                let scroll_left =
3528                    layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
3529
3530                for (wrap_position, active) in layout.wrap_guides.iter() {
3531                    let x = (layout.text_hitbox.origin.x
3532                        + *wrap_position
3533                        + layout.position_map.em_width / 2.)
3534                        - scroll_left;
3535
3536                    let show_scrollbars = {
3537                        let (scrollbar_x, scrollbar_y) = &layout.scrollbars_layout.as_xy();
3538
3539                        scrollbar_x.as_ref().map_or(false, |sx| sx.visible)
3540                            || scrollbar_y.as_ref().map_or(false, |sy| sy.visible)
3541                    };
3542
3543                    if x < layout.text_hitbox.origin.x
3544                        || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
3545                    {
3546                        continue;
3547                    }
3548
3549                    let color = if *active {
3550                        cx.theme().colors().editor_active_wrap_guide
3551                    } else {
3552                        cx.theme().colors().editor_wrap_guide
3553                    };
3554                    cx.paint_quad(fill(
3555                        Bounds {
3556                            origin: point(x, layout.text_hitbox.origin.y),
3557                            size: size(px(1.), layout.text_hitbox.size.height),
3558                        },
3559                        color,
3560                    ));
3561                }
3562            }
3563        })
3564    }
3565
3566    fn paint_indent_guides(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3567        let Some(indent_guides) = &layout.indent_guides else {
3568            return;
3569        };
3570
3571        let faded_color = |color: Hsla, alpha: f32| {
3572            let mut faded = color;
3573            faded.a = alpha;
3574            faded
3575        };
3576
3577        for indent_guide in indent_guides {
3578            let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
3579            let settings = indent_guide.settings;
3580
3581            // TODO fixed for now, expose them through themes later
3582            const INDENT_AWARE_ALPHA: f32 = 0.2;
3583            const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
3584            const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
3585            const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
3586
3587            let line_color = match (settings.coloring, indent_guide.active) {
3588                (IndentGuideColoring::Disabled, _) => None,
3589                (IndentGuideColoring::Fixed, false) => {
3590                    Some(cx.theme().colors().editor_indent_guide)
3591                }
3592                (IndentGuideColoring::Fixed, true) => {
3593                    Some(cx.theme().colors().editor_indent_guide_active)
3594                }
3595                (IndentGuideColoring::IndentAware, false) => {
3596                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
3597                }
3598                (IndentGuideColoring::IndentAware, true) => {
3599                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
3600                }
3601            };
3602
3603            let background_color = match (settings.background_coloring, indent_guide.active) {
3604                (IndentGuideBackgroundColoring::Disabled, _) => None,
3605                (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
3606                    indent_accent_colors,
3607                    INDENT_AWARE_BACKGROUND_ALPHA,
3608                )),
3609                (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
3610                    indent_accent_colors,
3611                    INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
3612                )),
3613            };
3614
3615            let requested_line_width = if indent_guide.active {
3616                settings.active_line_width
3617            } else {
3618                settings.line_width
3619            }
3620            .clamp(1, 10);
3621            let mut line_indicator_width = 0.;
3622            if let Some(color) = line_color {
3623                cx.paint_quad(fill(
3624                    Bounds {
3625                        origin: indent_guide.origin,
3626                        size: size(px(requested_line_width as f32), indent_guide.length),
3627                    },
3628                    color,
3629                ));
3630                line_indicator_width = requested_line_width as f32;
3631            }
3632
3633            if let Some(color) = background_color {
3634                let width = indent_guide.single_indent_width - px(line_indicator_width);
3635                cx.paint_quad(fill(
3636                    Bounds {
3637                        origin: point(
3638                            indent_guide.origin.x + px(line_indicator_width),
3639                            indent_guide.origin.y,
3640                        ),
3641                        size: size(width, indent_guide.length),
3642                    },
3643                    color,
3644                ));
3645            }
3646        }
3647    }
3648
3649    fn paint_line_numbers(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3650        let line_height = layout.position_map.line_height;
3651        let scroll_position = layout.position_map.snapshot.scroll_position();
3652        let scroll_top = scroll_position.y * line_height;
3653
3654        cx.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
3655
3656        for (ix, line) in layout.line_numbers.iter().enumerate() {
3657            if let Some(line) = line {
3658                let line_origin = layout.gutter_hitbox.origin
3659                    + point(
3660                        layout.gutter_hitbox.size.width
3661                            - line.width
3662                            - layout.gutter_dimensions.right_padding,
3663                        ix as f32 * line_height - (scroll_top % line_height),
3664                    );
3665
3666                line.paint(line_origin, line_height, cx).log_err();
3667            }
3668        }
3669    }
3670
3671    fn paint_diff_hunks(layout: &mut EditorLayout, cx: &mut WindowContext) {
3672        if layout.display_hunks.is_empty() {
3673            return;
3674        }
3675
3676        let line_height = layout.position_map.line_height;
3677        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3678            for (hunk, hitbox) in &layout.display_hunks {
3679                let hunk_to_paint = match hunk {
3680                    DisplayDiffHunk::Folded { .. } => {
3681                        let hunk_bounds = Self::diff_hunk_bounds(
3682                            &layout.position_map.snapshot,
3683                            line_height,
3684                            layout.gutter_hitbox.bounds,
3685                            hunk,
3686                        );
3687                        Some((
3688                            hunk_bounds,
3689                            cx.theme().status().modified,
3690                            Corners::all(px(0.)),
3691                        ))
3692                    }
3693                    DisplayDiffHunk::Unfolded { status, .. } => {
3694                        hitbox.as_ref().map(|hunk_hitbox| match status {
3695                            DiffHunkStatus::Added => (
3696                                hunk_hitbox.bounds,
3697                                cx.theme().status().created,
3698                                Corners::all(px(0.)),
3699                            ),
3700                            DiffHunkStatus::Modified => (
3701                                hunk_hitbox.bounds,
3702                                cx.theme().status().modified,
3703                                Corners::all(px(0.)),
3704                            ),
3705                            DiffHunkStatus::Removed => (
3706                                Bounds::new(
3707                                    point(
3708                                        hunk_hitbox.origin.x - hunk_hitbox.size.width,
3709                                        hunk_hitbox.origin.y,
3710                                    ),
3711                                    size(hunk_hitbox.size.width * px(2.), hunk_hitbox.size.height),
3712                                ),
3713                                cx.theme().status().deleted,
3714                                Corners::all(1. * line_height),
3715                            ),
3716                        })
3717                    }
3718                };
3719
3720                if let Some((hunk_bounds, background_color, corner_radii)) = hunk_to_paint {
3721                    cx.paint_quad(quad(
3722                        hunk_bounds,
3723                        corner_radii,
3724                        background_color,
3725                        Edges::default(),
3726                        transparent_black(),
3727                    ));
3728                }
3729            }
3730        });
3731    }
3732
3733    pub(super) fn diff_hunk_bounds(
3734        snapshot: &EditorSnapshot,
3735        line_height: Pixels,
3736        gutter_bounds: Bounds<Pixels>,
3737        hunk: &DisplayDiffHunk,
3738    ) -> Bounds<Pixels> {
3739        let scroll_position = snapshot.scroll_position();
3740        let scroll_top = scroll_position.y * line_height;
3741
3742        match hunk {
3743            DisplayDiffHunk::Folded { display_row, .. } => {
3744                let start_y = display_row.as_f32() * line_height - scroll_top;
3745                let end_y = start_y + line_height;
3746
3747                let width = Self::diff_hunk_strip_width(line_height);
3748                let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
3749                let highlight_size = size(width, end_y - start_y);
3750                Bounds::new(highlight_origin, highlight_size)
3751            }
3752            DisplayDiffHunk::Unfolded {
3753                display_row_range,
3754                status,
3755                ..
3756            } => match status {
3757                DiffHunkStatus::Added | DiffHunkStatus::Modified => {
3758                    let start_row = display_row_range.start;
3759                    let end_row = display_row_range.end;
3760                    // If we're in a multibuffer, row range span might include an
3761                    // excerpt header, so if we were to draw the marker straight away,
3762                    // the hunk might include the rows of that header.
3763                    // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
3764                    // Instead, we simply check whether the range we're dealing with includes
3765                    // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
3766                    let end_row_in_current_excerpt = snapshot
3767                        .blocks_in_range(start_row..end_row)
3768                        .find_map(|(start_row, block)| {
3769                            if matches!(block, Block::ExcerptBoundary { .. }) {
3770                                Some(start_row)
3771                            } else {
3772                                None
3773                            }
3774                        })
3775                        .unwrap_or(end_row);
3776
3777                    let start_y = start_row.as_f32() * line_height - scroll_top;
3778                    let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
3779
3780                    let width = Self::diff_hunk_strip_width(line_height);
3781                    let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
3782                    let highlight_size = size(width, end_y - start_y);
3783                    Bounds::new(highlight_origin, highlight_size)
3784                }
3785                DiffHunkStatus::Removed => {
3786                    let row = display_row_range.start;
3787
3788                    let offset = line_height / 2.;
3789                    let start_y = row.as_f32() * line_height - offset - scroll_top;
3790                    let end_y = start_y + line_height;
3791
3792                    let width = (0.35 * line_height).floor();
3793                    let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
3794                    let highlight_size = size(width, end_y - start_y);
3795                    Bounds::new(highlight_origin, highlight_size)
3796                }
3797            },
3798        }
3799    }
3800
3801    /// Returns the width of the diff strip that will be displayed in the gutter.
3802    pub(super) fn diff_hunk_strip_width(line_height: Pixels) -> Pixels {
3803        // We floor the value to prevent pixel rounding.
3804        (0.275 * line_height).floor()
3805    }
3806
3807    fn paint_gutter_indicators(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3808        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3809            cx.with_element_namespace("crease_toggles", |cx| {
3810                for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
3811                    crease_toggle.paint(cx);
3812                }
3813            });
3814
3815            for test_indicator in layout.test_indicators.iter_mut() {
3816                test_indicator.paint(cx);
3817            }
3818
3819            if let Some(indicator) = layout.code_actions_indicator.as_mut() {
3820                indicator.paint(cx);
3821            }
3822        });
3823    }
3824
3825    fn paint_gutter_highlights(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3826        for (_, hunk_hitbox) in &layout.display_hunks {
3827            if let Some(hunk_hitbox) = hunk_hitbox {
3828                cx.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
3829            }
3830        }
3831
3832        let show_git_gutter = layout
3833            .position_map
3834            .snapshot
3835            .show_git_diff_gutter
3836            .unwrap_or_else(|| {
3837                matches!(
3838                    ProjectSettings::get_global(cx).git.git_gutter,
3839                    Some(GitGutterSetting::TrackedFiles)
3840                )
3841            });
3842        if show_git_gutter {
3843            Self::paint_diff_hunks(layout, cx)
3844        }
3845
3846        let highlight_width = 0.275 * layout.position_map.line_height;
3847        let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
3848        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3849            for (range, color) in &layout.highlighted_gutter_ranges {
3850                let start_row = if range.start.row() < layout.visible_display_row_range.start {
3851                    layout.visible_display_row_range.start - DisplayRow(1)
3852                } else {
3853                    range.start.row()
3854                };
3855                let end_row = if range.end.row() > layout.visible_display_row_range.end {
3856                    layout.visible_display_row_range.end + DisplayRow(1)
3857                } else {
3858                    range.end.row()
3859                };
3860
3861                let start_y = layout.gutter_hitbox.top()
3862                    + start_row.0 as f32 * layout.position_map.line_height
3863                    - layout.position_map.scroll_pixel_position.y;
3864                let end_y = layout.gutter_hitbox.top()
3865                    + (end_row.0 + 1) as f32 * layout.position_map.line_height
3866                    - layout.position_map.scroll_pixel_position.y;
3867                let bounds = Bounds::from_corners(
3868                    point(layout.gutter_hitbox.left(), start_y),
3869                    point(layout.gutter_hitbox.left() + highlight_width, end_y),
3870                );
3871                cx.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
3872            }
3873        });
3874    }
3875
3876    fn paint_blamed_display_rows(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3877        let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
3878            return;
3879        };
3880
3881        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3882            for mut blame_element in blamed_display_rows.into_iter() {
3883                blame_element.paint(cx);
3884            }
3885        })
3886    }
3887
3888    fn paint_text(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3889        cx.with_content_mask(
3890            Some(ContentMask {
3891                bounds: layout.text_hitbox.bounds,
3892            }),
3893            |cx| {
3894                let cursor_style = if self
3895                    .editor
3896                    .read(cx)
3897                    .hovered_link_state
3898                    .as_ref()
3899                    .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
3900                {
3901                    CursorStyle::PointingHand
3902                } else {
3903                    CursorStyle::IBeam
3904                };
3905                cx.set_cursor_style(cursor_style, &layout.text_hitbox);
3906
3907                let invisible_display_ranges = self.paint_highlights(layout, cx);
3908                self.paint_lines(&invisible_display_ranges, layout, cx);
3909                self.paint_redactions(layout, cx);
3910                self.paint_cursors(layout, cx);
3911                self.paint_inline_blame(layout, cx);
3912                cx.with_element_namespace("crease_trailers", |cx| {
3913                    for trailer in layout.crease_trailers.iter_mut().flatten() {
3914                        trailer.element.paint(cx);
3915                    }
3916                });
3917            },
3918        )
3919    }
3920
3921    fn paint_highlights(
3922        &mut self,
3923        layout: &mut EditorLayout,
3924        cx: &mut WindowContext,
3925    ) -> SmallVec<[Range<DisplayPoint>; 32]> {
3926        cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3927            let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
3928            let line_end_overshoot = 0.15 * layout.position_map.line_height;
3929            for (range, color) in &layout.highlighted_ranges {
3930                self.paint_highlighted_range(
3931                    range.clone(),
3932                    *color,
3933                    Pixels::ZERO,
3934                    line_end_overshoot,
3935                    layout,
3936                    cx,
3937                );
3938            }
3939
3940            let corner_radius = 0.15 * layout.position_map.line_height;
3941
3942            for (player_color, selections) in &layout.selections {
3943                for selection in selections.iter() {
3944                    self.paint_highlighted_range(
3945                        selection.range.clone(),
3946                        player_color.selection,
3947                        corner_radius,
3948                        corner_radius * 2.,
3949                        layout,
3950                        cx,
3951                    );
3952
3953                    if selection.is_local && !selection.range.is_empty() {
3954                        invisible_display_ranges.push(selection.range.clone());
3955                    }
3956                }
3957            }
3958            invisible_display_ranges
3959        })
3960    }
3961
3962    fn paint_lines(
3963        &mut self,
3964        invisible_display_ranges: &[Range<DisplayPoint>],
3965        layout: &mut EditorLayout,
3966        cx: &mut WindowContext,
3967    ) {
3968        let whitespace_setting = self
3969            .editor
3970            .read(cx)
3971            .buffer
3972            .read(cx)
3973            .settings_at(0, cx)
3974            .show_whitespaces;
3975
3976        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
3977            let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
3978            line_with_invisibles.draw(
3979                layout,
3980                row,
3981                layout.content_origin,
3982                whitespace_setting,
3983                invisible_display_ranges,
3984                cx,
3985            )
3986        }
3987
3988        for line_element in &mut layout.line_elements {
3989            line_element.paint(cx);
3990        }
3991    }
3992
3993    fn paint_redactions(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
3994        if layout.redacted_ranges.is_empty() {
3995            return;
3996        }
3997
3998        let line_end_overshoot = layout.line_end_overshoot();
3999
4000        // A softer than perfect black
4001        let redaction_color = gpui::rgb(0x0e1111);
4002
4003        cx.paint_layer(layout.text_hitbox.bounds, |cx| {
4004            for range in layout.redacted_ranges.iter() {
4005                self.paint_highlighted_range(
4006                    range.clone(),
4007                    redaction_color.into(),
4008                    Pixels::ZERO,
4009                    line_end_overshoot,
4010                    layout,
4011                    cx,
4012                );
4013            }
4014        });
4015    }
4016
4017    fn paint_cursors(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
4018        for cursor in &mut layout.visible_cursors {
4019            cursor.paint(layout.content_origin, cx);
4020        }
4021    }
4022
4023    fn paint_scrollbars(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
4024        let (scrollbar_x, scrollbar_y) = layout.scrollbars_layout.as_xy();
4025
4026        if let Some(scrollbar_layout) = scrollbar_x {
4027            let hitbox = scrollbar_layout.hitbox.clone();
4028            let text_unit_size = scrollbar_layout.text_unit_size;
4029            let visible_range = scrollbar_layout.visible_range.clone();
4030            let thumb_bounds = scrollbar_layout.thumb_bounds();
4031
4032            if scrollbar_layout.visible {
4033                cx.paint_layer(hitbox.bounds, |cx| {
4034                    cx.paint_quad(quad(
4035                        hitbox.bounds,
4036                        Corners::default(),
4037                        cx.theme().colors().scrollbar_track_background,
4038                        Edges {
4039                            top: Pixels::ZERO,
4040                            right: Pixels::ZERO,
4041                            bottom: Pixels::ZERO,
4042                            left: Pixels::ZERO,
4043                        },
4044                        cx.theme().colors().scrollbar_track_border,
4045                    ));
4046
4047                    cx.paint_quad(quad(
4048                        thumb_bounds,
4049                        Corners::default(),
4050                        cx.theme().colors().scrollbar_thumb_background,
4051                        Edges {
4052                            top: Pixels::ZERO,
4053                            right: Pixels::ZERO,
4054                            bottom: Pixels::ZERO,
4055                            left: ScrollbarLayout::BORDER_WIDTH,
4056                        },
4057                        cx.theme().colors().scrollbar_thumb_border,
4058                    ));
4059                })
4060            }
4061
4062            cx.set_cursor_style(CursorStyle::Arrow, &hitbox);
4063
4064            cx.on_mouse_event({
4065                let editor = self.editor.clone();
4066
4067                // there may be a way to avoid this clone
4068                let hitbox = hitbox.clone();
4069
4070                let mut mouse_position = cx.mouse_position();
4071                move |event: &MouseMoveEvent, phase, cx| {
4072                    if phase == DispatchPhase::Capture {
4073                        return;
4074                    }
4075
4076                    editor.update(cx, |editor, cx| {
4077                        if event.pressed_button == Some(MouseButton::Left)
4078                            && editor
4079                                .scroll_manager
4080                                .is_dragging_scrollbar(Axis::Horizontal)
4081                        {
4082                            let x = mouse_position.x;
4083                            let new_x = event.position.x;
4084                            if (hitbox.left()..hitbox.right()).contains(&x) {
4085                                let mut position = editor.scroll_position(cx);
4086
4087                                position.x += (new_x - x) / text_unit_size;
4088                                if position.x < 0.0 {
4089                                    position.x = 0.0;
4090                                }
4091                                editor.set_scroll_position(position, cx);
4092                            }
4093
4094                            cx.stop_propagation();
4095                        } else {
4096                            editor.scroll_manager.set_is_dragging_scrollbar(
4097                                Axis::Horizontal,
4098                                false,
4099                                cx,
4100                            );
4101
4102                            if hitbox.is_hovered(cx) {
4103                                editor.scroll_manager.show_scrollbar(cx);
4104                            }
4105                        }
4106                        mouse_position = event.position;
4107                    })
4108                }
4109            });
4110
4111            if self
4112                .editor
4113                .read(cx)
4114                .scroll_manager
4115                .is_dragging_scrollbar(Axis::Horizontal)
4116            {
4117                cx.on_mouse_event({
4118                    let editor = self.editor.clone();
4119                    move |_: &MouseUpEvent, phase, cx| {
4120                        if phase == DispatchPhase::Capture {
4121                            return;
4122                        }
4123
4124                        editor.update(cx, |editor, cx| {
4125                            editor.scroll_manager.set_is_dragging_scrollbar(
4126                                Axis::Horizontal,
4127                                false,
4128                                cx,
4129                            );
4130                            cx.stop_propagation();
4131                        });
4132                    }
4133                });
4134            } else {
4135                cx.on_mouse_event({
4136                    let editor = self.editor.clone();
4137
4138                    move |event: &MouseDownEvent, phase, cx| {
4139                        if phase == DispatchPhase::Capture || !hitbox.is_hovered(cx) {
4140                            return;
4141                        }
4142
4143                        editor.update(cx, |editor, cx| {
4144                            editor.scroll_manager.set_is_dragging_scrollbar(
4145                                Axis::Horizontal,
4146                                true,
4147                                cx,
4148                            );
4149
4150                            let x = event.position.x;
4151
4152                            if x < thumb_bounds.left() || thumb_bounds.right() < x {
4153                                let center_row =
4154                                    ((x - hitbox.left()) / text_unit_size).round() as u32;
4155                                let top_row = center_row.saturating_sub(
4156                                    (visible_range.end - visible_range.start) as u32 / 2,
4157                                );
4158
4159                                let mut position = editor.scroll_position(cx);
4160                                position.x = top_row as f32;
4161
4162                                editor.set_scroll_position(position, cx);
4163                            } else {
4164                                editor.scroll_manager.show_scrollbar(cx);
4165                            }
4166
4167                            cx.stop_propagation();
4168                        });
4169                    }
4170                });
4171            }
4172        }
4173
4174        if let Some(scrollbar_layout) = scrollbar_y {
4175            let hitbox = scrollbar_layout.hitbox.clone();
4176            let text_unit_size = scrollbar_layout.text_unit_size;
4177            let visible_range = scrollbar_layout.visible_range.clone();
4178            let thumb_bounds = scrollbar_layout.thumb_bounds();
4179
4180            if scrollbar_layout.visible {
4181                cx.paint_layer(hitbox.bounds, |cx| {
4182                    cx.paint_quad(quad(
4183                        hitbox.bounds,
4184                        Corners::default(),
4185                        cx.theme().colors().scrollbar_track_background,
4186                        Edges {
4187                            top: Pixels::ZERO,
4188                            right: Pixels::ZERO,
4189                            bottom: Pixels::ZERO,
4190                            left: ScrollbarLayout::BORDER_WIDTH,
4191                        },
4192                        cx.theme().colors().scrollbar_track_border,
4193                    ));
4194
4195                    let fast_markers =
4196                        self.collect_fast_scrollbar_markers(layout, &scrollbar_layout, cx);
4197                    // Refresh slow scrollbar markers in the background. Below, we paint whatever markers have already been computed.
4198                    self.refresh_slow_scrollbar_markers(layout, &scrollbar_layout, cx);
4199
4200                    let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
4201                    for marker in markers.iter().chain(&fast_markers) {
4202                        let mut marker = marker.clone();
4203                        marker.bounds.origin += hitbox.origin;
4204                        cx.paint_quad(marker);
4205                    }
4206
4207                    cx.paint_quad(quad(
4208                        thumb_bounds,
4209                        Corners::default(),
4210                        cx.theme().colors().scrollbar_thumb_background,
4211                        Edges {
4212                            top: Pixels::ZERO,
4213                            right: Pixels::ZERO,
4214                            bottom: Pixels::ZERO,
4215                            left: ScrollbarLayout::BORDER_WIDTH,
4216                        },
4217                        cx.theme().colors().scrollbar_thumb_border,
4218                    ));
4219                });
4220            }
4221
4222            cx.set_cursor_style(CursorStyle::Arrow, &hitbox);
4223
4224            cx.on_mouse_event({
4225                let editor = self.editor.clone();
4226
4227                let hitbox = hitbox.clone();
4228
4229                let mut mouse_position = cx.mouse_position();
4230                move |event: &MouseMoveEvent, phase, cx| {
4231                    if phase == DispatchPhase::Capture {
4232                        return;
4233                    }
4234
4235                    editor.update(cx, |editor, cx| {
4236                        if event.pressed_button == Some(MouseButton::Left)
4237                            && editor.scroll_manager.is_dragging_scrollbar(Axis::Vertical)
4238                        {
4239                            let y = mouse_position.y;
4240                            let new_y = event.position.y;
4241                            if (hitbox.top()..hitbox.bottom()).contains(&y) {
4242                                let mut position = editor.scroll_position(cx);
4243                                position.y += (new_y - y) / text_unit_size;
4244                                if position.y < 0.0 {
4245                                    position.y = 0.0;
4246                                }
4247                                editor.set_scroll_position(position, cx);
4248                            }
4249                        } else {
4250                            editor.scroll_manager.set_is_dragging_scrollbar(
4251                                Axis::Vertical,
4252                                false,
4253                                cx,
4254                            );
4255
4256                            if hitbox.is_hovered(cx) {
4257                                editor.scroll_manager.show_scrollbar(cx);
4258                            }
4259                        }
4260                        mouse_position = event.position;
4261                    })
4262                }
4263            });
4264
4265            if self
4266                .editor
4267                .read(cx)
4268                .scroll_manager
4269                .is_dragging_scrollbar(Axis::Vertical)
4270            {
4271                cx.on_mouse_event({
4272                    let editor = self.editor.clone();
4273                    move |_: &MouseUpEvent, phase, cx| {
4274                        if phase == DispatchPhase::Capture {
4275                            return;
4276                        }
4277
4278                        editor.update(cx, |editor, cx| {
4279                            editor.scroll_manager.set_is_dragging_scrollbar(
4280                                Axis::Vertical,
4281                                false,
4282                                cx,
4283                            );
4284                            cx.stop_propagation();
4285                        });
4286                    }
4287                });
4288            } else {
4289                cx.on_mouse_event({
4290                    let editor = self.editor.clone();
4291
4292                    move |event: &MouseDownEvent, phase, cx| {
4293                        if phase == DispatchPhase::Capture || !hitbox.is_hovered(cx) {
4294                            return;
4295                        }
4296
4297                        editor.update(cx, |editor, cx| {
4298                            editor.scroll_manager.set_is_dragging_scrollbar(
4299                                Axis::Vertical,
4300                                true,
4301                                cx,
4302                            );
4303
4304                            let y = event.position.y;
4305                            if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
4306                                let center_row =
4307                                    ((y - hitbox.top()) / text_unit_size).round() as u32;
4308                                let top_row = center_row.saturating_sub(
4309                                    (visible_range.end - visible_range.start) as u32 / 2,
4310                                );
4311                                let mut position = editor.scroll_position(cx);
4312                                position.y = top_row as f32;
4313                                editor.set_scroll_position(position, cx);
4314                            } else {
4315                                editor.scroll_manager.show_scrollbar(cx);
4316                            }
4317
4318                            cx.stop_propagation();
4319                        });
4320                    }
4321                });
4322            }
4323        }
4324    }
4325
4326    fn collect_fast_scrollbar_markers(
4327        &self,
4328        layout: &EditorLayout,
4329        scrollbar_layout: &ScrollbarLayout,
4330        cx: &mut WindowContext,
4331    ) -> Vec<PaintQuad> {
4332        const LIMIT: usize = 100;
4333        if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
4334            return vec![];
4335        }
4336        let cursor_ranges = layout
4337            .cursors
4338            .iter()
4339            .map(|(point, color)| ColoredRange {
4340                start: point.row(),
4341                end: point.row(),
4342                color: *color,
4343            })
4344            .collect_vec();
4345        scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
4346    }
4347
4348    fn refresh_slow_scrollbar_markers(
4349        &self,
4350        layout: &EditorLayout,
4351        scrollbar_layout: &ScrollbarLayout,
4352        cx: &mut WindowContext,
4353    ) {
4354        self.editor.update(cx, |editor, cx| {
4355            if !editor.is_singleton(cx)
4356                || !editor
4357                    .scrollbar_marker_state
4358                    .should_refresh(scrollbar_layout.hitbox.size)
4359            {
4360                return;
4361            }
4362
4363            let scrollbar_layout = scrollbar_layout.clone();
4364            let background_highlights = editor.background_highlights.clone();
4365            let snapshot = layout.position_map.snapshot.clone();
4366            let theme = cx.theme().clone();
4367            let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
4368
4369            editor.scrollbar_marker_state.dirty = false;
4370            editor.scrollbar_marker_state.pending_refresh =
4371                Some(cx.spawn(|editor, mut cx| async move {
4372                    let scrollbar_size = scrollbar_layout.hitbox.size;
4373                    let scrollbar_markers = cx
4374                        .background_executor()
4375                        .spawn(async move {
4376                            let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
4377                            let mut marker_quads = Vec::new();
4378                            if scrollbar_settings.git_diff {
4379                                let marker_row_ranges = snapshot
4380                                    .diff_map
4381                                    .diff_hunks(&snapshot.buffer_snapshot)
4382                                    .map(|hunk| {
4383                                        let start_display_row =
4384                                            MultiBufferPoint::new(hunk.row_range.start.0, 0)
4385                                                .to_display_point(&snapshot.display_snapshot)
4386                                                .row();
4387                                        let mut end_display_row =
4388                                            MultiBufferPoint::new(hunk.row_range.end.0, 0)
4389                                                .to_display_point(&snapshot.display_snapshot)
4390                                                .row();
4391                                        if end_display_row != start_display_row {
4392                                            end_display_row.0 -= 1;
4393                                        }
4394                                        let color = match hunk_status(&hunk) {
4395                                            DiffHunkStatus::Added => theme.status().created,
4396                                            DiffHunkStatus::Modified => theme.status().modified,
4397                                            DiffHunkStatus::Removed => theme.status().deleted,
4398                                        };
4399                                        ColoredRange {
4400                                            start: start_display_row,
4401                                            end: end_display_row,
4402                                            color,
4403                                        }
4404                                    });
4405
4406                                marker_quads.extend(
4407                                    scrollbar_layout
4408                                        .marker_quads_for_ranges(marker_row_ranges, Some(0)),
4409                                );
4410                            }
4411
4412                            for (background_highlight_id, (_, background_ranges)) in
4413                                background_highlights.iter()
4414                            {
4415                                let is_search_highlights = *background_highlight_id
4416                                    == TypeId::of::<BufferSearchHighlights>();
4417                                let is_symbol_occurrences = *background_highlight_id
4418                                    == TypeId::of::<DocumentHighlightRead>()
4419                                    || *background_highlight_id
4420                                        == TypeId::of::<DocumentHighlightWrite>();
4421                                if (is_search_highlights && scrollbar_settings.search_results)
4422                                    || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
4423                                {
4424                                    let mut color = theme.status().info;
4425                                    if is_symbol_occurrences {
4426                                        color.fade_out(0.5);
4427                                    }
4428                                    let marker_row_ranges = background_ranges.iter().map(|range| {
4429                                        let display_start = range
4430                                            .start
4431                                            .to_display_point(&snapshot.display_snapshot);
4432                                        let display_end =
4433                                            range.end.to_display_point(&snapshot.display_snapshot);
4434                                        ColoredRange {
4435                                            start: display_start.row(),
4436                                            end: display_end.row(),
4437                                            color,
4438                                        }
4439                                    });
4440                                    marker_quads.extend(
4441                                        scrollbar_layout
4442                                            .marker_quads_for_ranges(marker_row_ranges, Some(1)),
4443                                    );
4444                                }
4445                            }
4446
4447                            if scrollbar_settings.diagnostics {
4448                                let diagnostics = snapshot
4449                                    .buffer_snapshot
4450                                    .diagnostics_in_range::<_, Point>(
4451                                        Point::zero()..max_point,
4452                                        false,
4453                                    )
4454                                    // We want to sort by severity, in order to paint the most severe diagnostics last.
4455                                    .sorted_by_key(|diagnostic| {
4456                                        std::cmp::Reverse(diagnostic.diagnostic.severity)
4457                                    });
4458
4459                                let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
4460                                    let start_display = diagnostic
4461                                        .range
4462                                        .start
4463                                        .to_display_point(&snapshot.display_snapshot);
4464                                    let end_display = diagnostic
4465                                        .range
4466                                        .end
4467                                        .to_display_point(&snapshot.display_snapshot);
4468                                    let color = match diagnostic.diagnostic.severity {
4469                                        DiagnosticSeverity::ERROR => theme.status().error,
4470                                        DiagnosticSeverity::WARNING => theme.status().warning,
4471                                        DiagnosticSeverity::INFORMATION => theme.status().info,
4472                                        _ => theme.status().hint,
4473                                    };
4474                                    ColoredRange {
4475                                        start: start_display.row(),
4476                                        end: end_display.row(),
4477                                        color,
4478                                    }
4479                                });
4480                                marker_quads.extend(
4481                                    scrollbar_layout
4482                                        .marker_quads_for_ranges(marker_row_ranges, Some(2)),
4483                                );
4484                            }
4485
4486                            Arc::from(marker_quads)
4487                        })
4488                        .await;
4489
4490                    editor.update(&mut cx, |editor, cx| {
4491                        editor.scrollbar_marker_state.markers = scrollbar_markers;
4492                        editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
4493                        editor.scrollbar_marker_state.pending_refresh = None;
4494                        cx.notify();
4495                    })?;
4496
4497                    Ok(())
4498                }));
4499        });
4500    }
4501
4502    #[allow(clippy::too_many_arguments)]
4503    fn paint_highlighted_range(
4504        &self,
4505        range: Range<DisplayPoint>,
4506        color: Hsla,
4507        corner_radius: Pixels,
4508        line_end_overshoot: Pixels,
4509        layout: &EditorLayout,
4510        cx: &mut WindowContext,
4511    ) {
4512        let start_row = layout.visible_display_row_range.start;
4513        let end_row = layout.visible_display_row_range.end;
4514        if range.start != range.end {
4515            let row_range = if range.end.column() == 0 {
4516                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
4517            } else {
4518                cmp::max(range.start.row(), start_row)
4519                    ..cmp::min(range.end.row().next_row(), end_row)
4520            };
4521
4522            let highlighted_range = HighlightedRange {
4523                color,
4524                line_height: layout.position_map.line_height,
4525                corner_radius,
4526                start_y: layout.content_origin.y
4527                    + row_range.start.as_f32() * layout.position_map.line_height
4528                    - layout.position_map.scroll_pixel_position.y,
4529                lines: row_range
4530                    .iter_rows()
4531                    .map(|row| {
4532                        let line_layout =
4533                            &layout.position_map.line_layouts[row.minus(start_row) as usize];
4534                        HighlightedRangeLine {
4535                            start_x: if row == range.start.row() {
4536                                layout.content_origin.x
4537                                    + line_layout.x_for_index(range.start.column() as usize)
4538                                    - layout.position_map.scroll_pixel_position.x
4539                            } else {
4540                                layout.content_origin.x
4541                                    - layout.position_map.scroll_pixel_position.x
4542                            },
4543                            end_x: if row == range.end.row() {
4544                                layout.content_origin.x
4545                                    + line_layout.x_for_index(range.end.column() as usize)
4546                                    - layout.position_map.scroll_pixel_position.x
4547                            } else {
4548                                layout.content_origin.x + line_layout.width + line_end_overshoot
4549                                    - layout.position_map.scroll_pixel_position.x
4550                            },
4551                        }
4552                    })
4553                    .collect(),
4554            };
4555
4556            highlighted_range.paint(layout.text_hitbox.bounds, cx);
4557        }
4558    }
4559
4560    fn paint_inline_blame(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
4561        if let Some(mut inline_blame) = layout.inline_blame.take() {
4562            cx.paint_layer(layout.text_hitbox.bounds, |cx| {
4563                inline_blame.paint(cx);
4564            })
4565        }
4566    }
4567
4568    fn paint_blocks(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
4569        for mut block in layout.blocks.drain(..) {
4570            block.element.paint(cx);
4571        }
4572    }
4573
4574    fn paint_inline_completion_popover(
4575        &mut self,
4576        layout: &mut EditorLayout,
4577        cx: &mut WindowContext,
4578    ) {
4579        if let Some(inline_completion_popover) = layout.inline_completion_popover.as_mut() {
4580            inline_completion_popover.paint(cx);
4581        }
4582    }
4583
4584    fn paint_mouse_context_menu(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
4585        if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
4586            mouse_context_menu.paint(cx);
4587        }
4588    }
4589
4590    fn paint_scroll_wheel_listener(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
4591        cx.on_mouse_event({
4592            let position_map = layout.position_map.clone();
4593            let editor = self.editor.clone();
4594            let hitbox = layout.hitbox.clone();
4595            let mut delta = ScrollDelta::default();
4596
4597            // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
4598            // accidentally turn off their scrolling.
4599            let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
4600
4601            move |event: &ScrollWheelEvent, phase, cx| {
4602                if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
4603                    delta = delta.coalesce(event.delta);
4604                    editor.update(cx, |editor, cx| {
4605                        let position_map: &PositionMap = &position_map;
4606
4607                        let line_height = position_map.line_height;
4608                        let max_glyph_width = position_map.em_width;
4609                        let (delta, axis) = match delta {
4610                            gpui::ScrollDelta::Pixels(mut pixels) => {
4611                                //Trackpad
4612                                let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
4613                                (pixels, axis)
4614                            }
4615
4616                            gpui::ScrollDelta::Lines(lines) => {
4617                                //Not trackpad
4618                                let pixels =
4619                                    point(lines.x * max_glyph_width, lines.y * line_height);
4620                                (pixels, None)
4621                            }
4622                        };
4623
4624                        let current_scroll_position = position_map.snapshot.scroll_position();
4625                        let x = (current_scroll_position.x * max_glyph_width
4626                            - (delta.x * scroll_sensitivity))
4627                            / max_glyph_width;
4628                        let y = (current_scroll_position.y * line_height
4629                            - (delta.y * scroll_sensitivity))
4630                            / line_height;
4631                        let mut scroll_position =
4632                            point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
4633                        let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
4634                        if forbid_vertical_scroll {
4635                            scroll_position.y = current_scroll_position.y;
4636                        }
4637
4638                        if scroll_position != current_scroll_position {
4639                            editor.scroll(scroll_position, axis, cx);
4640                            cx.stop_propagation();
4641                        } else if y < 0. {
4642                            // Due to clamping, we may fail to detect cases of overscroll to the top;
4643                            // We want the scroll manager to get an update in such cases and detect the change of direction
4644                            // on the next frame.
4645                            cx.notify();
4646                        }
4647                    });
4648                }
4649            }
4650        });
4651    }
4652
4653    fn paint_mouse_listeners(
4654        &mut self,
4655        layout: &EditorLayout,
4656        hovered_hunk: Option<HoveredHunk>,
4657        cx: &mut WindowContext,
4658    ) {
4659        self.paint_scroll_wheel_listener(layout, cx);
4660
4661        cx.on_mouse_event({
4662            let position_map = layout.position_map.clone();
4663            let editor = self.editor.clone();
4664            let text_hitbox = layout.text_hitbox.clone();
4665            let gutter_hitbox = layout.gutter_hitbox.clone();
4666
4667            move |event: &MouseDownEvent, phase, cx| {
4668                if phase == DispatchPhase::Bubble {
4669                    match event.button {
4670                        MouseButton::Left => editor.update(cx, |editor, cx| {
4671                            Self::mouse_left_down(
4672                                editor,
4673                                event,
4674                                hovered_hunk.clone(),
4675                                &position_map,
4676                                &text_hitbox,
4677                                &gutter_hitbox,
4678                                cx,
4679                            );
4680                        }),
4681                        MouseButton::Right => editor.update(cx, |editor, cx| {
4682                            Self::mouse_right_down(editor, event, &position_map, &text_hitbox, cx);
4683                        }),
4684                        MouseButton::Middle => editor.update(cx, |editor, cx| {
4685                            Self::mouse_middle_down(editor, event, &position_map, &text_hitbox, cx);
4686                        }),
4687                        _ => {}
4688                    };
4689                }
4690            }
4691        });
4692
4693        cx.on_mouse_event({
4694            let editor = self.editor.clone();
4695            let position_map = layout.position_map.clone();
4696            let text_hitbox = layout.text_hitbox.clone();
4697
4698            move |event: &MouseUpEvent, phase, cx| {
4699                if phase == DispatchPhase::Bubble {
4700                    editor.update(cx, |editor, cx| {
4701                        Self::mouse_up(editor, event, &position_map, &text_hitbox, cx)
4702                    });
4703                }
4704            }
4705        });
4706        cx.on_mouse_event({
4707            let position_map = layout.position_map.clone();
4708            let editor = self.editor.clone();
4709            let text_hitbox = layout.text_hitbox.clone();
4710            let gutter_hitbox = layout.gutter_hitbox.clone();
4711
4712            move |event: &MouseMoveEvent, phase, cx| {
4713                if phase == DispatchPhase::Bubble {
4714                    editor.update(cx, |editor, cx| {
4715                        if editor.hover_state.focused(cx) {
4716                            return;
4717                        }
4718                        if event.pressed_button == Some(MouseButton::Left)
4719                            || event.pressed_button == Some(MouseButton::Middle)
4720                        {
4721                            Self::mouse_dragged(
4722                                editor,
4723                                event,
4724                                &position_map,
4725                                text_hitbox.bounds,
4726                                cx,
4727                            )
4728                        }
4729
4730                        Self::mouse_moved(
4731                            editor,
4732                            event,
4733                            &position_map,
4734                            &text_hitbox,
4735                            &gutter_hitbox,
4736                            cx,
4737                        )
4738                    });
4739                }
4740            }
4741        });
4742    }
4743
4744    fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
4745        bounds.top_right().x - self.style.scrollbar_width
4746    }
4747
4748    fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
4749        let style = &self.style;
4750        let font_size = style.text.font_size.to_pixels(cx.rem_size());
4751        let layout = cx
4752            .text_system()
4753            .shape_line(
4754                SharedString::from(" ".repeat(column)),
4755                font_size,
4756                &[TextRun {
4757                    len: column,
4758                    font: style.text.font(),
4759                    color: Hsla::default(),
4760                    background_color: None,
4761                    underline: None,
4762                    strikethrough: None,
4763                }],
4764            )
4765            .unwrap();
4766
4767        layout.width
4768    }
4769
4770    fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
4771        let digit_count = (snapshot.widest_line_number() as f32).log10().floor() as usize + 1;
4772        self.column_pixels(digit_count, cx)
4773    }
4774}
4775
4776fn jump_data(
4777    snapshot: &EditorSnapshot,
4778    block_row_start: DisplayRow,
4779    height: u32,
4780    for_excerpt: &ExcerptInfo,
4781    cx: &mut WindowContext<'_>,
4782) -> JumpData {
4783    let range = &for_excerpt.range;
4784    let buffer = &for_excerpt.buffer;
4785    let jump_path = project::File::from_dyn(buffer.file()).map(|file| ProjectPath {
4786        worktree_id: file.worktree_id(cx),
4787        path: file.path.clone(),
4788    });
4789    let jump_anchor = range
4790        .primary
4791        .as_ref()
4792        .map_or(range.context.start, |primary| primary.start);
4793
4794    let excerpt_start = range.context.start;
4795    let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
4796    let offset_from_excerpt_start = if jump_anchor == excerpt_start {
4797        0
4798    } else {
4799        let excerpt_start_row = language::ToPoint::to_point(&jump_anchor, buffer).row;
4800        jump_position.row - excerpt_start_row
4801    };
4802    let line_offset_from_top = block_row_start.0 + height + offset_from_excerpt_start
4803        - snapshot
4804            .scroll_anchor
4805            .scroll_position(&snapshot.display_snapshot)
4806            .y as u32;
4807    JumpData {
4808        excerpt_id: for_excerpt.id,
4809        anchor: jump_anchor,
4810        position: language::ToPoint::to_point(&jump_anchor, buffer),
4811        path: jump_path,
4812        line_offset_from_top,
4813    }
4814}
4815
4816fn all_edits_insertions_or_deletions(
4817    edits: &Vec<(Range<Anchor>, String)>,
4818    snapshot: &MultiBufferSnapshot,
4819) -> bool {
4820    let mut all_insertions = true;
4821    let mut all_deletions = true;
4822
4823    for (range, new_text) in edits.iter() {
4824        let range_is_empty = range.to_offset(&snapshot).is_empty();
4825        let text_is_empty = new_text.is_empty();
4826
4827        if range_is_empty != text_is_empty {
4828            if range_is_empty {
4829                all_deletions = false;
4830            } else {
4831                all_insertions = false;
4832            }
4833        } else {
4834            return false;
4835        }
4836
4837        if !all_insertions && !all_deletions {
4838            return false;
4839        }
4840    }
4841    all_insertions || all_deletions
4842}
4843
4844#[allow(clippy::too_many_arguments)]
4845fn prepaint_gutter_button(
4846    button: IconButton,
4847    row: DisplayRow,
4848    line_height: Pixels,
4849    gutter_dimensions: &GutterDimensions,
4850    scroll_pixel_position: gpui::Point<Pixels>,
4851    gutter_hitbox: &Hitbox,
4852    rows_with_hunk_bounds: &HashMap<DisplayRow, Bounds<Pixels>>,
4853    cx: &mut WindowContext<'_>,
4854) -> AnyElement {
4855    let mut button = button.into_any_element();
4856    let available_space = size(
4857        AvailableSpace::MinContent,
4858        AvailableSpace::Definite(line_height),
4859    );
4860    let indicator_size = button.layout_as_root(available_space, cx);
4861
4862    let blame_width = gutter_dimensions.git_blame_entries_width;
4863    let gutter_width = rows_with_hunk_bounds
4864        .get(&row)
4865        .map(|bounds| bounds.size.width);
4866    let left_offset = blame_width.max(gutter_width).unwrap_or_default();
4867
4868    let mut x = left_offset;
4869    let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
4870        - indicator_size.width
4871        - left_offset;
4872    x += available_width / 2.;
4873
4874    let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
4875    y += (line_height - indicator_size.height) / 2.;
4876
4877    button.prepaint_as_root(gutter_hitbox.origin + point(x, y), available_space, cx);
4878    button
4879}
4880
4881fn render_inline_blame_entry(
4882    blame: &gpui::Model<GitBlame>,
4883    blame_entry: BlameEntry,
4884    style: &EditorStyle,
4885    workspace: Option<WeakView<Workspace>>,
4886    cx: &mut WindowContext<'_>,
4887) -> AnyElement {
4888    let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
4889
4890    let author = blame_entry.author.as_deref().unwrap_or_default();
4891    let summary_enabled = ProjectSettings::get_global(cx)
4892        .git
4893        .show_inline_commit_summary();
4894
4895    let text = match blame_entry.summary.as_ref() {
4896        Some(summary) if summary_enabled => {
4897            format!("{}, {} - {}", author, relative_timestamp, summary)
4898        }
4899        _ => format!("{}, {}", author, relative_timestamp),
4900    };
4901
4902    let details = blame.read(cx).details_for_entry(&blame_entry);
4903
4904    let tooltip = cx.new_view(|_| BlameEntryTooltip::new(blame_entry, details, style, workspace));
4905
4906    h_flex()
4907        .id("inline-blame")
4908        .w_full()
4909        .font_family(style.text.font().family)
4910        .text_color(cx.theme().status().hint)
4911        .line_height(style.text.line_height)
4912        .child(Icon::new(IconName::FileGit).color(Color::Hint))
4913        .child(text)
4914        .gap_2()
4915        .hoverable_tooltip(move |_| tooltip.clone().into())
4916        .into_any()
4917}
4918
4919fn render_blame_entry(
4920    ix: usize,
4921    blame: &gpui::Model<GitBlame>,
4922    blame_entry: BlameEntry,
4923    style: &EditorStyle,
4924    last_used_color: &mut Option<(PlayerColor, Oid)>,
4925    editor: View<Editor>,
4926    cx: &mut WindowContext<'_>,
4927) -> AnyElement {
4928    let mut sha_color = cx
4929        .theme()
4930        .players()
4931        .color_for_participant(blame_entry.sha.into());
4932    // If the last color we used is the same as the one we get for this line, but
4933    // the commit SHAs are different, then we try again to get a different color.
4934    match *last_used_color {
4935        Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
4936            let index: u32 = blame_entry.sha.into();
4937            sha_color = cx.theme().players().color_for_participant(index + 1);
4938        }
4939        _ => {}
4940    };
4941    last_used_color.replace((sha_color, blame_entry.sha));
4942
4943    let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
4944
4945    let short_commit_id = blame_entry.sha.display_short();
4946
4947    let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
4948    let name = util::truncate_and_trailoff(author_name, GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED);
4949
4950    let details = blame.read(cx).details_for_entry(&blame_entry);
4951
4952    let workspace = editor.read(cx).workspace.as_ref().map(|(w, _)| w.clone());
4953
4954    let tooltip = cx.new_view(|_| {
4955        BlameEntryTooltip::new(blame_entry.clone(), details.clone(), style, workspace)
4956    });
4957
4958    h_flex()
4959        .w_full()
4960        .justify_between()
4961        .font_family(style.text.font().family)
4962        .line_height(style.text.line_height)
4963        .id(("blame", ix))
4964        .text_color(cx.theme().status().hint)
4965        .pr_2()
4966        .gap_2()
4967        .child(
4968            h_flex()
4969                .items_center()
4970                .gap_2()
4971                .child(div().text_color(sha_color.cursor).child(short_commit_id))
4972                .child(name),
4973        )
4974        .child(relative_timestamp)
4975        .on_mouse_down(MouseButton::Right, {
4976            let blame_entry = blame_entry.clone();
4977            let details = details.clone();
4978            move |event, cx| {
4979                deploy_blame_entry_context_menu(
4980                    &blame_entry,
4981                    details.as_ref(),
4982                    editor.clone(),
4983                    event.position,
4984                    cx,
4985                );
4986            }
4987        })
4988        .hover(|style| style.bg(cx.theme().colors().element_hover))
4989        .when_some(
4990            details.and_then(|details| details.permalink),
4991            |this, url| {
4992                let url = url.clone();
4993                this.cursor_pointer().on_click(move |_, cx| {
4994                    cx.stop_propagation();
4995                    cx.open_url(url.as_str())
4996                })
4997            },
4998        )
4999        .hoverable_tooltip(move |_| tooltip.clone().into())
5000        .into_any()
5001}
5002
5003fn deploy_blame_entry_context_menu(
5004    blame_entry: &BlameEntry,
5005    details: Option<&CommitDetails>,
5006    editor: View<Editor>,
5007    position: gpui::Point<Pixels>,
5008    cx: &mut WindowContext<'_>,
5009) {
5010    let context_menu = ContextMenu::build(cx, move |menu, _| {
5011        let sha = format!("{}", blame_entry.sha);
5012        menu.on_blur_subscription(Subscription::new(|| {}))
5013            .entry("Copy commit SHA", None, move |cx| {
5014                cx.write_to_clipboard(ClipboardItem::new_string(sha.clone()));
5015            })
5016            .when_some(
5017                details.and_then(|details| details.permalink.clone()),
5018                |this, url| this.entry("Open permalink", None, move |cx| cx.open_url(url.as_str())),
5019            )
5020    });
5021
5022    editor.update(cx, move |editor, cx| {
5023        editor.mouse_context_menu = Some(MouseContextMenu::new(
5024            MenuPosition::PinnedToScreen(position),
5025            context_menu,
5026            cx,
5027        ));
5028        cx.notify();
5029    });
5030}
5031
5032#[derive(Debug)]
5033pub(crate) struct LineWithInvisibles {
5034    fragments: SmallVec<[LineFragment; 1]>,
5035    invisibles: Vec<Invisible>,
5036    len: usize,
5037    width: Pixels,
5038    font_size: Pixels,
5039}
5040
5041#[allow(clippy::large_enum_variant)]
5042enum LineFragment {
5043    Text(ShapedLine),
5044    Element {
5045        element: Option<AnyElement>,
5046        size: Size<Pixels>,
5047        len: usize,
5048    },
5049}
5050
5051impl fmt::Debug for LineFragment {
5052    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5053        match self {
5054            LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
5055            LineFragment::Element { size, len, .. } => f
5056                .debug_struct("Element")
5057                .field("size", size)
5058                .field("len", len)
5059                .finish(),
5060        }
5061    }
5062}
5063
5064impl LineWithInvisibles {
5065    #[allow(clippy::too_many_arguments)]
5066    fn from_chunks<'a>(
5067        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
5068        editor_style: &EditorStyle,
5069        max_line_len: usize,
5070        max_line_count: usize,
5071        editor_mode: EditorMode,
5072        text_width: Pixels,
5073        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
5074        cx: &mut WindowContext,
5075    ) -> Vec<Self> {
5076        let text_style = &editor_style.text;
5077        let mut layouts = Vec::with_capacity(max_line_count);
5078        let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
5079        let mut line = String::new();
5080        let mut invisibles = Vec::new();
5081        let mut width = Pixels::ZERO;
5082        let mut len = 0;
5083        let mut styles = Vec::new();
5084        let mut non_whitespace_added = false;
5085        let mut row = 0;
5086        let mut line_exceeded_max_len = false;
5087        let font_size = text_style.font_size.to_pixels(cx.rem_size());
5088
5089        let ellipsis = SharedString::from("");
5090
5091        for highlighted_chunk in chunks.chain([HighlightedChunk {
5092            text: "\n",
5093            style: None,
5094            is_tab: false,
5095            replacement: None,
5096        }]) {
5097            if let Some(replacement) = highlighted_chunk.replacement {
5098                if !line.is_empty() {
5099                    let shaped_line = cx
5100                        .text_system()
5101                        .shape_line(line.clone().into(), font_size, &styles)
5102                        .unwrap();
5103                    width += shaped_line.width;
5104                    len += shaped_line.len;
5105                    fragments.push(LineFragment::Text(shaped_line));
5106                    line.clear();
5107                    styles.clear();
5108                }
5109
5110                match replacement {
5111                    ChunkReplacement::Renderer(renderer) => {
5112                        let available_width = if renderer.constrain_width {
5113                            let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
5114                                ellipsis.clone()
5115                            } else {
5116                                SharedString::from(Arc::from(highlighted_chunk.text))
5117                            };
5118                            let shaped_line = cx
5119                                .text_system()
5120                                .shape_line(
5121                                    chunk,
5122                                    font_size,
5123                                    &[text_style.to_run(highlighted_chunk.text.len())],
5124                                )
5125                                .unwrap();
5126                            AvailableSpace::Definite(shaped_line.width)
5127                        } else {
5128                            AvailableSpace::MinContent
5129                        };
5130
5131                        let mut element = (renderer.render)(&mut ChunkRendererContext {
5132                            context: cx,
5133                            max_width: text_width,
5134                        });
5135                        let line_height = text_style.line_height_in_pixels(cx.rem_size());
5136                        let size = element.layout_as_root(
5137                            size(available_width, AvailableSpace::Definite(line_height)),
5138                            cx,
5139                        );
5140
5141                        width += size.width;
5142                        len += highlighted_chunk.text.len();
5143                        fragments.push(LineFragment::Element {
5144                            element: Some(element),
5145                            size,
5146                            len: highlighted_chunk.text.len(),
5147                        });
5148                    }
5149                    ChunkReplacement::Str(x) => {
5150                        let text_style = if let Some(style) = highlighted_chunk.style {
5151                            Cow::Owned(text_style.clone().highlight(style))
5152                        } else {
5153                            Cow::Borrowed(text_style)
5154                        };
5155
5156                        let run = TextRun {
5157                            len: x.len(),
5158                            font: text_style.font(),
5159                            color: text_style.color,
5160                            background_color: text_style.background_color,
5161                            underline: text_style.underline,
5162                            strikethrough: text_style.strikethrough,
5163                        };
5164                        let line_layout = cx
5165                            .text_system()
5166                            .shape_line(x, font_size, &[run])
5167                            .unwrap()
5168                            .with_len(highlighted_chunk.text.len());
5169
5170                        width += line_layout.width;
5171                        len += highlighted_chunk.text.len();
5172                        fragments.push(LineFragment::Text(line_layout))
5173                    }
5174                }
5175            } else {
5176                for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
5177                    if ix > 0 {
5178                        let shaped_line = cx
5179                            .text_system()
5180                            .shape_line(line.clone().into(), font_size, &styles)
5181                            .unwrap();
5182                        width += shaped_line.width;
5183                        len += shaped_line.len;
5184                        fragments.push(LineFragment::Text(shaped_line));
5185                        layouts.push(Self {
5186                            width: mem::take(&mut width),
5187                            len: mem::take(&mut len),
5188                            fragments: mem::take(&mut fragments),
5189                            invisibles: std::mem::take(&mut invisibles),
5190                            font_size,
5191                        });
5192
5193                        line.clear();
5194                        styles.clear();
5195                        row += 1;
5196                        line_exceeded_max_len = false;
5197                        non_whitespace_added = false;
5198                        if row == max_line_count {
5199                            return layouts;
5200                        }
5201                    }
5202
5203                    if !line_chunk.is_empty() && !line_exceeded_max_len {
5204                        let text_style = if let Some(style) = highlighted_chunk.style {
5205                            Cow::Owned(text_style.clone().highlight(style))
5206                        } else {
5207                            Cow::Borrowed(text_style)
5208                        };
5209
5210                        if line.len() + line_chunk.len() > max_line_len {
5211                            let mut chunk_len = max_line_len - line.len();
5212                            while !line_chunk.is_char_boundary(chunk_len) {
5213                                chunk_len -= 1;
5214                            }
5215                            line_chunk = &line_chunk[..chunk_len];
5216                            line_exceeded_max_len = true;
5217                        }
5218
5219                        styles.push(TextRun {
5220                            len: line_chunk.len(),
5221                            font: text_style.font(),
5222                            color: text_style.color,
5223                            background_color: text_style.background_color,
5224                            underline: text_style.underline,
5225                            strikethrough: text_style.strikethrough,
5226                        });
5227
5228                        if editor_mode == EditorMode::Full {
5229                            // Line wrap pads its contents with fake whitespaces,
5230                            // avoid printing them
5231                            let is_soft_wrapped = is_row_soft_wrapped(row);
5232                            if highlighted_chunk.is_tab {
5233                                if non_whitespace_added || !is_soft_wrapped {
5234                                    invisibles.push(Invisible::Tab {
5235                                        line_start_offset: line.len(),
5236                                        line_end_offset: line.len() + line_chunk.len(),
5237                                    });
5238                                }
5239                            } else {
5240                                invisibles.extend(
5241                                    line_chunk
5242                                        .bytes()
5243                                        .enumerate()
5244                                        .filter(|(_, line_byte)| {
5245                                            let is_whitespace =
5246                                                (*line_byte as char).is_whitespace();
5247                                            non_whitespace_added |= !is_whitespace;
5248                                            is_whitespace
5249                                                && (non_whitespace_added || !is_soft_wrapped)
5250                                        })
5251                                        .map(|(whitespace_index, _)| Invisible::Whitespace {
5252                                            line_offset: line.len() + whitespace_index,
5253                                        }),
5254                                )
5255                            }
5256                        }
5257
5258                        line.push_str(line_chunk);
5259                    }
5260                }
5261            }
5262        }
5263
5264        layouts
5265    }
5266
5267    fn prepaint(
5268        &mut self,
5269        line_height: Pixels,
5270        scroll_pixel_position: gpui::Point<Pixels>,
5271        row: DisplayRow,
5272        content_origin: gpui::Point<Pixels>,
5273        line_elements: &mut SmallVec<[AnyElement; 1]>,
5274        cx: &mut WindowContext,
5275    ) {
5276        let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
5277        let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
5278        for fragment in &mut self.fragments {
5279            match fragment {
5280                LineFragment::Text(line) => {
5281                    fragment_origin.x += line.width;
5282                }
5283                LineFragment::Element { element, size, .. } => {
5284                    let mut element = element
5285                        .take()
5286                        .expect("you can't prepaint LineWithInvisibles twice");
5287
5288                    // Center the element vertically within the line.
5289                    let mut element_origin = fragment_origin;
5290                    element_origin.y += (line_height - size.height) / 2.;
5291                    element.prepaint_at(element_origin, cx);
5292                    line_elements.push(element);
5293
5294                    fragment_origin.x += size.width;
5295                }
5296            }
5297        }
5298    }
5299
5300    fn draw(
5301        &self,
5302        layout: &EditorLayout,
5303        row: DisplayRow,
5304        content_origin: gpui::Point<Pixels>,
5305        whitespace_setting: ShowWhitespaceSetting,
5306        selection_ranges: &[Range<DisplayPoint>],
5307        cx: &mut WindowContext,
5308    ) {
5309        let line_height = layout.position_map.line_height;
5310        let line_y = line_height
5311            * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
5312
5313        let mut fragment_origin =
5314            content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
5315
5316        for fragment in &self.fragments {
5317            match fragment {
5318                LineFragment::Text(line) => {
5319                    line.paint(fragment_origin, line_height, cx).log_err();
5320                    fragment_origin.x += line.width;
5321                }
5322                LineFragment::Element { size, .. } => {
5323                    fragment_origin.x += size.width;
5324                }
5325            }
5326        }
5327
5328        self.draw_invisibles(
5329            selection_ranges,
5330            layout,
5331            content_origin,
5332            line_y,
5333            row,
5334            line_height,
5335            whitespace_setting,
5336            cx,
5337        );
5338    }
5339
5340    #[allow(clippy::too_many_arguments)]
5341    fn draw_invisibles(
5342        &self,
5343        selection_ranges: &[Range<DisplayPoint>],
5344        layout: &EditorLayout,
5345        content_origin: gpui::Point<Pixels>,
5346        line_y: Pixels,
5347        row: DisplayRow,
5348        line_height: Pixels,
5349        whitespace_setting: ShowWhitespaceSetting,
5350        cx: &mut WindowContext,
5351    ) {
5352        let extract_whitespace_info = |invisible: &Invisible| {
5353            let (token_offset, token_end_offset, invisible_symbol) = match invisible {
5354                Invisible::Tab {
5355                    line_start_offset,
5356                    line_end_offset,
5357                } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
5358                Invisible::Whitespace { line_offset } => {
5359                    (*line_offset, line_offset + 1, &layout.space_invisible)
5360                }
5361            };
5362
5363            let x_offset = self.x_for_index(token_offset);
5364            let invisible_offset =
5365                (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
5366            let origin = content_origin
5367                + gpui::point(
5368                    x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
5369                    line_y,
5370                );
5371
5372            (
5373                [token_offset, token_end_offset],
5374                Box::new(move |cx: &mut WindowContext| {
5375                    invisible_symbol.paint(origin, line_height, cx).log_err();
5376                }),
5377            )
5378        };
5379
5380        let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
5381        match whitespace_setting {
5382            ShowWhitespaceSetting::None => (),
5383            ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(cx)),
5384            ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
5385                let invisible_point = DisplayPoint::new(row, start as u32);
5386                if !selection_ranges
5387                    .iter()
5388                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
5389                {
5390                    return;
5391                }
5392
5393                paint(cx);
5394            }),
5395
5396            // For a whitespace to be on a boundary, any of the following conditions need to be met:
5397            // - It is a tab
5398            // - It is adjacent to an edge (start or end)
5399            // - It is adjacent to a whitespace (left or right)
5400            ShowWhitespaceSetting::Boundary => {
5401                // 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
5402                // the above cases.
5403                // Note: We zip in the original `invisibles` to check for tab equality
5404                let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut WindowContext)>)> = None;
5405                for (([start, end], paint), invisible) in
5406                    invisible_iter.zip_eq(self.invisibles.iter())
5407                {
5408                    let should_render = match (&last_seen, invisible) {
5409                        (_, Invisible::Tab { .. }) => true,
5410                        (Some((_, last_end, _)), _) => *last_end == start,
5411                        _ => false,
5412                    };
5413
5414                    if should_render || start == 0 || end == self.len {
5415                        paint(cx);
5416
5417                        // Since we are scanning from the left, we will skip over the first available whitespace that is part
5418                        // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
5419                        if let Some((should_render_last, last_end, paint_last)) = last_seen {
5420                            // Note that we need to make sure that the last one is actually adjacent
5421                            if !should_render_last && last_end == start {
5422                                paint_last(cx);
5423                            }
5424                        }
5425                    }
5426
5427                    // Manually render anything within a selection
5428                    let invisible_point = DisplayPoint::new(row, start as u32);
5429                    if selection_ranges.iter().any(|region| {
5430                        region.start <= invisible_point && invisible_point < region.end
5431                    }) {
5432                        paint(cx);
5433                    }
5434
5435                    last_seen = Some((should_render, end, paint));
5436                }
5437            }
5438        }
5439    }
5440
5441    pub fn x_for_index(&self, index: usize) -> Pixels {
5442        let mut fragment_start_x = Pixels::ZERO;
5443        let mut fragment_start_index = 0;
5444
5445        for fragment in &self.fragments {
5446            match fragment {
5447                LineFragment::Text(shaped_line) => {
5448                    let fragment_end_index = fragment_start_index + shaped_line.len;
5449                    if index < fragment_end_index {
5450                        return fragment_start_x
5451                            + shaped_line.x_for_index(index - fragment_start_index);
5452                    }
5453                    fragment_start_x += shaped_line.width;
5454                    fragment_start_index = fragment_end_index;
5455                }
5456                LineFragment::Element { len, size, .. } => {
5457                    let fragment_end_index = fragment_start_index + len;
5458                    if index < fragment_end_index {
5459                        return fragment_start_x;
5460                    }
5461                    fragment_start_x += size.width;
5462                    fragment_start_index = fragment_end_index;
5463                }
5464            }
5465        }
5466
5467        fragment_start_x
5468    }
5469
5470    pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
5471        let mut fragment_start_x = Pixels::ZERO;
5472        let mut fragment_start_index = 0;
5473
5474        for fragment in &self.fragments {
5475            match fragment {
5476                LineFragment::Text(shaped_line) => {
5477                    let fragment_end_x = fragment_start_x + shaped_line.width;
5478                    if x < fragment_end_x {
5479                        return Some(
5480                            fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
5481                        );
5482                    }
5483                    fragment_start_x = fragment_end_x;
5484                    fragment_start_index += shaped_line.len;
5485                }
5486                LineFragment::Element { len, size, .. } => {
5487                    let fragment_end_x = fragment_start_x + size.width;
5488                    if x < fragment_end_x {
5489                        return Some(fragment_start_index);
5490                    }
5491                    fragment_start_index += len;
5492                    fragment_start_x = fragment_end_x;
5493                }
5494            }
5495        }
5496
5497        None
5498    }
5499
5500    pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
5501        let mut fragment_start_index = 0;
5502
5503        for fragment in &self.fragments {
5504            match fragment {
5505                LineFragment::Text(shaped_line) => {
5506                    let fragment_end_index = fragment_start_index + shaped_line.len;
5507                    if index < fragment_end_index {
5508                        return shaped_line.font_id_for_index(index - fragment_start_index);
5509                    }
5510                    fragment_start_index = fragment_end_index;
5511                }
5512                LineFragment::Element { len, .. } => {
5513                    let fragment_end_index = fragment_start_index + len;
5514                    if index < fragment_end_index {
5515                        return None;
5516                    }
5517                    fragment_start_index = fragment_end_index;
5518                }
5519            }
5520        }
5521
5522        None
5523    }
5524}
5525
5526#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5527enum Invisible {
5528    /// A tab character
5529    ///
5530    /// A tab character is internally represented by spaces (configured by the user's tab width)
5531    /// aligned to the nearest column, so it's necessary to store the start and end offset for
5532    /// adjacency checks.
5533    Tab {
5534        line_start_offset: usize,
5535        line_end_offset: usize,
5536    },
5537    Whitespace {
5538        line_offset: usize,
5539    },
5540}
5541
5542impl EditorElement {
5543    /// Returns the rem size to use when rendering the [`EditorElement`].
5544    ///
5545    /// This allows UI elements to scale based on the `buffer_font_size`.
5546    fn rem_size(&self, cx: &WindowContext) -> Option<Pixels> {
5547        match self.editor.read(cx).mode {
5548            EditorMode::Full => {
5549                let buffer_font_size = self.style.text.font_size;
5550                match buffer_font_size {
5551                    AbsoluteLength::Pixels(pixels) => {
5552                        let rem_size_scale = {
5553                            // Our default UI font size is 14px on a 16px base scale.
5554                            // This means the default UI font size is 0.875rems.
5555                            let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
5556
5557                            // We then determine the delta between a single rem and the default font
5558                            // size scale.
5559                            let default_font_size_delta = 1. - default_font_size_scale;
5560
5561                            // Finally, we add this delta to 1rem to get the scale factor that
5562                            // should be used to scale up the UI.
5563                            1. + default_font_size_delta
5564                        };
5565
5566                        Some(pixels * rem_size_scale)
5567                    }
5568                    AbsoluteLength::Rems(rems) => {
5569                        Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
5570                    }
5571                }
5572            }
5573            // We currently use single-line and auto-height editors in UI contexts,
5574            // so we don't want to scale everything with the buffer font size, as it
5575            // ends up looking off.
5576            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => None,
5577        }
5578    }
5579}
5580
5581impl Element for EditorElement {
5582    type RequestLayoutState = ();
5583    type PrepaintState = EditorLayout;
5584
5585    fn id(&self) -> Option<ElementId> {
5586        None
5587    }
5588
5589    fn request_layout(
5590        &mut self,
5591        _: Option<&GlobalElementId>,
5592        cx: &mut WindowContext,
5593    ) -> (gpui::LayoutId, ()) {
5594        let rem_size = self.rem_size(cx);
5595        cx.with_rem_size(rem_size, |cx| {
5596            self.editor.update(cx, |editor, cx| {
5597                editor.set_style(self.style.clone(), cx);
5598
5599                let layout_id = match editor.mode {
5600                    EditorMode::SingleLine { auto_width } => {
5601                        let rem_size = cx.rem_size();
5602
5603                        let height = self.style.text.line_height_in_pixels(rem_size);
5604                        if auto_width {
5605                            let editor_handle = cx.view().clone();
5606                            let style = self.style.clone();
5607                            cx.request_measured_layout(Style::default(), move |_, _, cx| {
5608                                let editor_snapshot =
5609                                    editor_handle.update(cx, |editor, cx| editor.snapshot(cx));
5610                                let line = Self::layout_lines(
5611                                    DisplayRow(0)..DisplayRow(1),
5612                                    &editor_snapshot,
5613                                    &style,
5614                                    px(f32::MAX),
5615                                    |_| false, // Single lines never soft wrap
5616                                    cx,
5617                                )
5618                                .pop()
5619                                .unwrap();
5620
5621                                let font_id = cx.text_system().resolve_font(&style.text.font());
5622                                let font_size = style.text.font_size.to_pixels(cx.rem_size());
5623                                let em_width = cx
5624                                    .text_system()
5625                                    .typographic_bounds(font_id, font_size, 'm')
5626                                    .unwrap()
5627                                    .size
5628                                    .width;
5629
5630                                size(line.width + em_width, height)
5631                            })
5632                        } else {
5633                            let mut style = Style::default();
5634                            style.size.height = height.into();
5635                            style.size.width = relative(1.).into();
5636                            cx.request_layout(style, None)
5637                        }
5638                    }
5639                    EditorMode::AutoHeight { max_lines } => {
5640                        let editor_handle = cx.view().clone();
5641                        let max_line_number_width =
5642                            self.max_line_number_width(&editor.snapshot(cx), cx);
5643                        cx.request_measured_layout(
5644                            Style::default(),
5645                            move |known_dimensions, available_space, cx| {
5646                                editor_handle
5647                                    .update(cx, |editor, cx| {
5648                                        compute_auto_height_layout(
5649                                            editor,
5650                                            max_lines,
5651                                            max_line_number_width,
5652                                            known_dimensions,
5653                                            available_space.width,
5654                                            cx,
5655                                        )
5656                                    })
5657                                    .unwrap_or_default()
5658                            },
5659                        )
5660                    }
5661                    EditorMode::Full => {
5662                        let mut style = Style::default();
5663                        style.size.width = relative(1.).into();
5664                        style.size.height = relative(1.).into();
5665                        cx.request_layout(style, None)
5666                    }
5667                };
5668
5669                (layout_id, ())
5670            })
5671        })
5672    }
5673
5674    fn prepaint(
5675        &mut self,
5676        _: Option<&GlobalElementId>,
5677        bounds: Bounds<Pixels>,
5678        _: &mut Self::RequestLayoutState,
5679        cx: &mut WindowContext,
5680    ) -> Self::PrepaintState {
5681        let text_style = TextStyleRefinement {
5682            font_size: Some(self.style.text.font_size),
5683            line_height: Some(self.style.text.line_height),
5684            ..Default::default()
5685        };
5686        let focus_handle = self.editor.focus_handle(cx);
5687        cx.set_view_id(self.editor.entity_id());
5688        cx.set_focus_handle(&focus_handle);
5689
5690        let rem_size = self.rem_size(cx);
5691        cx.with_rem_size(rem_size, |cx| {
5692            cx.with_text_style(Some(text_style), |cx| {
5693                cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
5694                    let mut snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
5695                    let style = self.style.clone();
5696
5697                    let font_id = cx.text_system().resolve_font(&style.text.font());
5698                    let font_size = style.text.font_size.to_pixels(cx.rem_size());
5699                    let line_height = style.text.line_height_in_pixels(cx.rem_size());
5700                    let em_width = cx
5701                        .text_system()
5702                        .typographic_bounds(font_id, font_size, 'm')
5703                        .unwrap()
5704                        .size
5705                        .width;
5706                    let em_advance = cx
5707                        .text_system()
5708                        .advance(font_id, font_size, 'm')
5709                        .unwrap()
5710                        .width;
5711
5712                    let letter_size = size(em_width, line_height);
5713
5714                    let gutter_dimensions = snapshot.gutter_dimensions(
5715                        font_id,
5716                        font_size,
5717                        em_width,
5718                        em_advance,
5719                        self.max_line_number_width(&snapshot, cx),
5720                        cx,
5721                    );
5722                    let text_width = bounds.size.width - gutter_dimensions.width;
5723
5724                    let editor_width = text_width - gutter_dimensions.margin - em_width;
5725
5726                    snapshot = self.editor.update(cx, |editor, cx| {
5727                        editor.last_bounds = Some(bounds);
5728                        editor.gutter_dimensions = gutter_dimensions;
5729                        editor.set_visible_line_count(bounds.size.height / line_height, cx);
5730
5731                        if matches!(editor.mode, EditorMode::AutoHeight { .. }) {
5732                            snapshot
5733                        } else {
5734                            let wrap_width = match editor.soft_wrap_mode(cx) {
5735                                SoftWrap::GitDiff => None,
5736                                SoftWrap::None => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
5737                                SoftWrap::EditorWidth => Some(editor_width),
5738                                SoftWrap::Column(column) => Some(column as f32 * em_advance),
5739                                SoftWrap::Bounded(column) => {
5740                                    Some(editor_width.min(column as f32 * em_advance))
5741                                }
5742                            };
5743
5744                            if editor.set_wrap_width(wrap_width, cx) {
5745                                editor.snapshot(cx)
5746                            } else {
5747                                snapshot
5748                            }
5749                        }
5750                    });
5751
5752                    let wrap_guides = self
5753                        .editor
5754                        .read(cx)
5755                        .wrap_guides(cx)
5756                        .iter()
5757                        .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
5758                        .collect::<SmallVec<[_; 2]>>();
5759
5760                    let hitbox = cx.insert_hitbox(bounds, false);
5761                    let gutter_hitbox =
5762                        cx.insert_hitbox(gutter_bounds(bounds, gutter_dimensions), false);
5763                    let text_hitbox = cx.insert_hitbox(
5764                        Bounds {
5765                            origin: gutter_hitbox.top_right(),
5766                            size: size(text_width, bounds.size.height),
5767                        },
5768                        false,
5769                    );
5770                    // Offset the content_bounds from the text_bounds by the gutter margin (which
5771                    // is roughly half a character wide) to make hit testing work more like how we want.
5772                    let content_origin =
5773                        text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
5774
5775                    let scrollbar_bounds =
5776                        Bounds::from_corners(content_origin, bounds.bottom_right());
5777
5778                    let height_in_lines = scrollbar_bounds.size.height / line_height;
5779
5780                    // NOTE: The max row number in the current file, minus one
5781                    let max_row = snapshot.max_point().row().as_f32();
5782
5783                    // NOTE: The max scroll position for the top of the window
5784                    let max_scroll_top = if matches!(snapshot.mode, EditorMode::AutoHeight { .. }) {
5785                        (max_row - height_in_lines + 1.).max(0.)
5786                    } else {
5787                        let settings = EditorSettings::get_global(cx);
5788                        match settings.scroll_beyond_last_line {
5789                            ScrollBeyondLastLine::OnePage => max_row,
5790                            ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
5791                            ScrollBeyondLastLine::VerticalScrollMargin => {
5792                                (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
5793                                    .max(0.)
5794                            }
5795                        }
5796                    };
5797
5798                    // TODO: Autoscrolling for both axes
5799                    let mut autoscroll_request = None;
5800                    let mut autoscroll_containing_element = false;
5801                    let mut autoscroll_horizontally = false;
5802                    self.editor.update(cx, |editor, cx| {
5803                        autoscroll_request = editor.autoscroll_request();
5804                        autoscroll_containing_element =
5805                            autoscroll_request.is_some() || editor.has_pending_selection();
5806                        // TODO: Is this horizontal or vertical?!
5807                        autoscroll_horizontally =
5808                            editor.autoscroll_vertically(bounds, line_height, max_scroll_top, cx);
5809                        snapshot = editor.snapshot(cx);
5810                    });
5811
5812                    let mut scroll_position = snapshot.scroll_position();
5813                    // The scroll position is a fractional point, the whole number of which represents
5814                    // the top of the window in terms of display rows.
5815                    let start_row = DisplayRow(scroll_position.y as u32);
5816                    let max_row = snapshot.max_point().row();
5817                    let end_row = cmp::min(
5818                        (scroll_position.y + height_in_lines).ceil() as u32,
5819                        max_row.next_row().0,
5820                    );
5821                    let end_row = DisplayRow(end_row);
5822
5823                    let buffer_rows = snapshot
5824                        .buffer_rows(start_row)
5825                        .take((start_row..end_row).len())
5826                        .collect::<Vec<_>>();
5827                    let is_row_soft_wrapped =
5828                        |row| buffer_rows.get(row).copied().flatten().is_none();
5829
5830                    let start_anchor = if start_row == Default::default() {
5831                        Anchor::min()
5832                    } else {
5833                        snapshot.buffer_snapshot.anchor_before(
5834                            DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
5835                        )
5836                    };
5837                    let end_anchor = if end_row > max_row {
5838                        Anchor::max()
5839                    } else {
5840                        snapshot.buffer_snapshot.anchor_before(
5841                            DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
5842                        )
5843                    };
5844
5845                    let highlighted_rows = self
5846                        .editor
5847                        .update(cx, |editor, cx| editor.highlighted_display_rows(cx));
5848                    let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
5849                        start_anchor..end_anchor,
5850                        &snapshot.display_snapshot,
5851                        cx.theme().colors(),
5852                    );
5853                    let highlighted_gutter_ranges =
5854                        self.editor.read(cx).gutter_highlights_in_range(
5855                            start_anchor..end_anchor,
5856                            &snapshot.display_snapshot,
5857                            cx,
5858                        );
5859
5860                    let redacted_ranges = self.editor.read(cx).redacted_ranges(
5861                        start_anchor..end_anchor,
5862                        &snapshot.display_snapshot,
5863                        cx,
5864                    );
5865
5866                    let local_selections: Vec<Selection<Point>> =
5867                        self.editor.update(cx, |editor, cx| {
5868                            let mut selections = editor
5869                                .selections
5870                                .disjoint_in_range(start_anchor..end_anchor, cx);
5871                            selections.extend(editor.selections.pending(cx));
5872                            selections
5873                        });
5874
5875                    let (selections, active_rows, newest_selection_head) = self.layout_selections(
5876                        start_anchor,
5877                        end_anchor,
5878                        &local_selections,
5879                        &snapshot,
5880                        start_row,
5881                        end_row,
5882                        cx,
5883                    );
5884
5885                    let line_numbers = self.layout_line_numbers(
5886                        start_row..end_row,
5887                        buffer_rows.iter().copied(),
5888                        &active_rows,
5889                        newest_selection_head,
5890                        &snapshot,
5891                        cx,
5892                    );
5893
5894                    let mut crease_toggles = cx.with_element_namespace("crease_toggles", |cx| {
5895                        self.layout_crease_toggles(
5896                            start_row..end_row,
5897                            buffer_rows.iter().copied(),
5898                            &active_rows,
5899                            &snapshot,
5900                            cx,
5901                        )
5902                    });
5903                    let crease_trailers = cx.with_element_namespace("crease_trailers", |cx| {
5904                        self.layout_crease_trailers(buffer_rows.iter().copied(), &snapshot, cx)
5905                    });
5906
5907                    let display_hunks = self.layout_gutter_git_hunks(
5908                        line_height,
5909                        &gutter_hitbox,
5910                        start_row..end_row,
5911                        start_anchor..end_anchor,
5912                        &snapshot,
5913                        cx,
5914                    );
5915
5916                    let mut max_visible_line_width = Pixels::ZERO;
5917                    let mut line_layouts = Self::layout_lines(
5918                        start_row..end_row,
5919                        &snapshot,
5920                        &self.style,
5921                        editor_width,
5922                        is_row_soft_wrapped,
5923                        cx,
5924                    );
5925                    for line_with_invisibles in &line_layouts {
5926                        if line_with_invisibles.width > max_visible_line_width {
5927                            max_visible_line_width = line_with_invisibles.width;
5928                        }
5929                    }
5930
5931                    let longest_line_width = layout_line(
5932                        snapshot.longest_row(),
5933                        &snapshot,
5934                        &style,
5935                        editor_width,
5936                        is_row_soft_wrapped,
5937                        cx,
5938                    )
5939                    .width;
5940
5941                    let scrollbar_range_data = ScrollbarRangeData::new(
5942                        scrollbar_bounds,
5943                        letter_size,
5944                        &snapshot,
5945                        longest_line_width,
5946                        &style,
5947                        cx,
5948                    );
5949
5950                    let scroll_range_bounds = scrollbar_range_data.scroll_range;
5951                    let mut scroll_width = scroll_range_bounds.size.width;
5952
5953                    let blocks = cx.with_element_namespace("blocks", |cx| {
5954                        self.render_blocks(
5955                            start_row..end_row,
5956                            &snapshot,
5957                            &hitbox,
5958                            &text_hitbox,
5959                            editor_width,
5960                            &mut scroll_width,
5961                            &gutter_dimensions,
5962                            em_width,
5963                            gutter_dimensions.full_width(),
5964                            line_height,
5965                            &line_layouts,
5966                            &local_selections,
5967                            is_row_soft_wrapped,
5968                            cx,
5969                        )
5970                    });
5971                    let mut blocks = match blocks {
5972                        Ok(blocks) => blocks,
5973                        Err(resized_blocks) => {
5974                            self.editor.update(cx, |editor, cx| {
5975                                editor.resize_blocks(resized_blocks, autoscroll_request, cx)
5976                            });
5977                            return self.prepaint(None, bounds, &mut (), cx);
5978                        }
5979                    };
5980
5981                    let start_buffer_row =
5982                        MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
5983                    let end_buffer_row =
5984                        MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
5985
5986                    let scroll_max = point(
5987                        ((scroll_width - scrollbar_bounds.size.width) / em_width).max(0.0),
5988                        max_row.as_f32(),
5989                    );
5990
5991                    self.editor.update(cx, |editor, cx| {
5992                        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
5993
5994                        let autoscrolled = if autoscroll_horizontally {
5995                            editor.autoscroll_horizontally(
5996                                start_row,
5997                                text_hitbox.size.width,
5998                                scroll_width,
5999                                em_width,
6000                                &line_layouts,
6001                                cx,
6002                            )
6003                        } else {
6004                            false
6005                        };
6006
6007                        if clamped || autoscrolled {
6008                            snapshot = editor.snapshot(cx);
6009                            scroll_position = snapshot.scroll_position();
6010                        }
6011                    });
6012
6013                    let scroll_pixel_position = point(
6014                        scroll_position.x * em_width,
6015                        scroll_position.y * line_height,
6016                    );
6017
6018                    let indent_guides = self.layout_indent_guides(
6019                        content_origin,
6020                        text_hitbox.origin,
6021                        start_buffer_row..end_buffer_row,
6022                        scroll_pixel_position,
6023                        line_height,
6024                        &snapshot,
6025                        cx,
6026                    );
6027
6028                    let crease_trailers = cx.with_element_namespace("crease_trailers", |cx| {
6029                        self.prepaint_crease_trailers(
6030                            crease_trailers,
6031                            &line_layouts,
6032                            line_height,
6033                            content_origin,
6034                            scroll_pixel_position,
6035                            em_width,
6036                            cx,
6037                        )
6038                    });
6039
6040                    let mut inline_blame = None;
6041                    if let Some(newest_selection_head) = newest_selection_head {
6042                        let display_row = newest_selection_head.row();
6043                        if (start_row..end_row).contains(&display_row) {
6044                            let line_ix = display_row.minus(start_row) as usize;
6045                            let line_layout = &line_layouts[line_ix];
6046                            let crease_trailer_layout = crease_trailers[line_ix].as_ref();
6047                            inline_blame = self.layout_inline_blame(
6048                                display_row,
6049                                &snapshot.display_snapshot,
6050                                line_layout,
6051                                crease_trailer_layout,
6052                                em_width,
6053                                content_origin,
6054                                scroll_pixel_position,
6055                                line_height,
6056                                cx,
6057                            );
6058                        }
6059                    }
6060
6061                    let blamed_display_rows = self.layout_blame_entries(
6062                        buffer_rows.into_iter(),
6063                        em_width,
6064                        scroll_position,
6065                        line_height,
6066                        &gutter_hitbox,
6067                        gutter_dimensions.git_blame_entries_width,
6068                        cx,
6069                    );
6070
6071                    let scroll_max = point(
6072                        ((scroll_width - scrollbar_bounds.size.width) / em_width).max(0.0),
6073                        max_scroll_top,
6074                    );
6075
6076                    self.editor.update(cx, |editor, cx| {
6077                        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
6078
6079                        let autoscrolled = if autoscroll_horizontally {
6080                            editor.autoscroll_horizontally(
6081                                start_row,
6082                                text_hitbox.size.width,
6083                                scroll_width,
6084                                em_width,
6085                                &line_layouts,
6086                                cx,
6087                            )
6088                        } else {
6089                            false
6090                        };
6091
6092                        if clamped || autoscrolled {
6093                            snapshot = editor.snapshot(cx);
6094                            scroll_position = snapshot.scroll_position();
6095                        }
6096                    });
6097
6098                    let line_elements = self.prepaint_lines(
6099                        start_row,
6100                        &mut line_layouts,
6101                        line_height,
6102                        scroll_pixel_position,
6103                        content_origin,
6104                        cx,
6105                    );
6106
6107                    let mut block_start_rows = HashSet::default();
6108                    cx.with_element_namespace("blocks", |cx| {
6109                        self.layout_blocks(
6110                            &mut blocks,
6111                            &mut block_start_rows,
6112                            &hitbox,
6113                            line_height,
6114                            scroll_pixel_position,
6115                            cx,
6116                        );
6117                    });
6118
6119                    let cursors = self.collect_cursors(&snapshot, cx);
6120                    let visible_row_range = start_row..end_row;
6121                    let non_visible_cursors = cursors
6122                        .iter()
6123                        .any(move |c| !visible_row_range.contains(&c.0.row()));
6124
6125                    let visible_cursors = self.layout_visible_cursors(
6126                        &snapshot,
6127                        &selections,
6128                        &block_start_rows,
6129                        start_row..end_row,
6130                        &line_layouts,
6131                        &text_hitbox,
6132                        content_origin,
6133                        scroll_position,
6134                        scroll_pixel_position,
6135                        line_height,
6136                        em_width,
6137                        autoscroll_containing_element,
6138                        cx,
6139                    );
6140
6141                    let scrollbars_layout = self.layout_scrollbars(
6142                        &snapshot,
6143                        scrollbar_range_data,
6144                        scroll_position,
6145                        non_visible_cursors,
6146                        cx,
6147                    );
6148
6149                    let gutter_settings = EditorSettings::get_global(cx).gutter;
6150
6151                    let expanded_add_hunks_by_rows = self.editor.update(cx, |editor, _| {
6152                        editor
6153                            .diff_map
6154                            .hunks(false)
6155                            .filter(|hunk| hunk.status == DiffHunkStatus::Added)
6156                            .map(|expanded_hunk| {
6157                                let start_row = expanded_hunk
6158                                    .hunk_range
6159                                    .start
6160                                    .to_display_point(&snapshot)
6161                                    .row();
6162                                (start_row, expanded_hunk.clone())
6163                            })
6164                            .collect::<HashMap<_, _>>()
6165                    });
6166
6167                    let rows_with_hunk_bounds = display_hunks
6168                        .iter()
6169                        .filter_map(|(hunk, hitbox)| Some((hunk, hitbox.as_ref()?.bounds)))
6170                        .fold(
6171                            HashMap::default(),
6172                            |mut rows_with_hunk_bounds, (hunk, bounds)| {
6173                                match hunk {
6174                                    DisplayDiffHunk::Folded { display_row } => {
6175                                        rows_with_hunk_bounds.insert(*display_row, bounds);
6176                                    }
6177                                    DisplayDiffHunk::Unfolded {
6178                                        display_row_range, ..
6179                                    } => {
6180                                        for display_row in display_row_range.iter_rows() {
6181                                            rows_with_hunk_bounds.insert(display_row, bounds);
6182                                        }
6183                                    }
6184                                }
6185                                rows_with_hunk_bounds
6186                            },
6187                        );
6188                    let mut code_actions_indicator = None;
6189                    if let Some(newest_selection_head) = newest_selection_head {
6190                        if (start_row..end_row).contains(&newest_selection_head.row()) {
6191                            self.layout_context_menu(
6192                                line_height,
6193                                &text_hitbox,
6194                                content_origin,
6195                                start_row,
6196                                scroll_pixel_position,
6197                                &line_layouts,
6198                                newest_selection_head,
6199                                gutter_dimensions.width - gutter_dimensions.left_padding,
6200                                cx,
6201                            );
6202
6203                            let show_code_actions = snapshot
6204                                .show_code_actions
6205                                .unwrap_or(gutter_settings.code_actions);
6206                            if show_code_actions {
6207                                let newest_selection_point =
6208                                    newest_selection_head.to_point(&snapshot.display_snapshot);
6209                                let newest_selection_display_row =
6210                                    newest_selection_point.to_display_point(&snapshot).row();
6211                                if !expanded_add_hunks_by_rows
6212                                    .contains_key(&newest_selection_display_row)
6213                                {
6214                                    if !snapshot
6215                                        .is_line_folded(MultiBufferRow(newest_selection_point.row))
6216                                    {
6217                                        let buffer = snapshot.buffer_snapshot.buffer_line_for_row(
6218                                            MultiBufferRow(newest_selection_point.row),
6219                                        );
6220                                        if let Some((buffer, range)) = buffer {
6221                                            let buffer_id = buffer.remote_id();
6222                                            let row = range.start.row;
6223                                            let has_test_indicator = self
6224                                                .editor
6225                                                .read(cx)
6226                                                .tasks
6227                                                .contains_key(&(buffer_id, row));
6228
6229                                            if !has_test_indicator {
6230                                                code_actions_indicator = self
6231                                                    .layout_code_actions_indicator(
6232                                                        line_height,
6233                                                        newest_selection_head,
6234                                                        scroll_pixel_position,
6235                                                        &gutter_dimensions,
6236                                                        &gutter_hitbox,
6237                                                        &rows_with_hunk_bounds,
6238                                                        cx,
6239                                                    );
6240                                            }
6241                                        }
6242                                    }
6243                                }
6244                            }
6245                        }
6246                    }
6247
6248                    let test_indicators = if gutter_settings.runnables {
6249                        self.layout_run_indicators(
6250                            line_height,
6251                            start_row..end_row,
6252                            scroll_pixel_position,
6253                            &gutter_dimensions,
6254                            &gutter_hitbox,
6255                            &rows_with_hunk_bounds,
6256                            &snapshot,
6257                            cx,
6258                        )
6259                    } else {
6260                        Vec::new()
6261                    };
6262
6263                    self.layout_signature_help(
6264                        &hitbox,
6265                        content_origin,
6266                        scroll_pixel_position,
6267                        newest_selection_head,
6268                        start_row,
6269                        &line_layouts,
6270                        line_height,
6271                        em_width,
6272                        cx,
6273                    );
6274
6275                    if !cx.has_active_drag() {
6276                        self.layout_hover_popovers(
6277                            &snapshot,
6278                            &hitbox,
6279                            &text_hitbox,
6280                            start_row..end_row,
6281                            content_origin,
6282                            scroll_pixel_position,
6283                            &line_layouts,
6284                            line_height,
6285                            em_width,
6286                            cx,
6287                        );
6288                    }
6289
6290                    let inline_completion_popover = self.layout_inline_completion_popover(
6291                        &text_hitbox.bounds,
6292                        &snapshot,
6293                        start_row..end_row,
6294                        scroll_position.y,
6295                        scroll_position.y + height_in_lines,
6296                        &line_layouts,
6297                        line_height,
6298                        scroll_pixel_position,
6299                        editor_width,
6300                        &style,
6301                        cx,
6302                    );
6303
6304                    let mouse_context_menu = self.layout_mouse_context_menu(
6305                        &snapshot,
6306                        start_row..end_row,
6307                        content_origin,
6308                        cx,
6309                    );
6310
6311                    cx.with_element_namespace("crease_toggles", |cx| {
6312                        self.prepaint_crease_toggles(
6313                            &mut crease_toggles,
6314                            line_height,
6315                            &gutter_dimensions,
6316                            gutter_settings,
6317                            scroll_pixel_position,
6318                            &gutter_hitbox,
6319                            cx,
6320                        )
6321                    });
6322
6323                    let invisible_symbol_font_size = font_size / 2.;
6324                    let tab_invisible = cx
6325                        .text_system()
6326                        .shape_line(
6327                            "".into(),
6328                            invisible_symbol_font_size,
6329                            &[TextRun {
6330                                len: "".len(),
6331                                font: self.style.text.font(),
6332                                color: cx.theme().colors().editor_invisible,
6333                                background_color: None,
6334                                underline: None,
6335                                strikethrough: None,
6336                            }],
6337                        )
6338                        .unwrap();
6339                    let space_invisible = cx
6340                        .text_system()
6341                        .shape_line(
6342                            "".into(),
6343                            invisible_symbol_font_size,
6344                            &[TextRun {
6345                                len: "".len(),
6346                                font: self.style.text.font(),
6347                                color: cx.theme().colors().editor_invisible,
6348                                background_color: None,
6349                                underline: None,
6350                                strikethrough: None,
6351                            }],
6352                        )
6353                        .unwrap();
6354
6355                    EditorLayout {
6356                        mode: snapshot.mode,
6357                        position_map: Rc::new(PositionMap {
6358                            size: bounds.size,
6359                            scroll_pixel_position,
6360                            scroll_max,
6361                            line_layouts,
6362                            line_height,
6363                            em_width,
6364                            em_advance,
6365                            snapshot,
6366                        }),
6367                        visible_display_row_range: start_row..end_row,
6368                        wrap_guides,
6369                        indent_guides,
6370                        hitbox,
6371                        text_hitbox,
6372                        gutter_hitbox,
6373                        gutter_dimensions,
6374                        display_hunks,
6375                        content_origin,
6376                        scrollbars_layout,
6377                        active_rows,
6378                        highlighted_rows,
6379                        highlighted_ranges,
6380                        highlighted_gutter_ranges,
6381                        redacted_ranges,
6382                        line_elements,
6383                        line_numbers,
6384                        blamed_display_rows,
6385                        inline_blame,
6386                        blocks,
6387                        cursors,
6388                        visible_cursors,
6389                        selections,
6390                        inline_completion_popover,
6391                        mouse_context_menu,
6392                        test_indicators,
6393                        code_actions_indicator,
6394                        crease_toggles,
6395                        crease_trailers,
6396                        tab_invisible,
6397                        space_invisible,
6398                    }
6399                })
6400            })
6401        })
6402    }
6403
6404    fn paint(
6405        &mut self,
6406        _: Option<&GlobalElementId>,
6407        bounds: Bounds<gpui::Pixels>,
6408        _: &mut Self::RequestLayoutState,
6409        layout: &mut Self::PrepaintState,
6410        cx: &mut WindowContext,
6411    ) {
6412        let focus_handle = self.editor.focus_handle(cx);
6413        let key_context = self.editor.update(cx, |editor, cx| editor.key_context(cx));
6414        cx.set_key_context(key_context);
6415        cx.handle_input(
6416            &focus_handle,
6417            ElementInputHandler::new(bounds, self.editor.clone()),
6418        );
6419        self.register_actions(cx);
6420        self.register_key_listeners(cx, layout);
6421
6422        let text_style = TextStyleRefinement {
6423            font_size: Some(self.style.text.font_size),
6424            line_height: Some(self.style.text.line_height),
6425            ..Default::default()
6426        };
6427        let hovered_hunk = layout
6428            .display_hunks
6429            .iter()
6430            .find_map(|(hunk, hunk_hitbox)| match hunk {
6431                DisplayDiffHunk::Folded { .. } => None,
6432                DisplayDiffHunk::Unfolded {
6433                    diff_base_byte_range,
6434                    multi_buffer_range,
6435                    status,
6436                    ..
6437                } => {
6438                    if hunk_hitbox
6439                        .as_ref()
6440                        .map(|hitbox| hitbox.is_hovered(cx))
6441                        .unwrap_or(false)
6442                    {
6443                        Some(HoveredHunk {
6444                            status: *status,
6445                            multi_buffer_range: multi_buffer_range.clone(),
6446                            diff_base_byte_range: diff_base_byte_range.clone(),
6447                        })
6448                    } else {
6449                        None
6450                    }
6451                }
6452            });
6453        let rem_size = self.rem_size(cx);
6454        cx.with_rem_size(rem_size, |cx| {
6455            cx.with_text_style(Some(text_style), |cx| {
6456                cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
6457                    self.paint_mouse_listeners(layout, hovered_hunk, cx);
6458                    self.paint_background(layout, cx);
6459                    self.paint_indent_guides(layout, cx);
6460
6461                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
6462                        self.paint_blamed_display_rows(layout, cx);
6463                        self.paint_line_numbers(layout, cx);
6464                    }
6465
6466                    self.paint_text(layout, cx);
6467
6468                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
6469                        self.paint_gutter_highlights(layout, cx);
6470                        self.paint_gutter_indicators(layout, cx);
6471                    }
6472
6473                    if !layout.blocks.is_empty() {
6474                        cx.with_element_namespace("blocks", |cx| {
6475                            self.paint_blocks(layout, cx);
6476                        });
6477                    }
6478
6479                    self.paint_scrollbars(layout, cx);
6480                    self.paint_inline_completion_popover(layout, cx);
6481                    self.paint_mouse_context_menu(layout, cx);
6482                });
6483            })
6484        })
6485    }
6486}
6487
6488pub(super) fn gutter_bounds(
6489    editor_bounds: Bounds<Pixels>,
6490    gutter_dimensions: GutterDimensions,
6491) -> Bounds<Pixels> {
6492    Bounds {
6493        origin: editor_bounds.origin,
6494        size: size(gutter_dimensions.width, editor_bounds.size.height),
6495    }
6496}
6497
6498struct ScrollbarRangeData {
6499    scrollbar_bounds: Bounds<Pixels>,
6500    scroll_range: Bounds<Pixels>,
6501    letter_size: Size<Pixels>,
6502}
6503
6504impl ScrollbarRangeData {
6505    pub fn new(
6506        scrollbar_bounds: Bounds<Pixels>,
6507        letter_size: Size<Pixels>,
6508        snapshot: &EditorSnapshot,
6509        longest_line_width: Pixels,
6510        style: &EditorStyle,
6511        cx: &WindowContext,
6512    ) -> ScrollbarRangeData {
6513        // TODO: Simplify this function down, it requires a lot of parameters
6514        let max_row = snapshot.max_point().row();
6515        let text_bounds_size = size(longest_line_width, max_row.0 as f32 * letter_size.height);
6516
6517        let scrollbar_width = style.scrollbar_width;
6518
6519        let settings = EditorSettings::get_global(cx);
6520        let scroll_beyond_last_line: Pixels = match settings.scroll_beyond_last_line {
6521            ScrollBeyondLastLine::OnePage => px(scrollbar_bounds.size.height / letter_size.height),
6522            ScrollBeyondLastLine::Off => px(1.),
6523            ScrollBeyondLastLine::VerticalScrollMargin => px(1.0 + settings.vertical_scroll_margin),
6524        };
6525
6526        let overscroll = size(
6527            scrollbar_width + (letter_size.width / 2.0),
6528            letter_size.height * scroll_beyond_last_line,
6529        );
6530
6531        let scroll_range = Bounds {
6532            origin: scrollbar_bounds.origin,
6533            size: text_bounds_size + overscroll,
6534        };
6535
6536        ScrollbarRangeData {
6537            scrollbar_bounds,
6538            scroll_range,
6539            letter_size,
6540        }
6541    }
6542}
6543
6544impl IntoElement for EditorElement {
6545    type Element = Self;
6546
6547    fn into_element(self) -> Self::Element {
6548        self
6549    }
6550}
6551
6552pub struct EditorLayout {
6553    position_map: Rc<PositionMap>,
6554    hitbox: Hitbox,
6555    text_hitbox: Hitbox,
6556    gutter_hitbox: Hitbox,
6557    gutter_dimensions: GutterDimensions,
6558    content_origin: gpui::Point<Pixels>,
6559    scrollbars_layout: AxisPair<Option<ScrollbarLayout>>,
6560    mode: EditorMode,
6561    wrap_guides: SmallVec<[(Pixels, bool); 2]>,
6562    indent_guides: Option<Vec<IndentGuideLayout>>,
6563    visible_display_row_range: Range<DisplayRow>,
6564    active_rows: BTreeMap<DisplayRow, bool>,
6565    highlighted_rows: BTreeMap<DisplayRow, Hsla>,
6566    line_elements: SmallVec<[AnyElement; 1]>,
6567    line_numbers: Vec<Option<ShapedLine>>,
6568    display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
6569    blamed_display_rows: Option<Vec<AnyElement>>,
6570    inline_blame: Option<AnyElement>,
6571    blocks: Vec<BlockLayout>,
6572    highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
6573    highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
6574    redacted_ranges: Vec<Range<DisplayPoint>>,
6575    cursors: Vec<(DisplayPoint, Hsla)>,
6576    visible_cursors: Vec<CursorLayout>,
6577    selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
6578    code_actions_indicator: Option<AnyElement>,
6579    test_indicators: Vec<AnyElement>,
6580    crease_toggles: Vec<Option<AnyElement>>,
6581    crease_trailers: Vec<Option<CreaseTrailerLayout>>,
6582    inline_completion_popover: Option<AnyElement>,
6583    mouse_context_menu: Option<AnyElement>,
6584    tab_invisible: ShapedLine,
6585    space_invisible: ShapedLine,
6586}
6587
6588impl EditorLayout {
6589    fn line_end_overshoot(&self) -> Pixels {
6590        0.15 * self.position_map.line_height
6591    }
6592}
6593
6594struct ColoredRange<T> {
6595    start: T,
6596    end: T,
6597    color: Hsla,
6598}
6599
6600#[derive(Clone)]
6601struct ScrollbarLayout {
6602    hitbox: Hitbox,
6603    visible_range: Range<f32>,
6604    visible: bool,
6605    text_unit_size: Pixels,
6606    thumb_size: Pixels,
6607    axis: Axis,
6608}
6609
6610impl ScrollbarLayout {
6611    const BORDER_WIDTH: Pixels = px(1.0);
6612    const LINE_MARKER_HEIGHT: Pixels = px(2.0);
6613    const MIN_MARKER_HEIGHT: Pixels = px(5.0);
6614    // const MIN_THUMB_HEIGHT: Pixels = px(20.0);
6615
6616    fn thumb_bounds(&self) -> Bounds<Pixels> {
6617        match self.axis {
6618            Axis::Vertical => {
6619                let thumb_top = self.y_for_row(self.visible_range.start);
6620                let thumb_bottom = thumb_top + self.thumb_size;
6621                Bounds::from_corners(
6622                    point(self.hitbox.left(), thumb_top),
6623                    point(self.hitbox.right(), thumb_bottom),
6624                )
6625            }
6626            Axis::Horizontal => {
6627                let thumb_left =
6628                    self.hitbox.left() + self.visible_range.start * self.text_unit_size;
6629                let thumb_right = thumb_left + self.thumb_size;
6630                Bounds::from_corners(
6631                    point(thumb_left, self.hitbox.top()),
6632                    point(thumb_right, self.hitbox.bottom()),
6633                )
6634            }
6635        }
6636    }
6637
6638    fn y_for_row(&self, row: f32) -> Pixels {
6639        self.hitbox.top() + row * self.text_unit_size
6640    }
6641
6642    fn marker_quads_for_ranges(
6643        &self,
6644        row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
6645        column: Option<usize>,
6646    ) -> Vec<PaintQuad> {
6647        struct MinMax {
6648            min: Pixels,
6649            max: Pixels,
6650        }
6651        let (x_range, height_limit) = if let Some(column) = column {
6652            let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
6653            let start = Self::BORDER_WIDTH + (column as f32 * column_width);
6654            let end = start + column_width;
6655            (
6656                Range { start, end },
6657                MinMax {
6658                    min: Self::MIN_MARKER_HEIGHT,
6659                    max: px(f32::MAX),
6660                },
6661            )
6662        } else {
6663            (
6664                Range {
6665                    start: Self::BORDER_WIDTH,
6666                    end: self.hitbox.size.width,
6667                },
6668                MinMax {
6669                    min: Self::LINE_MARKER_HEIGHT,
6670                    max: Self::LINE_MARKER_HEIGHT,
6671                },
6672            )
6673        };
6674
6675        let row_to_y = |row: DisplayRow| row.as_f32() * self.text_unit_size;
6676        let mut pixel_ranges = row_ranges
6677            .into_iter()
6678            .map(|range| {
6679                let start_y = row_to_y(range.start);
6680                let end_y = row_to_y(range.end)
6681                    + self
6682                        .text_unit_size
6683                        .max(height_limit.min)
6684                        .min(height_limit.max);
6685                ColoredRange {
6686                    start: start_y,
6687                    end: end_y,
6688                    color: range.color,
6689                }
6690            })
6691            .peekable();
6692
6693        let mut quads = Vec::new();
6694        while let Some(mut pixel_range) = pixel_ranges.next() {
6695            while let Some(next_pixel_range) = pixel_ranges.peek() {
6696                if pixel_range.end >= next_pixel_range.start - px(1.0)
6697                    && pixel_range.color == next_pixel_range.color
6698                {
6699                    pixel_range.end = next_pixel_range.end.max(pixel_range.end);
6700                    pixel_ranges.next();
6701                } else {
6702                    break;
6703                }
6704            }
6705
6706            let bounds = Bounds::from_corners(
6707                point(x_range.start, pixel_range.start),
6708                point(x_range.end, pixel_range.end),
6709            );
6710            quads.push(quad(
6711                bounds,
6712                Corners::default(),
6713                pixel_range.color,
6714                Edges::default(),
6715                Hsla::transparent_black(),
6716            ));
6717        }
6718
6719        quads
6720    }
6721}
6722
6723struct CreaseTrailerLayout {
6724    element: AnyElement,
6725    bounds: Bounds<Pixels>,
6726}
6727
6728struct PositionMap {
6729    size: Size<Pixels>,
6730    line_height: Pixels,
6731    scroll_pixel_position: gpui::Point<Pixels>,
6732    scroll_max: gpui::Point<f32>,
6733    em_width: Pixels,
6734    em_advance: Pixels,
6735    line_layouts: Vec<LineWithInvisibles>,
6736    snapshot: EditorSnapshot,
6737}
6738
6739#[derive(Debug, Copy, Clone)]
6740pub struct PointForPosition {
6741    pub previous_valid: DisplayPoint,
6742    pub next_valid: DisplayPoint,
6743    pub exact_unclipped: DisplayPoint,
6744    pub column_overshoot_after_line_end: u32,
6745}
6746
6747impl PointForPosition {
6748    pub fn as_valid(&self) -> Option<DisplayPoint> {
6749        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
6750            Some(self.previous_valid)
6751        } else {
6752            None
6753        }
6754    }
6755}
6756
6757impl PositionMap {
6758    fn point_for_position(
6759        &self,
6760        text_bounds: Bounds<Pixels>,
6761        position: gpui::Point<Pixels>,
6762    ) -> PointForPosition {
6763        let scroll_position = self.snapshot.scroll_position();
6764        let position = position - text_bounds.origin;
6765        let y = position.y.max(px(0.)).min(self.size.height);
6766        let x = position.x + (scroll_position.x * self.em_width);
6767        let row = ((y / self.line_height) + scroll_position.y) as u32;
6768
6769        let (column, x_overshoot_after_line_end) = if let Some(line) = self
6770            .line_layouts
6771            .get(row as usize - scroll_position.y as usize)
6772        {
6773            if let Some(ix) = line.index_for_x(x) {
6774                (ix as u32, px(0.))
6775            } else {
6776                (line.len as u32, px(0.).max(x - line.width))
6777            }
6778        } else {
6779            (0, x)
6780        };
6781
6782        let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
6783        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
6784        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
6785
6786        let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
6787        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
6788        PointForPosition {
6789            previous_valid,
6790            next_valid,
6791            exact_unclipped,
6792            column_overshoot_after_line_end,
6793        }
6794    }
6795}
6796
6797struct BlockLayout {
6798    id: BlockId,
6799    row: Option<DisplayRow>,
6800    element: AnyElement,
6801    available_space: Size<AvailableSpace>,
6802    style: BlockStyle,
6803}
6804
6805fn layout_line(
6806    row: DisplayRow,
6807    snapshot: &EditorSnapshot,
6808    style: &EditorStyle,
6809    text_width: Pixels,
6810    is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
6811    cx: &mut WindowContext,
6812) -> LineWithInvisibles {
6813    let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
6814    LineWithInvisibles::from_chunks(
6815        chunks,
6816        &style,
6817        MAX_LINE_LEN,
6818        1,
6819        snapshot.mode,
6820        text_width,
6821        is_row_soft_wrapped,
6822        cx,
6823    )
6824    .pop()
6825    .unwrap()
6826}
6827
6828#[derive(Debug)]
6829pub struct IndentGuideLayout {
6830    origin: gpui::Point<Pixels>,
6831    length: Pixels,
6832    single_indent_width: Pixels,
6833    depth: u32,
6834    active: bool,
6835    settings: IndentGuideSettings,
6836}
6837
6838pub struct CursorLayout {
6839    origin: gpui::Point<Pixels>,
6840    block_width: Pixels,
6841    line_height: Pixels,
6842    color: Hsla,
6843    shape: CursorShape,
6844    block_text: Option<ShapedLine>,
6845    cursor_name: Option<AnyElement>,
6846}
6847
6848#[derive(Debug)]
6849pub struct CursorName {
6850    string: SharedString,
6851    color: Hsla,
6852    is_top_row: bool,
6853}
6854
6855impl CursorLayout {
6856    pub fn new(
6857        origin: gpui::Point<Pixels>,
6858        block_width: Pixels,
6859        line_height: Pixels,
6860        color: Hsla,
6861        shape: CursorShape,
6862        block_text: Option<ShapedLine>,
6863    ) -> CursorLayout {
6864        CursorLayout {
6865            origin,
6866            block_width,
6867            line_height,
6868            color,
6869            shape,
6870            block_text,
6871            cursor_name: None,
6872        }
6873    }
6874
6875    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
6876        Bounds {
6877            origin: self.origin + origin,
6878            size: size(self.block_width, self.line_height),
6879        }
6880    }
6881
6882    fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
6883        match self.shape {
6884            CursorShape::Bar => Bounds {
6885                origin: self.origin + origin,
6886                size: size(px(2.0), self.line_height),
6887            },
6888            CursorShape::Block | CursorShape::Hollow => Bounds {
6889                origin: self.origin + origin,
6890                size: size(self.block_width, self.line_height),
6891            },
6892            CursorShape::Underline => Bounds {
6893                origin: self.origin
6894                    + origin
6895                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
6896                size: size(self.block_width, px(2.0)),
6897            },
6898        }
6899    }
6900
6901    pub fn layout(
6902        &mut self,
6903        origin: gpui::Point<Pixels>,
6904        cursor_name: Option<CursorName>,
6905        cx: &mut WindowContext,
6906    ) {
6907        if let Some(cursor_name) = cursor_name {
6908            let bounds = self.bounds(origin);
6909            let text_size = self.line_height / 1.5;
6910
6911            let name_origin = if cursor_name.is_top_row {
6912                point(bounds.right() - px(1.), bounds.top())
6913            } else {
6914                point(bounds.left(), bounds.top() - text_size / 2. - px(1.))
6915            };
6916            let mut name_element = div()
6917                .bg(self.color)
6918                .text_size(text_size)
6919                .px_0p5()
6920                .line_height(text_size + px(2.))
6921                .text_color(cursor_name.color)
6922                .child(cursor_name.string.clone())
6923                .into_any_element();
6924
6925            name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), cx);
6926
6927            self.cursor_name = Some(name_element);
6928        }
6929    }
6930
6931    pub fn paint(&mut self, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
6932        let bounds = self.bounds(origin);
6933
6934        //Draw background or border quad
6935        let cursor = if matches!(self.shape, CursorShape::Hollow) {
6936            outline(bounds, self.color)
6937        } else {
6938            fill(bounds, self.color)
6939        };
6940
6941        if let Some(name) = &mut self.cursor_name {
6942            name.paint(cx);
6943        }
6944
6945        cx.paint_quad(cursor);
6946
6947        if let Some(block_text) = &self.block_text {
6948            block_text
6949                .paint(self.origin + origin, self.line_height, cx)
6950                .log_err();
6951        }
6952    }
6953
6954    pub fn shape(&self) -> CursorShape {
6955        self.shape
6956    }
6957}
6958
6959#[derive(Debug)]
6960pub struct HighlightedRange {
6961    pub start_y: Pixels,
6962    pub line_height: Pixels,
6963    pub lines: Vec<HighlightedRangeLine>,
6964    pub color: Hsla,
6965    pub corner_radius: Pixels,
6966}
6967
6968#[derive(Debug)]
6969pub struct HighlightedRangeLine {
6970    pub start_x: Pixels,
6971    pub end_x: Pixels,
6972}
6973
6974impl HighlightedRange {
6975    pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut WindowContext) {
6976        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
6977            self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
6978            self.paint_lines(
6979                self.start_y + self.line_height,
6980                &self.lines[1..],
6981                bounds,
6982                cx,
6983            );
6984        } else {
6985            self.paint_lines(self.start_y, &self.lines, bounds, cx);
6986        }
6987    }
6988
6989    fn paint_lines(
6990        &self,
6991        start_y: Pixels,
6992        lines: &[HighlightedRangeLine],
6993        _bounds: Bounds<Pixels>,
6994        cx: &mut WindowContext,
6995    ) {
6996        if lines.is_empty() {
6997            return;
6998        }
6999
7000        let first_line = lines.first().unwrap();
7001        let last_line = lines.last().unwrap();
7002
7003        let first_top_left = point(first_line.start_x, start_y);
7004        let first_top_right = point(first_line.end_x, start_y);
7005
7006        let curve_height = point(Pixels::ZERO, self.corner_radius);
7007        let curve_width = |start_x: Pixels, end_x: Pixels| {
7008            let max = (end_x - start_x) / 2.;
7009            let width = if max < self.corner_radius {
7010                max
7011            } else {
7012                self.corner_radius
7013            };
7014
7015            point(width, Pixels::ZERO)
7016        };
7017
7018        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
7019        let mut path = gpui::Path::new(first_top_right - top_curve_width);
7020        path.curve_to(first_top_right + curve_height, first_top_right);
7021
7022        let mut iter = lines.iter().enumerate().peekable();
7023        while let Some((ix, line)) = iter.next() {
7024            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
7025
7026            if let Some((_, next_line)) = iter.peek() {
7027                let next_top_right = point(next_line.end_x, bottom_right.y);
7028
7029                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
7030                    Ordering::Equal => {
7031                        path.line_to(bottom_right);
7032                    }
7033                    Ordering::Less => {
7034                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
7035                        path.line_to(bottom_right - curve_height);
7036                        if self.corner_radius > Pixels::ZERO {
7037                            path.curve_to(bottom_right - curve_width, bottom_right);
7038                        }
7039                        path.line_to(next_top_right + curve_width);
7040                        if self.corner_radius > Pixels::ZERO {
7041                            path.curve_to(next_top_right + curve_height, next_top_right);
7042                        }
7043                    }
7044                    Ordering::Greater => {
7045                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
7046                        path.line_to(bottom_right - curve_height);
7047                        if self.corner_radius > Pixels::ZERO {
7048                            path.curve_to(bottom_right + curve_width, bottom_right);
7049                        }
7050                        path.line_to(next_top_right - curve_width);
7051                        if self.corner_radius > Pixels::ZERO {
7052                            path.curve_to(next_top_right + curve_height, next_top_right);
7053                        }
7054                    }
7055                }
7056            } else {
7057                let curve_width = curve_width(line.start_x, line.end_x);
7058                path.line_to(bottom_right - curve_height);
7059                if self.corner_radius > Pixels::ZERO {
7060                    path.curve_to(bottom_right - curve_width, bottom_right);
7061                }
7062
7063                let bottom_left = point(line.start_x, bottom_right.y);
7064                path.line_to(bottom_left + curve_width);
7065                if self.corner_radius > Pixels::ZERO {
7066                    path.curve_to(bottom_left - curve_height, bottom_left);
7067                }
7068            }
7069        }
7070
7071        if first_line.start_x > last_line.start_x {
7072            let curve_width = curve_width(last_line.start_x, first_line.start_x);
7073            let second_top_left = point(last_line.start_x, start_y + self.line_height);
7074            path.line_to(second_top_left + curve_height);
7075            if self.corner_radius > Pixels::ZERO {
7076                path.curve_to(second_top_left + curve_width, second_top_left);
7077            }
7078            let first_bottom_left = point(first_line.start_x, second_top_left.y);
7079            path.line_to(first_bottom_left - curve_width);
7080            if self.corner_radius > Pixels::ZERO {
7081                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
7082            }
7083        }
7084
7085        path.line_to(first_top_left + curve_height);
7086        if self.corner_radius > Pixels::ZERO {
7087            path.curve_to(first_top_left + top_curve_width, first_top_left);
7088        }
7089        path.line_to(first_top_right - top_curve_width);
7090
7091        cx.paint_path(path, self.color);
7092    }
7093}
7094
7095pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
7096    (delta.pow(1.5) / 100.0).into()
7097}
7098
7099fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
7100    (delta.pow(1.2) / 300.0).into()
7101}
7102
7103pub fn register_action<T: Action>(
7104    view: &View<Editor>,
7105    cx: &mut WindowContext,
7106    listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
7107) {
7108    let view = view.clone();
7109    cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
7110        let action = action.downcast_ref().unwrap();
7111        if phase == DispatchPhase::Bubble {
7112            view.update(cx, |editor, cx| {
7113                listener(editor, action, cx);
7114            })
7115        }
7116    })
7117}
7118
7119fn compute_auto_height_layout(
7120    editor: &mut Editor,
7121    max_lines: usize,
7122    max_line_number_width: Pixels,
7123    known_dimensions: Size<Option<Pixels>>,
7124    available_width: AvailableSpace,
7125    cx: &mut ViewContext<Editor>,
7126) -> Option<Size<Pixels>> {
7127    let width = known_dimensions.width.or({
7128        if let AvailableSpace::Definite(available_width) = available_width {
7129            Some(available_width)
7130        } else {
7131            None
7132        }
7133    })?;
7134    if let Some(height) = known_dimensions.height {
7135        return Some(size(width, height));
7136    }
7137
7138    let style = editor.style.as_ref().unwrap();
7139    let font_id = cx.text_system().resolve_font(&style.text.font());
7140    let font_size = style.text.font_size.to_pixels(cx.rem_size());
7141    let line_height = style.text.line_height_in_pixels(cx.rem_size());
7142    let em_width = cx
7143        .text_system()
7144        .typographic_bounds(font_id, font_size, 'm')
7145        .unwrap()
7146        .size
7147        .width;
7148    let em_advance = cx
7149        .text_system()
7150        .advance(font_id, font_size, 'm')
7151        .unwrap()
7152        .width;
7153
7154    let mut snapshot = editor.snapshot(cx);
7155    let gutter_dimensions = snapshot.gutter_dimensions(
7156        font_id,
7157        font_size,
7158        em_width,
7159        em_advance,
7160        max_line_number_width,
7161        cx,
7162    );
7163
7164    editor.gutter_dimensions = gutter_dimensions;
7165    let text_width = width - gutter_dimensions.width;
7166    let overscroll = size(em_width, px(0.));
7167
7168    let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
7169    if editor.set_wrap_width(Some(editor_width), cx) {
7170        snapshot = editor.snapshot(cx);
7171    }
7172
7173    let scroll_height = Pixels::from(snapshot.max_point().row().next_row().0) * line_height;
7174    let height = scroll_height
7175        .max(line_height)
7176        .min(line_height * max_lines as f32);
7177
7178    Some(size(width, height))
7179}
7180
7181#[cfg(test)]
7182mod tests {
7183    use super::*;
7184    use crate::{
7185        display_map::{BlockPlacement, BlockProperties},
7186        editor_tests::{init_test, update_test_language_settings},
7187        Editor, MultiBuffer,
7188    };
7189    use gpui::{TestAppContext, VisualTestContext};
7190    use language::language_settings;
7191    use log::info;
7192    use std::num::NonZeroU32;
7193    use util::test::sample_text;
7194
7195    #[gpui::test]
7196    fn test_shape_line_numbers(cx: &mut TestAppContext) {
7197        init_test(cx, |_| {});
7198        let window = cx.add_window(|cx| {
7199            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
7200            Editor::new(EditorMode::Full, buffer, None, true, cx)
7201        });
7202
7203        let editor = window.root(cx).unwrap();
7204        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
7205        let element = EditorElement::new(&editor, style);
7206        let snapshot = window.update(cx, |editor, cx| editor.snapshot(cx)).unwrap();
7207
7208        let layouts = cx
7209            .update_window(*window, |_, cx| {
7210                element.layout_line_numbers(
7211                    DisplayRow(0)..DisplayRow(6),
7212                    (0..6).map(MultiBufferRow).map(Some),
7213                    &Default::default(),
7214                    Some(DisplayPoint::new(DisplayRow(0), 0)),
7215                    &snapshot,
7216                    cx,
7217                )
7218            })
7219            .unwrap();
7220        assert_eq!(layouts.len(), 6);
7221
7222        let relative_rows = window
7223            .update(cx, |editor, cx| {
7224                let snapshot = editor.snapshot(cx);
7225                element.calculate_relative_line_numbers(
7226                    &snapshot,
7227                    &(DisplayRow(0)..DisplayRow(6)),
7228                    Some(DisplayRow(3)),
7229                )
7230            })
7231            .unwrap();
7232        assert_eq!(relative_rows[&DisplayRow(0)], 3);
7233        assert_eq!(relative_rows[&DisplayRow(1)], 2);
7234        assert_eq!(relative_rows[&DisplayRow(2)], 1);
7235        // current line has no relative number
7236        assert_eq!(relative_rows[&DisplayRow(4)], 1);
7237        assert_eq!(relative_rows[&DisplayRow(5)], 2);
7238
7239        // works if cursor is before screen
7240        let relative_rows = window
7241            .update(cx, |editor, cx| {
7242                let snapshot = editor.snapshot(cx);
7243                element.calculate_relative_line_numbers(
7244                    &snapshot,
7245                    &(DisplayRow(3)..DisplayRow(6)),
7246                    Some(DisplayRow(1)),
7247                )
7248            })
7249            .unwrap();
7250        assert_eq!(relative_rows.len(), 3);
7251        assert_eq!(relative_rows[&DisplayRow(3)], 2);
7252        assert_eq!(relative_rows[&DisplayRow(4)], 3);
7253        assert_eq!(relative_rows[&DisplayRow(5)], 4);
7254
7255        // works if cursor is after screen
7256        let relative_rows = window
7257            .update(cx, |editor, cx| {
7258                let snapshot = editor.snapshot(cx);
7259                element.calculate_relative_line_numbers(
7260                    &snapshot,
7261                    &(DisplayRow(0)..DisplayRow(3)),
7262                    Some(DisplayRow(6)),
7263                )
7264            })
7265            .unwrap();
7266        assert_eq!(relative_rows.len(), 3);
7267        assert_eq!(relative_rows[&DisplayRow(0)], 5);
7268        assert_eq!(relative_rows[&DisplayRow(1)], 4);
7269        assert_eq!(relative_rows[&DisplayRow(2)], 3);
7270    }
7271
7272    #[gpui::test]
7273    async fn test_vim_visual_selections(cx: &mut TestAppContext) {
7274        init_test(cx, |_| {});
7275
7276        let window = cx.add_window(|cx| {
7277            let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
7278            Editor::new(EditorMode::Full, buffer, None, true, cx)
7279        });
7280        let cx = &mut VisualTestContext::from_window(*window, cx);
7281        let editor = window.root(cx).unwrap();
7282        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
7283
7284        window
7285            .update(cx, |editor, cx| {
7286                editor.cursor_shape = CursorShape::Block;
7287                editor.change_selections(None, cx, |s| {
7288                    s.select_ranges([
7289                        Point::new(0, 0)..Point::new(1, 0),
7290                        Point::new(3, 2)..Point::new(3, 3),
7291                        Point::new(5, 6)..Point::new(6, 0),
7292                    ]);
7293                });
7294            })
7295            .unwrap();
7296
7297        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
7298            EditorElement::new(&editor, style)
7299        });
7300
7301        assert_eq!(state.selections.len(), 1);
7302        let local_selections = &state.selections[0].1;
7303        assert_eq!(local_selections.len(), 3);
7304        // moves cursor back one line
7305        assert_eq!(
7306            local_selections[0].head,
7307            DisplayPoint::new(DisplayRow(0), 6)
7308        );
7309        assert_eq!(
7310            local_selections[0].range,
7311            DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
7312        );
7313
7314        // moves cursor back one column
7315        assert_eq!(
7316            local_selections[1].range,
7317            DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
7318        );
7319        assert_eq!(
7320            local_selections[1].head,
7321            DisplayPoint::new(DisplayRow(3), 2)
7322        );
7323
7324        // leaves cursor on the max point
7325        assert_eq!(
7326            local_selections[2].range,
7327            DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
7328        );
7329        assert_eq!(
7330            local_selections[2].head,
7331            DisplayPoint::new(DisplayRow(6), 0)
7332        );
7333
7334        // active lines does not include 1 (even though the range of the selection does)
7335        assert_eq!(
7336            state.active_rows.keys().cloned().collect::<Vec<_>>(),
7337            vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
7338        );
7339
7340        // multi-buffer support
7341        // in DisplayPoint coordinates, this is what we're dealing with:
7342        //  0: [[file
7343        //  1:   header
7344        //  2:   section]]
7345        //  3: aaaaaa
7346        //  4: bbbbbb
7347        //  5: cccccc
7348        //  6:
7349        //  7: [[footer]]
7350        //  8: [[header]]
7351        //  9: ffffff
7352        // 10: gggggg
7353        // 11: hhhhhh
7354        // 12:
7355        // 13: [[footer]]
7356        // 14: [[file
7357        // 15:   header
7358        // 16:   section]]
7359        // 17: bbbbbb
7360        // 18: cccccc
7361        // 19: dddddd
7362        // 20: [[footer]]
7363        let window = cx.add_window(|cx| {
7364            let buffer = MultiBuffer::build_multi(
7365                [
7366                    (
7367                        &(sample_text(8, 6, 'a') + "\n"),
7368                        vec![
7369                            Point::new(0, 0)..Point::new(3, 0),
7370                            Point::new(4, 0)..Point::new(7, 0),
7371                        ],
7372                    ),
7373                    (
7374                        &(sample_text(8, 6, 'a') + "\n"),
7375                        vec![Point::new(1, 0)..Point::new(3, 0)],
7376                    ),
7377                ],
7378                cx,
7379            );
7380            Editor::new(EditorMode::Full, buffer, None, true, cx)
7381        });
7382        let editor = window.root(cx).unwrap();
7383        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
7384        let _state = window.update(cx, |editor, cx| {
7385            editor.cursor_shape = CursorShape::Block;
7386            editor.change_selections(None, cx, |s| {
7387                s.select_display_ranges([
7388                    DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0),
7389                    DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0),
7390                ]);
7391            });
7392        });
7393
7394        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
7395            EditorElement::new(&editor, style)
7396        });
7397        assert_eq!(state.selections.len(), 1);
7398        let local_selections = &state.selections[0].1;
7399        assert_eq!(local_selections.len(), 2);
7400
7401        // moves cursor on excerpt boundary back a line
7402        // and doesn't allow selection to bleed through
7403        assert_eq!(
7404            local_selections[0].range,
7405            DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0)
7406        );
7407        assert_eq!(
7408            local_selections[0].head,
7409            DisplayPoint::new(DisplayRow(6), 0)
7410        );
7411        // moves cursor on buffer boundary back two lines
7412        // and doesn't allow selection to bleed through
7413        assert_eq!(
7414            local_selections[1].range,
7415            DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0)
7416        );
7417        assert_eq!(
7418            local_selections[1].head,
7419            DisplayPoint::new(DisplayRow(12), 0)
7420        );
7421    }
7422
7423    #[gpui::test]
7424    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
7425        init_test(cx, |_| {});
7426
7427        let window = cx.add_window(|cx| {
7428            let buffer = MultiBuffer::build_simple("", cx);
7429            Editor::new(EditorMode::Full, buffer, None, true, cx)
7430        });
7431        let cx = &mut VisualTestContext::from_window(*window, cx);
7432        let editor = window.root(cx).unwrap();
7433        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
7434        window
7435            .update(cx, |editor, cx| {
7436                editor.set_placeholder_text("hello", cx);
7437                editor.insert_blocks(
7438                    [BlockProperties {
7439                        style: BlockStyle::Fixed,
7440                        placement: BlockPlacement::Above(Anchor::min()),
7441                        height: 3,
7442                        render: Arc::new(|cx| div().h(3. * cx.line_height()).into_any()),
7443                        priority: 0,
7444                    }],
7445                    None,
7446                    cx,
7447                );
7448
7449                // Blur the editor so that it displays placeholder text.
7450                cx.blur();
7451            })
7452            .unwrap();
7453
7454        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
7455            EditorElement::new(&editor, style)
7456        });
7457        assert_eq!(state.position_map.line_layouts.len(), 4);
7458        assert_eq!(
7459            state
7460                .line_numbers
7461                .iter()
7462                .map(Option::is_some)
7463                .collect::<Vec<_>>(),
7464            &[false, false, false, true]
7465        );
7466    }
7467
7468    #[gpui::test]
7469    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
7470        const TAB_SIZE: u32 = 4;
7471
7472        let input_text = "\t \t|\t| a b";
7473        let expected_invisibles = vec![
7474            Invisible::Tab {
7475                line_start_offset: 0,
7476                line_end_offset: TAB_SIZE as usize,
7477            },
7478            Invisible::Whitespace {
7479                line_offset: TAB_SIZE as usize,
7480            },
7481            Invisible::Tab {
7482                line_start_offset: TAB_SIZE as usize + 1,
7483                line_end_offset: TAB_SIZE as usize * 2,
7484            },
7485            Invisible::Tab {
7486                line_start_offset: TAB_SIZE as usize * 2 + 1,
7487                line_end_offset: TAB_SIZE as usize * 3,
7488            },
7489            Invisible::Whitespace {
7490                line_offset: TAB_SIZE as usize * 3 + 1,
7491            },
7492            Invisible::Whitespace {
7493                line_offset: TAB_SIZE as usize * 3 + 3,
7494            },
7495        ];
7496        assert_eq!(
7497            expected_invisibles.len(),
7498            input_text
7499                .chars()
7500                .filter(|initial_char| initial_char.is_whitespace())
7501                .count(),
7502            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
7503        );
7504
7505        for show_line_numbers in [true, false] {
7506            init_test(cx, |s| {
7507                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
7508                s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
7509            });
7510
7511            let actual_invisibles = collect_invisibles_from_new_editor(
7512                cx,
7513                EditorMode::Full,
7514                input_text,
7515                px(500.0),
7516                show_line_numbers,
7517            );
7518
7519            assert_eq!(expected_invisibles, actual_invisibles);
7520        }
7521    }
7522
7523    #[gpui::test]
7524    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
7525        init_test(cx, |s| {
7526            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
7527            s.defaults.tab_size = NonZeroU32::new(4);
7528        });
7529
7530        for editor_mode_without_invisibles in [
7531            EditorMode::SingleLine { auto_width: false },
7532            EditorMode::AutoHeight { max_lines: 100 },
7533        ] {
7534            for show_line_numbers in [true, false] {
7535                let invisibles = collect_invisibles_from_new_editor(
7536                    cx,
7537                    editor_mode_without_invisibles,
7538                    "\t\t\t| | a b",
7539                    px(500.0),
7540                    show_line_numbers,
7541                );
7542                assert!(invisibles.is_empty(),
7543                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
7544            }
7545        }
7546    }
7547
7548    #[gpui::test]
7549    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
7550        let tab_size = 4;
7551        let input_text = "a\tbcd     ".repeat(9);
7552        let repeated_invisibles = [
7553            Invisible::Tab {
7554                line_start_offset: 1,
7555                line_end_offset: tab_size as usize,
7556            },
7557            Invisible::Whitespace {
7558                line_offset: tab_size as usize + 3,
7559            },
7560            Invisible::Whitespace {
7561                line_offset: tab_size as usize + 4,
7562            },
7563            Invisible::Whitespace {
7564                line_offset: tab_size as usize + 5,
7565            },
7566            Invisible::Whitespace {
7567                line_offset: tab_size as usize + 6,
7568            },
7569            Invisible::Whitespace {
7570                line_offset: tab_size as usize + 7,
7571            },
7572        ];
7573        let expected_invisibles = std::iter::once(repeated_invisibles)
7574            .cycle()
7575            .take(9)
7576            .flatten()
7577            .collect::<Vec<_>>();
7578        assert_eq!(
7579            expected_invisibles.len(),
7580            input_text
7581                .chars()
7582                .filter(|initial_char| initial_char.is_whitespace())
7583                .count(),
7584            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
7585        );
7586        info!("Expected invisibles: {expected_invisibles:?}");
7587
7588        init_test(cx, |_| {});
7589
7590        // Put the same string with repeating whitespace pattern into editors of various size,
7591        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
7592        let resize_step = 10.0;
7593        let mut editor_width = 200.0;
7594        while editor_width <= 1000.0 {
7595            for show_line_numbers in [true, false] {
7596                update_test_language_settings(cx, |s| {
7597                    s.defaults.tab_size = NonZeroU32::new(tab_size);
7598                    s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
7599                    s.defaults.preferred_line_length = Some(editor_width as u32);
7600                    s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
7601                });
7602
7603                let actual_invisibles = collect_invisibles_from_new_editor(
7604                    cx,
7605                    EditorMode::Full,
7606                    &input_text,
7607                    px(editor_width),
7608                    show_line_numbers,
7609                );
7610
7611                // Whatever the editor size is, ensure it has the same invisible kinds in the same order
7612                // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
7613                let mut i = 0;
7614                for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
7615                    i = actual_index;
7616                    match expected_invisibles.get(i) {
7617                        Some(expected_invisible) => match (expected_invisible, actual_invisible) {
7618                            (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
7619                            | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
7620                            _ => {
7621                                panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
7622                            }
7623                        },
7624                        None => {
7625                            panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
7626                        }
7627                    }
7628                }
7629                let missing_expected_invisibles = &expected_invisibles[i + 1..];
7630                assert!(
7631                    missing_expected_invisibles.is_empty(),
7632                    "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
7633                );
7634
7635                editor_width += resize_step;
7636            }
7637        }
7638    }
7639
7640    fn collect_invisibles_from_new_editor(
7641        cx: &mut TestAppContext,
7642        editor_mode: EditorMode,
7643        input_text: &str,
7644        editor_width: Pixels,
7645        show_line_numbers: bool,
7646    ) -> Vec<Invisible> {
7647        info!(
7648            "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
7649            editor_width.0
7650        );
7651        let window = cx.add_window(|cx| {
7652            let buffer = MultiBuffer::build_simple(input_text, cx);
7653            Editor::new(editor_mode, buffer, None, true, cx)
7654        });
7655        let cx = &mut VisualTestContext::from_window(*window, cx);
7656        let editor = window.root(cx).unwrap();
7657
7658        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
7659        window
7660            .update(cx, |editor, cx| {
7661                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
7662                editor.set_wrap_width(Some(editor_width), cx);
7663                editor.set_show_line_numbers(show_line_numbers, cx);
7664            })
7665            .unwrap();
7666        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
7667            EditorElement::new(&editor, style)
7668        });
7669        state
7670            .position_map
7671            .line_layouts
7672            .iter()
7673            .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
7674            .cloned()
7675            .collect()
7676    }
7677}