element.rs

   1use crate::{
   2    display_map::{
   3        BlockContext, BlockStyle, DisplaySnapshot, FoldStatus, HighlightedChunk, ToDisplayPoint,
   4        TransformBlock,
   5    },
   6    editor_settings::{DoubleClickInMultibuffer, MultiCursorModifier, ShowScrollbar},
   7    git::{
   8        blame::{CommitDetails, GitBlame},
   9        diff_hunk_to_display, DisplayDiffHunk,
  10    },
  11    hover_popover::{
  12        self, hover_at, HOVER_POPOVER_GAP, MIN_POPOVER_CHARACTER_WIDTH, MIN_POPOVER_LINE_HEIGHT,
  13    },
  14    items::BufferSearchHighlights,
  15    mouse_context_menu::{self, MouseContextMenu},
  16    scroll::scroll_amount::ScrollAmount,
  17    CursorShape, DisplayPoint, DocumentHighlightRead, DocumentHighlightWrite, Editor, EditorMode,
  18    EditorSettings, EditorSnapshot, EditorStyle, GutterDimensions, HalfPageDown, HalfPageUp,
  19    HoveredCursor, LineDown, LineUp, OpenExcerpts, PageDown, PageUp, Point, SelectPhase, Selection,
  20    SoftWrap, ToPoint, CURSORS_VISIBLE_FOR, MAX_LINE_LEN,
  21};
  22use anyhow::Result;
  23use collections::{BTreeMap, HashMap};
  24use git::{blame::BlameEntry, diff::DiffHunkStatus, Oid};
  25use gpui::{
  26    anchored, deferred, div, fill, outline, point, px, quad, relative, size, svg,
  27    transparent_black, Action, AnchorCorner, AnyElement, AvailableSpace, Bounds, ClipboardItem,
  28    ContentMask, Corners, CursorStyle, DispatchPhase, Edges, Element, ElementContext,
  29    ElementInputHandler, Entity, Hitbox, Hsla, InteractiveElement, IntoElement,
  30    ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PaintQuad,
  31    ParentElement, Pixels, ScrollDelta, ScrollHandle, ScrollWheelEvent, ShapedLine, SharedString,
  32    Size, Stateful, StatefulInteractiveElement, Style, Styled, TextRun, TextStyle,
  33    TextStyleRefinement, View, ViewContext, WeakView, WindowContext,
  34};
  35use itertools::Itertools;
  36use language::language_settings::ShowWhitespaceSetting;
  37use lsp::DiagnosticSeverity;
  38use multi_buffer::Anchor;
  39use project::{
  40    project_settings::{GitGutterSetting, ProjectSettings},
  41    ProjectPath,
  42};
  43use settings::Settings;
  44use smallvec::SmallVec;
  45use std::{
  46    any::TypeId,
  47    borrow::Cow,
  48    cmp::{self, max, Ordering},
  49    fmt::Write,
  50    iter, mem,
  51    ops::Range,
  52    sync::Arc,
  53};
  54use sum_tree::Bias;
  55use theme::{ActiveTheme, PlayerColor, ThemeSettings};
  56use ui::{h_flex, ButtonLike, ButtonStyle, ContextMenu, Tooltip};
  57use ui::{prelude::*, tooltip_container};
  58use util::ResultExt;
  59use workspace::{item::Item, Workspace};
  60
  61struct SelectionLayout {
  62    head: DisplayPoint,
  63    cursor_shape: CursorShape,
  64    is_newest: bool,
  65    is_local: bool,
  66    range: Range<DisplayPoint>,
  67    active_rows: Range<u32>,
  68    user_name: Option<SharedString>,
  69}
  70
  71impl SelectionLayout {
  72    fn new<T: ToPoint + ToDisplayPoint + Clone>(
  73        selection: Selection<T>,
  74        line_mode: bool,
  75        cursor_shape: CursorShape,
  76        map: &DisplaySnapshot,
  77        is_newest: bool,
  78        is_local: bool,
  79        user_name: Option<SharedString>,
  80    ) -> Self {
  81        let point_selection = selection.map(|p| p.to_point(&map.buffer_snapshot));
  82        let display_selection = point_selection.map(|p| p.to_display_point(map));
  83        let mut range = display_selection.range();
  84        let mut head = display_selection.head();
  85        let mut active_rows = map.prev_line_boundary(point_selection.start).1.row()
  86            ..map.next_line_boundary(point_selection.end).1.row();
  87
  88        // vim visual line mode
  89        if line_mode {
  90            let point_range = map.expand_to_line(point_selection.range());
  91            range = point_range.start.to_display_point(map)..point_range.end.to_display_point(map);
  92        }
  93
  94        // any vim visual mode (including line mode)
  95        if cursor_shape == CursorShape::Block && !range.is_empty() && !selection.reversed {
  96            if head.column() > 0 {
  97                head = map.clip_point(DisplayPoint::new(head.row(), head.column() - 1), Bias::Left)
  98            } else if head.row() > 0 && head != map.max_point() {
  99                head = map.clip_point(
 100                    DisplayPoint::new(head.row() - 1, map.line_len(head.row() - 1)),
 101                    Bias::Left,
 102                );
 103                // updating range.end is a no-op unless you're cursor is
 104                // on the newline containing a multi-buffer divider
 105                // in which case the clip_point may have moved the head up
 106                // an additional row.
 107                range.end = DisplayPoint::new(head.row() + 1, 0);
 108                active_rows.end = head.row();
 109            }
 110        }
 111
 112        Self {
 113            head,
 114            cursor_shape,
 115            is_newest,
 116            is_local,
 117            range,
 118            active_rows,
 119            user_name,
 120        }
 121    }
 122}
 123
 124pub struct EditorElement {
 125    editor: View<Editor>,
 126    style: EditorStyle,
 127}
 128
 129impl EditorElement {
 130    pub fn new(editor: &View<Editor>, style: EditorStyle) -> Self {
 131        Self {
 132            editor: editor.clone(),
 133            style,
 134        }
 135    }
 136
 137    fn register_actions(&self, cx: &mut WindowContext) {
 138        let view = &self.editor;
 139        view.update(cx, |editor, cx| {
 140            for action in editor.editor_actions.iter() {
 141                (action)(cx)
 142            }
 143        });
 144
 145        crate::rust_analyzer_ext::apply_related_actions(view, cx);
 146        register_action(view, cx, Editor::move_left);
 147        register_action(view, cx, Editor::move_right);
 148        register_action(view, cx, Editor::move_down);
 149        register_action(view, cx, Editor::move_down_by_lines);
 150        register_action(view, cx, Editor::select_down_by_lines);
 151        register_action(view, cx, Editor::move_up);
 152        register_action(view, cx, Editor::move_up_by_lines);
 153        register_action(view, cx, Editor::select_up_by_lines);
 154        register_action(view, cx, Editor::cancel);
 155        register_action(view, cx, Editor::newline);
 156        register_action(view, cx, Editor::newline_above);
 157        register_action(view, cx, Editor::newline_below);
 158        register_action(view, cx, Editor::backspace);
 159        register_action(view, cx, Editor::delete);
 160        register_action(view, cx, Editor::tab);
 161        register_action(view, cx, Editor::tab_prev);
 162        register_action(view, cx, Editor::indent);
 163        register_action(view, cx, Editor::outdent);
 164        register_action(view, cx, Editor::delete_line);
 165        register_action(view, cx, Editor::join_lines);
 166        register_action(view, cx, Editor::sort_lines_case_sensitive);
 167        register_action(view, cx, Editor::sort_lines_case_insensitive);
 168        register_action(view, cx, Editor::reverse_lines);
 169        register_action(view, cx, Editor::shuffle_lines);
 170        register_action(view, cx, Editor::convert_to_upper_case);
 171        register_action(view, cx, Editor::convert_to_lower_case);
 172        register_action(view, cx, Editor::convert_to_title_case);
 173        register_action(view, cx, Editor::convert_to_snake_case);
 174        register_action(view, cx, Editor::convert_to_kebab_case);
 175        register_action(view, cx, Editor::convert_to_upper_camel_case);
 176        register_action(view, cx, Editor::convert_to_lower_camel_case);
 177        register_action(view, cx, Editor::delete_to_previous_word_start);
 178        register_action(view, cx, Editor::delete_to_previous_subword_start);
 179        register_action(view, cx, Editor::delete_to_next_word_end);
 180        register_action(view, cx, Editor::delete_to_next_subword_end);
 181        register_action(view, cx, Editor::delete_to_beginning_of_line);
 182        register_action(view, cx, Editor::delete_to_end_of_line);
 183        register_action(view, cx, Editor::cut_to_end_of_line);
 184        register_action(view, cx, Editor::duplicate_line_up);
 185        register_action(view, cx, Editor::duplicate_line_down);
 186        register_action(view, cx, Editor::move_line_up);
 187        register_action(view, cx, Editor::move_line_down);
 188        register_action(view, cx, Editor::transpose);
 189        register_action(view, cx, Editor::cut);
 190        register_action(view, cx, Editor::copy);
 191        register_action(view, cx, Editor::paste);
 192        register_action(view, cx, Editor::undo);
 193        register_action(view, cx, Editor::redo);
 194        register_action(view, cx, Editor::move_page_up);
 195        register_action(view, cx, Editor::move_page_down);
 196        register_action(view, cx, Editor::next_screen);
 197        register_action(view, cx, Editor::scroll_cursor_top);
 198        register_action(view, cx, Editor::scroll_cursor_center);
 199        register_action(view, cx, Editor::scroll_cursor_bottom);
 200        register_action(view, cx, |editor, _: &LineDown, cx| {
 201            editor.scroll_screen(&ScrollAmount::Line(1.), cx)
 202        });
 203        register_action(view, cx, |editor, _: &LineUp, cx| {
 204            editor.scroll_screen(&ScrollAmount::Line(-1.), cx)
 205        });
 206        register_action(view, cx, |editor, _: &HalfPageDown, cx| {
 207            editor.scroll_screen(&ScrollAmount::Page(0.5), cx)
 208        });
 209        register_action(view, cx, |editor, _: &HalfPageUp, cx| {
 210            editor.scroll_screen(&ScrollAmount::Page(-0.5), cx)
 211        });
 212        register_action(view, cx, |editor, _: &PageDown, cx| {
 213            editor.scroll_screen(&ScrollAmount::Page(1.), cx)
 214        });
 215        register_action(view, cx, |editor, _: &PageUp, cx| {
 216            editor.scroll_screen(&ScrollAmount::Page(-1.), cx)
 217        });
 218        register_action(view, cx, Editor::move_to_previous_word_start);
 219        register_action(view, cx, Editor::move_to_previous_subword_start);
 220        register_action(view, cx, Editor::move_to_next_word_end);
 221        register_action(view, cx, Editor::move_to_next_subword_end);
 222        register_action(view, cx, Editor::move_to_beginning_of_line);
 223        register_action(view, cx, Editor::move_to_end_of_line);
 224        register_action(view, cx, Editor::move_to_start_of_paragraph);
 225        register_action(view, cx, Editor::move_to_end_of_paragraph);
 226        register_action(view, cx, Editor::move_to_beginning);
 227        register_action(view, cx, Editor::move_to_end);
 228        register_action(view, cx, Editor::select_up);
 229        register_action(view, cx, Editor::select_down);
 230        register_action(view, cx, Editor::select_left);
 231        register_action(view, cx, Editor::select_right);
 232        register_action(view, cx, Editor::select_to_previous_word_start);
 233        register_action(view, cx, Editor::select_to_previous_subword_start);
 234        register_action(view, cx, Editor::select_to_next_word_end);
 235        register_action(view, cx, Editor::select_to_next_subword_end);
 236        register_action(view, cx, Editor::select_to_beginning_of_line);
 237        register_action(view, cx, Editor::select_to_end_of_line);
 238        register_action(view, cx, Editor::select_to_start_of_paragraph);
 239        register_action(view, cx, Editor::select_to_end_of_paragraph);
 240        register_action(view, cx, Editor::select_to_beginning);
 241        register_action(view, cx, Editor::select_to_end);
 242        register_action(view, cx, Editor::select_all);
 243        register_action(view, cx, |editor, action, cx| {
 244            editor.select_all_matches(action, cx).log_err();
 245        });
 246        register_action(view, cx, Editor::select_line);
 247        register_action(view, cx, Editor::split_selection_into_lines);
 248        register_action(view, cx, Editor::add_selection_above);
 249        register_action(view, cx, Editor::add_selection_below);
 250        register_action(view, cx, |editor, action, cx| {
 251            editor.select_next(action, cx).log_err();
 252        });
 253        register_action(view, cx, |editor, action, cx| {
 254            editor.select_previous(action, cx).log_err();
 255        });
 256        register_action(view, cx, Editor::toggle_comments);
 257        register_action(view, cx, Editor::select_larger_syntax_node);
 258        register_action(view, cx, Editor::select_smaller_syntax_node);
 259        register_action(view, cx, Editor::move_to_enclosing_bracket);
 260        register_action(view, cx, Editor::undo_selection);
 261        register_action(view, cx, Editor::redo_selection);
 262        register_action(view, cx, Editor::go_to_diagnostic);
 263        register_action(view, cx, Editor::go_to_prev_diagnostic);
 264        register_action(view, cx, Editor::go_to_hunk);
 265        register_action(view, cx, Editor::go_to_prev_hunk);
 266        register_action(view, cx, |editor, a, cx| {
 267            editor.go_to_definition(a, cx).detach_and_log_err(cx);
 268        });
 269        register_action(view, cx, |editor, a, cx| {
 270            editor.go_to_definition_split(a, cx).detach_and_log_err(cx);
 271        });
 272        register_action(view, cx, |editor, a, cx| {
 273            editor.go_to_implementation(a, cx).detach_and_log_err(cx);
 274        });
 275        register_action(view, cx, |editor, a, cx| {
 276            editor
 277                .go_to_implementation_split(a, cx)
 278                .detach_and_log_err(cx);
 279        });
 280        register_action(view, cx, |editor, a, cx| {
 281            editor.go_to_type_definition(a, cx).detach_and_log_err(cx);
 282        });
 283        register_action(view, cx, |editor, a, cx| {
 284            editor
 285                .go_to_type_definition_split(a, cx)
 286                .detach_and_log_err(cx);
 287        });
 288        register_action(view, cx, Editor::open_url);
 289        register_action(view, cx, Editor::fold);
 290        register_action(view, cx, Editor::fold_at);
 291        register_action(view, cx, Editor::unfold_lines);
 292        register_action(view, cx, Editor::unfold_at);
 293        register_action(view, cx, Editor::fold_selected_ranges);
 294        register_action(view, cx, Editor::show_completions);
 295        register_action(view, cx, Editor::toggle_code_actions);
 296        register_action(view, cx, Editor::open_excerpts);
 297        register_action(view, cx, Editor::open_excerpts_in_split);
 298        register_action(view, cx, Editor::toggle_soft_wrap);
 299        register_action(view, cx, Editor::toggle_line_numbers);
 300        register_action(view, cx, Editor::toggle_inlay_hints);
 301        register_action(view, cx, hover_popover::hover);
 302        register_action(view, cx, Editor::reveal_in_finder);
 303        register_action(view, cx, Editor::copy_path);
 304        register_action(view, cx, Editor::copy_relative_path);
 305        register_action(view, cx, Editor::copy_highlight_json);
 306        register_action(view, cx, Editor::copy_permalink_to_line);
 307        register_action(view, cx, Editor::open_permalink_to_line);
 308        register_action(view, cx, Editor::toggle_git_blame);
 309        register_action(view, cx, Editor::toggle_git_blame_inline);
 310        register_action(view, cx, |editor, action, cx| {
 311            if let Some(task) = editor.format(action, cx) {
 312                task.detach_and_log_err(cx);
 313            } else {
 314                cx.propagate();
 315            }
 316        });
 317        register_action(view, cx, Editor::restart_language_server);
 318        register_action(view, cx, Editor::show_character_palette);
 319        register_action(view, cx, |editor, action, cx| {
 320            if let Some(task) = editor.confirm_completion(action, cx) {
 321                task.detach_and_log_err(cx);
 322            } else {
 323                cx.propagate();
 324            }
 325        });
 326        register_action(view, cx, |editor, action, cx| {
 327            if let Some(task) = editor.confirm_code_action(action, cx) {
 328                task.detach_and_log_err(cx);
 329            } else {
 330                cx.propagate();
 331            }
 332        });
 333        register_action(view, cx, |editor, action, cx| {
 334            if let Some(task) = editor.rename(action, cx) {
 335                task.detach_and_log_err(cx);
 336            } else {
 337                cx.propagate();
 338            }
 339        });
 340        register_action(view, cx, |editor, action, cx| {
 341            if let Some(task) = editor.confirm_rename(action, cx) {
 342                task.detach_and_log_err(cx);
 343            } else {
 344                cx.propagate();
 345            }
 346        });
 347        register_action(view, cx, |editor, action, cx| {
 348            if let Some(task) = editor.find_all_references(action, cx) {
 349                task.detach_and_log_err(cx);
 350            } else {
 351                cx.propagate();
 352            }
 353        });
 354        register_action(view, cx, Editor::next_inline_completion);
 355        register_action(view, cx, Editor::previous_inline_completion);
 356        register_action(view, cx, Editor::show_inline_completion);
 357        register_action(view, cx, Editor::context_menu_first);
 358        register_action(view, cx, Editor::context_menu_prev);
 359        register_action(view, cx, Editor::context_menu_next);
 360        register_action(view, cx, Editor::context_menu_last);
 361        register_action(view, cx, Editor::display_cursor_names);
 362        register_action(view, cx, Editor::unique_lines_case_insensitive);
 363        register_action(view, cx, Editor::unique_lines_case_sensitive);
 364        register_action(view, cx, Editor::accept_partial_inline_completion);
 365        register_action(view, cx, Editor::revert_selected_hunks);
 366    }
 367
 368    fn register_key_listeners(&self, cx: &mut ElementContext, layout: &EditorLayout) {
 369        let position_map = layout.position_map.clone();
 370        cx.on_key_event({
 371            let editor = self.editor.clone();
 372            let text_hitbox = layout.text_hitbox.clone();
 373            move |event: &ModifiersChangedEvent, phase, cx| {
 374                if phase != DispatchPhase::Bubble {
 375                    return;
 376                }
 377
 378                editor.update(cx, |editor, cx| {
 379                    Self::modifiers_changed(editor, event, &position_map, &text_hitbox, cx)
 380                })
 381            }
 382        });
 383    }
 384
 385    fn modifiers_changed(
 386        editor: &mut Editor,
 387        event: &ModifiersChangedEvent,
 388        position_map: &PositionMap,
 389        text_hitbox: &Hitbox,
 390        cx: &mut ViewContext<Editor>,
 391    ) {
 392        let mouse_position = cx.mouse_position();
 393        if !text_hitbox.is_hovered(cx) {
 394            return;
 395        }
 396
 397        editor.update_hovered_link(
 398            position_map.point_for_position(text_hitbox.bounds, mouse_position),
 399            &position_map.snapshot,
 400            event.modifiers,
 401            cx,
 402        )
 403    }
 404
 405    fn mouse_left_down(
 406        editor: &mut Editor,
 407        event: &MouseDownEvent,
 408        position_map: &PositionMap,
 409        text_hitbox: &Hitbox,
 410        gutter_hitbox: &Hitbox,
 411        cx: &mut ViewContext<Editor>,
 412    ) {
 413        if cx.default_prevented() {
 414            return;
 415        }
 416
 417        let mut click_count = event.click_count;
 418        let mut modifiers = event.modifiers;
 419
 420        if gutter_hitbox.is_hovered(cx) {
 421            click_count = 3; // Simulate triple-click when clicking the gutter to select lines
 422        } else if !text_hitbox.is_hovered(cx) {
 423            return;
 424        }
 425
 426        if click_count == 2 && !editor.buffer().read(cx).is_singleton() {
 427            match EditorSettings::get_global(cx).double_click_in_multibuffer {
 428                DoubleClickInMultibuffer::Select => {
 429                    // do nothing special on double click, all selection logic is below
 430                }
 431                DoubleClickInMultibuffer::Open => {
 432                    if modifiers.alt {
 433                        // if double click is made with alt, pretend it's a regular double click without opening and alt,
 434                        // and run the selection logic.
 435                        modifiers.alt = false;
 436                    } else {
 437                        // if double click is made without alt, open the corresponding excerp
 438                        editor.open_excerpts(&OpenExcerpts, cx);
 439                        return;
 440                    }
 441                }
 442            }
 443        }
 444
 445        let point_for_position =
 446            position_map.point_for_position(text_hitbox.bounds, event.position);
 447        let position = point_for_position.previous_valid;
 448        if modifiers.shift && modifiers.alt {
 449            editor.select(
 450                SelectPhase::BeginColumnar {
 451                    position,
 452                    goal_column: point_for_position.exact_unclipped.column(),
 453                },
 454                cx,
 455            );
 456        } else if modifiers.shift && !modifiers.control && !modifiers.alt && !modifiers.secondary()
 457        {
 458            editor.select(
 459                SelectPhase::Extend {
 460                    position,
 461                    click_count,
 462                },
 463                cx,
 464            );
 465        } else {
 466            let multi_cursor_setting = EditorSettings::get_global(cx).multi_cursor_modifier;
 467            let multi_cursor_modifier = match multi_cursor_setting {
 468                MultiCursorModifier::Alt => modifiers.alt,
 469                MultiCursorModifier::CmdOrCtrl => modifiers.secondary(),
 470            };
 471            editor.select(
 472                SelectPhase::Begin {
 473                    position,
 474                    add: multi_cursor_modifier,
 475                    click_count,
 476                },
 477                cx,
 478            );
 479        }
 480
 481        cx.stop_propagation();
 482    }
 483
 484    fn mouse_right_down(
 485        editor: &mut Editor,
 486        event: &MouseDownEvent,
 487        position_map: &PositionMap,
 488        text_hitbox: &Hitbox,
 489        cx: &mut ViewContext<Editor>,
 490    ) {
 491        if !text_hitbox.is_hovered(cx) {
 492            return;
 493        }
 494        let point_for_position =
 495            position_map.point_for_position(text_hitbox.bounds, event.position);
 496        mouse_context_menu::deploy_context_menu(
 497            editor,
 498            event.position,
 499            point_for_position.previous_valid,
 500            cx,
 501        );
 502        cx.stop_propagation();
 503    }
 504
 505    fn mouse_up(
 506        editor: &mut Editor,
 507        event: &MouseUpEvent,
 508        position_map: &PositionMap,
 509        text_hitbox: &Hitbox,
 510        cx: &mut ViewContext<Editor>,
 511    ) {
 512        let end_selection = editor.has_pending_selection();
 513        let pending_nonempty_selections = editor.has_pending_nonempty_selection();
 514
 515        if end_selection {
 516            editor.select(SelectPhase::End, cx);
 517        }
 518
 519        let multi_cursor_setting = EditorSettings::get_global(cx).multi_cursor_modifier;
 520        let multi_cursor_modifier = match multi_cursor_setting {
 521            MultiCursorModifier::Alt => event.modifiers.secondary(),
 522            MultiCursorModifier::CmdOrCtrl => event.modifiers.alt,
 523        };
 524
 525        if !pending_nonempty_selections && multi_cursor_modifier && text_hitbox.is_hovered(cx) {
 526            let point = position_map.point_for_position(text_hitbox.bounds, event.position);
 527            editor.handle_click_hovered_link(point, event.modifiers, cx);
 528
 529            cx.stop_propagation();
 530        } else if end_selection {
 531            cx.stop_propagation();
 532        }
 533    }
 534
 535    fn mouse_dragged(
 536        editor: &mut Editor,
 537        event: &MouseMoveEvent,
 538        position_map: &PositionMap,
 539        text_bounds: Bounds<Pixels>,
 540        cx: &mut ViewContext<Editor>,
 541    ) {
 542        if !editor.has_pending_selection() {
 543            return;
 544        }
 545
 546        let point_for_position = position_map.point_for_position(text_bounds, event.position);
 547        let mut scroll_delta = gpui::Point::<f32>::default();
 548        let vertical_margin = position_map.line_height.min(text_bounds.size.height / 3.0);
 549        let top = text_bounds.origin.y + vertical_margin;
 550        let bottom = text_bounds.lower_left().y - vertical_margin;
 551        if event.position.y < top {
 552            scroll_delta.y = -scale_vertical_mouse_autoscroll_delta(top - event.position.y);
 553        }
 554        if event.position.y > bottom {
 555            scroll_delta.y = scale_vertical_mouse_autoscroll_delta(event.position.y - bottom);
 556        }
 557
 558        let horizontal_margin = position_map.line_height.min(text_bounds.size.width / 3.0);
 559        let left = text_bounds.origin.x + horizontal_margin;
 560        let right = text_bounds.upper_right().x - horizontal_margin;
 561        if event.position.x < left {
 562            scroll_delta.x = -scale_horizontal_mouse_autoscroll_delta(left - event.position.x);
 563        }
 564        if event.position.x > right {
 565            scroll_delta.x = scale_horizontal_mouse_autoscroll_delta(event.position.x - right);
 566        }
 567
 568        editor.select(
 569            SelectPhase::Update {
 570                position: point_for_position.previous_valid,
 571                goal_column: point_for_position.exact_unclipped.column(),
 572                scroll_delta,
 573            },
 574            cx,
 575        );
 576    }
 577
 578    fn mouse_moved(
 579        editor: &mut Editor,
 580        event: &MouseMoveEvent,
 581        position_map: &PositionMap,
 582        text_hitbox: &Hitbox,
 583        gutter_hitbox: &Hitbox,
 584        cx: &mut ViewContext<Editor>,
 585    ) {
 586        let modifiers = event.modifiers;
 587        let gutter_hovered = gutter_hitbox.is_hovered(cx);
 588        editor.set_gutter_hovered(gutter_hovered, cx);
 589
 590        // Don't trigger hover popover if mouse is hovering over context menu
 591        if text_hitbox.is_hovered(cx) {
 592            let point_for_position =
 593                position_map.point_for_position(text_hitbox.bounds, event.position);
 594
 595            editor.update_hovered_link(point_for_position, &position_map.snapshot, modifiers, cx);
 596
 597            if let Some(point) = point_for_position.as_valid() {
 598                hover_at(editor, Some(point), cx);
 599                Self::update_visible_cursor(editor, point, position_map, cx);
 600            } else {
 601                hover_at(editor, None, cx);
 602            }
 603        } else {
 604            editor.hide_hovered_link(cx);
 605            hover_at(editor, None, cx);
 606            if gutter_hovered {
 607                cx.stop_propagation();
 608            }
 609        }
 610    }
 611
 612    fn update_visible_cursor(
 613        editor: &mut Editor,
 614        point: DisplayPoint,
 615        position_map: &PositionMap,
 616        cx: &mut ViewContext<Editor>,
 617    ) {
 618        let snapshot = &position_map.snapshot;
 619        let Some(hub) = editor.collaboration_hub() else {
 620            return;
 621        };
 622        let range = DisplayPoint::new(point.row(), point.column().saturating_sub(1))
 623            ..DisplayPoint::new(
 624                point.row(),
 625                (point.column() + 1).min(snapshot.line_len(point.row())),
 626            );
 627
 628        let range = snapshot
 629            .buffer_snapshot
 630            .anchor_at(range.start.to_point(&snapshot.display_snapshot), Bias::Left)
 631            ..snapshot
 632                .buffer_snapshot
 633                .anchor_at(range.end.to_point(&snapshot.display_snapshot), Bias::Right);
 634
 635        let Some(selection) = snapshot.remote_selections_in_range(&range, hub, cx).next() else {
 636            return;
 637        };
 638        let key = crate::HoveredCursor {
 639            replica_id: selection.replica_id,
 640            selection_id: selection.selection.id,
 641        };
 642        editor.hovered_cursors.insert(
 643            key.clone(),
 644            cx.spawn(|editor, mut cx| async move {
 645                cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 646                editor
 647                    .update(&mut cx, |editor, cx| {
 648                        editor.hovered_cursors.remove(&key);
 649                        cx.notify();
 650                    })
 651                    .ok();
 652            }),
 653        );
 654        cx.notify()
 655    }
 656
 657    fn layout_selections(
 658        &self,
 659        start_anchor: Anchor,
 660        end_anchor: Anchor,
 661        snapshot: &EditorSnapshot,
 662        start_row: u32,
 663        end_row: u32,
 664        cx: &mut ElementContext,
 665    ) -> (
 666        Vec<(PlayerColor, Vec<SelectionLayout>)>,
 667        BTreeMap<u32, bool>,
 668        Option<DisplayPoint>,
 669    ) {
 670        let mut selections: Vec<(PlayerColor, Vec<SelectionLayout>)> = Vec::new();
 671        let mut active_rows = BTreeMap::new();
 672        let mut newest_selection_head = None;
 673        let editor = self.editor.read(cx);
 674
 675        if editor.show_local_selections {
 676            let mut local_selections: Vec<Selection<Point>> = editor
 677                .selections
 678                .disjoint_in_range(start_anchor..end_anchor, cx);
 679            local_selections.extend(editor.selections.pending(cx));
 680            let mut layouts = Vec::new();
 681            let newest = editor.selections.newest(cx);
 682            for selection in local_selections.drain(..) {
 683                let is_empty = selection.start == selection.end;
 684                let is_newest = selection == newest;
 685
 686                let layout = SelectionLayout::new(
 687                    selection,
 688                    editor.selections.line_mode,
 689                    editor.cursor_shape,
 690                    &snapshot.display_snapshot,
 691                    is_newest,
 692                    editor.leader_peer_id.is_none(),
 693                    None,
 694                );
 695                if is_newest {
 696                    newest_selection_head = Some(layout.head);
 697                }
 698
 699                for row in cmp::max(layout.active_rows.start, start_row)
 700                    ..=cmp::min(layout.active_rows.end, end_row)
 701                {
 702                    let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
 703                    *contains_non_empty_selection |= !is_empty;
 704                }
 705                layouts.push(layout);
 706            }
 707
 708            let player = if editor.read_only(cx) {
 709                cx.theme().players().read_only()
 710            } else {
 711                self.style.local_player
 712            };
 713
 714            selections.push((player, layouts));
 715        }
 716
 717        if let Some(collaboration_hub) = &editor.collaboration_hub {
 718            // When following someone, render the local selections in their color.
 719            if let Some(leader_id) = editor.leader_peer_id {
 720                if let Some(collaborator) = collaboration_hub.collaborators(cx).get(&leader_id) {
 721                    if let Some(participant_index) = collaboration_hub
 722                        .user_participant_indices(cx)
 723                        .get(&collaborator.user_id)
 724                    {
 725                        if let Some((local_selection_style, _)) = selections.first_mut() {
 726                            *local_selection_style = cx
 727                                .theme()
 728                                .players()
 729                                .color_for_participant(participant_index.0);
 730                        }
 731                    }
 732                }
 733            }
 734
 735            let mut remote_selections = HashMap::default();
 736            for selection in snapshot.remote_selections_in_range(
 737                &(start_anchor..end_anchor),
 738                collaboration_hub.as_ref(),
 739                cx,
 740            ) {
 741                let selection_style = if let Some(participant_index) = selection.participant_index {
 742                    cx.theme()
 743                        .players()
 744                        .color_for_participant(participant_index.0)
 745                } else {
 746                    cx.theme().players().absent()
 747                };
 748
 749                // Don't re-render the leader's selections, since the local selections
 750                // match theirs.
 751                if Some(selection.peer_id) == editor.leader_peer_id {
 752                    continue;
 753                }
 754                let key = HoveredCursor {
 755                    replica_id: selection.replica_id,
 756                    selection_id: selection.selection.id,
 757                };
 758
 759                let is_shown =
 760                    editor.show_cursor_names || editor.hovered_cursors.contains_key(&key);
 761
 762                remote_selections
 763                    .entry(selection.replica_id)
 764                    .or_insert((selection_style, Vec::new()))
 765                    .1
 766                    .push(SelectionLayout::new(
 767                        selection.selection,
 768                        selection.line_mode,
 769                        selection.cursor_shape,
 770                        &snapshot.display_snapshot,
 771                        false,
 772                        false,
 773                        if is_shown { selection.user_name } else { None },
 774                    ));
 775            }
 776
 777            selections.extend(remote_selections.into_values());
 778        }
 779        (selections, active_rows, newest_selection_head)
 780    }
 781
 782    #[allow(clippy::too_many_arguments)]
 783    fn layout_folds(
 784        &self,
 785        snapshot: &EditorSnapshot,
 786        content_origin: gpui::Point<Pixels>,
 787        visible_anchor_range: Range<Anchor>,
 788        visible_display_row_range: Range<u32>,
 789        scroll_pixel_position: gpui::Point<Pixels>,
 790        line_height: Pixels,
 791        line_layouts: &[LineWithInvisibles],
 792        cx: &mut ElementContext,
 793    ) -> Vec<FoldLayout> {
 794        snapshot
 795            .folds_in_range(visible_anchor_range.clone())
 796            .filter_map(|fold| {
 797                let fold_range = fold.range.clone();
 798                let display_range = fold.range.start.to_display_point(&snapshot)
 799                    ..fold.range.end.to_display_point(&snapshot);
 800                debug_assert_eq!(display_range.start.row(), display_range.end.row());
 801                let row = display_range.start.row();
 802                debug_assert!(row < visible_display_row_range.end);
 803                let line_layout = line_layouts
 804                    .get((row - visible_display_row_range.start) as usize)
 805                    .map(|l| &l.line)?;
 806
 807                let start_x = content_origin.x
 808                    + line_layout.x_for_index(display_range.start.column() as usize)
 809                    - scroll_pixel_position.x;
 810                let start_y = content_origin.y + row as f32 * line_height - scroll_pixel_position.y;
 811                let end_x = content_origin.x
 812                    + line_layout.x_for_index(display_range.end.column() as usize)
 813                    - scroll_pixel_position.x;
 814
 815                let fold_bounds = Bounds {
 816                    origin: point(start_x, start_y),
 817                    size: size(end_x - start_x, line_height),
 818                };
 819
 820                let mut hover_element = div()
 821                    .id(fold.id)
 822                    .size_full()
 823                    .cursor_pointer()
 824                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 825                    .on_click(
 826                        cx.listener_for(&self.editor, move |editor: &mut Editor, _, cx| {
 827                            editor.unfold_ranges(
 828                                [fold_range.start..fold_range.end],
 829                                true,
 830                                false,
 831                                cx,
 832                            );
 833                            cx.stop_propagation();
 834                        }),
 835                    )
 836                    .into_any();
 837                hover_element.layout(fold_bounds.origin, fold_bounds.size.into(), cx);
 838                Some(FoldLayout {
 839                    display_range,
 840                    hover_element,
 841                })
 842            })
 843            .collect()
 844    }
 845
 846    #[allow(clippy::too_many_arguments)]
 847    fn layout_cursors(
 848        &self,
 849        snapshot: &EditorSnapshot,
 850        selections: &[(PlayerColor, Vec<SelectionLayout>)],
 851        visible_display_row_range: Range<u32>,
 852        line_layouts: &[LineWithInvisibles],
 853        text_hitbox: &Hitbox,
 854        content_origin: gpui::Point<Pixels>,
 855        scroll_pixel_position: gpui::Point<Pixels>,
 856        line_height: Pixels,
 857        em_width: Pixels,
 858        cx: &mut ElementContext,
 859    ) -> Vec<CursorLayout> {
 860        self.editor.update(cx, |editor, cx| {
 861            let mut cursors = Vec::new();
 862            for (player_color, selections) in selections {
 863                for selection in selections {
 864                    let cursor_position = selection.head;
 865                    if (selection.is_local && !editor.show_local_cursors(cx))
 866                        || !visible_display_row_range.contains(&cursor_position.row())
 867                    {
 868                        continue;
 869                    }
 870
 871                    let cursor_row_layout = &line_layouts
 872                        [(cursor_position.row() - visible_display_row_range.start) as usize]
 873                        .line;
 874                    let cursor_column = cursor_position.column() as usize;
 875
 876                    let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 877                    let mut block_width =
 878                        cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
 879                    if block_width == Pixels::ZERO {
 880                        block_width = em_width;
 881                    }
 882                    let block_text = if let CursorShape::Block = selection.cursor_shape {
 883                        snapshot.display_chars_at(cursor_position).next().and_then(
 884                            |(character, _)| {
 885                                let text = if character == '\n' {
 886                                    SharedString::from(" ")
 887                                } else {
 888                                    SharedString::from(character.to_string())
 889                                };
 890                                let len = text.len();
 891
 892                                let font = cursor_row_layout
 893                                    .font_id_for_index(cursor_column)
 894                                    .and_then(|cursor_font_id| {
 895                                        cx.text_system().get_font_for_id(cursor_font_id)
 896                                    })
 897                                    .unwrap_or(self.style.text.font());
 898
 899                                cx.text_system()
 900                                    .shape_line(
 901                                        text,
 902                                        cursor_row_layout.font_size,
 903                                        &[TextRun {
 904                                            len,
 905                                            font: font,
 906                                            color: self.style.background,
 907                                            background_color: None,
 908                                            strikethrough: None,
 909                                            underline: None,
 910                                        }],
 911                                    )
 912                                    .log_err()
 913                            },
 914                        )
 915                    } else {
 916                        None
 917                    };
 918
 919                    let x = cursor_character_x - scroll_pixel_position.x;
 920                    let y = (cursor_position.row() as f32 - scroll_pixel_position.y / line_height)
 921                        * line_height;
 922                    if selection.is_newest {
 923                        editor.pixel_position_of_newest_cursor = Some(point(
 924                            text_hitbox.origin.x + x + block_width / 2.,
 925                            text_hitbox.origin.y + y + line_height / 2.,
 926                        ))
 927                    }
 928
 929                    let mut cursor = CursorLayout {
 930                        color: player_color.cursor,
 931                        block_width,
 932                        origin: point(x, y),
 933                        line_height,
 934                        shape: selection.cursor_shape,
 935                        block_text,
 936                        cursor_name: None,
 937                    };
 938                    let cursor_name = selection.user_name.clone().map(|name| CursorName {
 939                        string: name,
 940                        color: self.style.background,
 941                        is_top_row: cursor_position.row() == 0,
 942                    });
 943                    cx.with_element_context(|cx| cursor.layout(content_origin, cursor_name, cx));
 944                    cursors.push(cursor);
 945                }
 946            }
 947            cursors
 948        })
 949    }
 950
 951    fn layout_scrollbar(
 952        &self,
 953        snapshot: &EditorSnapshot,
 954        bounds: Bounds<Pixels>,
 955        scroll_position: gpui::Point<f32>,
 956        line_height: Pixels,
 957        height_in_lines: f32,
 958        cx: &mut ElementContext,
 959    ) -> Option<ScrollbarLayout> {
 960        let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
 961        let show_scrollbars = match scrollbar_settings.show {
 962            ShowScrollbar::Auto => {
 963                let editor = self.editor.read(cx);
 964                let is_singleton = editor.is_singleton(cx);
 965                // Git
 966                (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_git_diffs())
 967                    ||
 968                    // Buffer Search Results
 969                    (is_singleton && scrollbar_settings.search_results && editor.has_background_highlights::<BufferSearchHighlights>())
 970                    ||
 971                    // Selected Symbol Occurrences
 972                    (is_singleton && scrollbar_settings.selected_symbol && (editor.has_background_highlights::<DocumentHighlightRead>() || editor.has_background_highlights::<DocumentHighlightWrite>()))
 973                    ||
 974                    // Diagnostics
 975                    (is_singleton && scrollbar_settings.diagnostics && snapshot.buffer_snapshot.has_diagnostics())
 976                    ||
 977                    // Scrollmanager
 978                    editor.scroll_manager.scrollbars_visible()
 979            }
 980            ShowScrollbar::System => self.editor.read(cx).scroll_manager.scrollbars_visible(),
 981            ShowScrollbar::Always => true,
 982            ShowScrollbar::Never => false,
 983        };
 984        if snapshot.mode != EditorMode::Full {
 985            return None;
 986        }
 987
 988        let visible_row_range = scroll_position.y..scroll_position.y + height_in_lines;
 989
 990        // If a drag took place after we started dragging the scrollbar,
 991        // cancel the scrollbar drag.
 992        if cx.has_active_drag() {
 993            self.editor.update(cx, |editor, cx| {
 994                editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
 995            });
 996        }
 997
 998        let track_bounds = Bounds::from_corners(
 999            point(self.scrollbar_left(&bounds), bounds.origin.y),
1000            point(bounds.lower_right().x, bounds.lower_left().y),
1001        );
1002
1003        let scroll_height = snapshot.max_point().row() as f32 + height_in_lines;
1004        let mut height = bounds.size.height;
1005        let mut first_row_y_offset = px(0.0);
1006
1007        // Impose a minimum height on the scrollbar thumb
1008        let row_height = height / scroll_height;
1009        let min_thumb_height = line_height;
1010        let thumb_height = height_in_lines * row_height;
1011        if thumb_height < min_thumb_height {
1012            first_row_y_offset = (min_thumb_height - thumb_height) / 2.0;
1013            height -= min_thumb_height - thumb_height;
1014        }
1015
1016        Some(ScrollbarLayout {
1017            hitbox: cx.insert_hitbox(track_bounds, false),
1018            visible_row_range,
1019            height,
1020            scroll_height,
1021            first_row_y_offset,
1022            row_height,
1023            visible: show_scrollbars,
1024        })
1025    }
1026
1027    #[allow(clippy::too_many_arguments)]
1028    fn layout_gutter_fold_indicators(
1029        &self,
1030        fold_statuses: Vec<Option<(FoldStatus, u32, bool)>>,
1031        line_height: Pixels,
1032        gutter_dimensions: &GutterDimensions,
1033        gutter_settings: crate::editor_settings::Gutter,
1034        scroll_pixel_position: gpui::Point<Pixels>,
1035        gutter_hitbox: &Hitbox,
1036        cx: &mut ElementContext,
1037    ) -> Vec<Option<AnyElement>> {
1038        let mut indicators = self.editor.update(cx, |editor, cx| {
1039            editor.render_fold_indicators(
1040                fold_statuses,
1041                &self.style,
1042                editor.gutter_hovered,
1043                line_height,
1044                gutter_dimensions.margin,
1045                cx,
1046            )
1047        });
1048
1049        for (ix, fold_indicator) in indicators.iter_mut().enumerate() {
1050            if let Some(fold_indicator) = fold_indicator {
1051                debug_assert!(gutter_settings.folds);
1052                let available_space = size(
1053                    AvailableSpace::MinContent,
1054                    AvailableSpace::Definite(line_height * 0.55),
1055                );
1056                let fold_indicator_size = fold_indicator.measure(available_space, cx);
1057
1058                let position = point(
1059                    gutter_dimensions.width - gutter_dimensions.right_padding,
1060                    ix as f32 * line_height - (scroll_pixel_position.y % line_height),
1061                );
1062                let centering_offset = point(
1063                    (gutter_dimensions.right_padding + gutter_dimensions.margin
1064                        - fold_indicator_size.width)
1065                        / 2.,
1066                    (line_height - fold_indicator_size.height) / 2.,
1067                );
1068                let origin = gutter_hitbox.origin + position + centering_offset;
1069                fold_indicator.layout(origin, available_space, cx);
1070            }
1071        }
1072
1073        indicators
1074    }
1075
1076    //Folds contained in a hunk are ignored apart from shrinking visual size
1077    //If a fold contains any hunks then that fold line is marked as modified
1078    fn layout_git_gutters(
1079        &self,
1080        display_rows: Range<u32>,
1081        snapshot: &EditorSnapshot,
1082    ) -> Vec<DisplayDiffHunk> {
1083        let buffer_snapshot = &snapshot.buffer_snapshot;
1084
1085        let buffer_start_row = DisplayPoint::new(display_rows.start, 0)
1086            .to_point(snapshot)
1087            .row;
1088        let buffer_end_row = DisplayPoint::new(display_rows.end, 0)
1089            .to_point(snapshot)
1090            .row;
1091
1092        buffer_snapshot
1093            .git_diff_hunks_in_range(buffer_start_row..buffer_end_row)
1094            .map(|hunk| diff_hunk_to_display(hunk, snapshot))
1095            .dedup()
1096            .collect()
1097    }
1098
1099    #[allow(clippy::too_many_arguments)]
1100    fn layout_inline_blame(
1101        &self,
1102        display_row: u32,
1103        display_snapshot: &DisplaySnapshot,
1104        line_layout: &LineWithInvisibles,
1105        em_width: Pixels,
1106        content_origin: gpui::Point<Pixels>,
1107        scroll_pixel_position: gpui::Point<Pixels>,
1108        line_height: Pixels,
1109        cx: &mut ElementContext,
1110    ) -> Option<AnyElement> {
1111        if !self
1112            .editor
1113            .update(cx, |editor, cx| editor.render_git_blame_inline(cx))
1114        {
1115            return None;
1116        }
1117
1118        let workspace = self
1119            .editor
1120            .read(cx)
1121            .workspace
1122            .as_ref()
1123            .map(|(w, _)| w.clone());
1124
1125        let display_point = DisplayPoint::new(display_row, 0);
1126        let buffer_row = display_point.to_point(display_snapshot).row;
1127
1128        let blame = self.editor.read(cx).blame.clone()?;
1129        let blame_entry = blame
1130            .update(cx, |blame, cx| {
1131                blame.blame_for_rows([Some(buffer_row)], cx).next()
1132            })
1133            .flatten()?;
1134
1135        let mut element =
1136            render_inline_blame_entry(&blame, blame_entry, &self.style, workspace, cx);
1137
1138        let start_y = content_origin.y
1139            + line_height * (display_row as f32 - scroll_pixel_position.y / line_height);
1140
1141        let start_x = {
1142            const INLINE_BLAME_PADDING_EM_WIDTHS: f32 = 6.;
1143
1144            let padded_line_width =
1145                line_layout.line.width + (em_width * INLINE_BLAME_PADDING_EM_WIDTHS);
1146
1147            let min_column = ProjectSettings::get_global(cx)
1148                .git
1149                .inline_blame
1150                .and_then(|settings| settings.min_column)
1151                .map(|col| self.column_pixels(col as usize, cx))
1152                .unwrap_or(px(0.));
1153
1154            content_origin.x + max(padded_line_width, min_column)
1155        };
1156
1157        let absolute_offset = point(start_x, start_y);
1158        let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1159
1160        element.layout(absolute_offset, available_space, cx);
1161
1162        Some(element)
1163    }
1164
1165    #[allow(clippy::too_many_arguments)]
1166    fn layout_blame_entries(
1167        &self,
1168        buffer_rows: impl Iterator<Item = Option<u32>>,
1169        em_width: Pixels,
1170        scroll_position: gpui::Point<f32>,
1171        line_height: Pixels,
1172        gutter_hitbox: &Hitbox,
1173        max_width: Option<Pixels>,
1174        cx: &mut ElementContext,
1175    ) -> Option<Vec<AnyElement>> {
1176        if !self
1177            .editor
1178            .update(cx, |editor, cx| editor.render_git_blame_gutter(cx))
1179        {
1180            return None;
1181        }
1182
1183        let blame = self.editor.read(cx).blame.clone()?;
1184        let blamed_rows: Vec<_> = blame.update(cx, |blame, cx| {
1185            blame.blame_for_rows(buffer_rows, cx).collect()
1186        });
1187
1188        let width = if let Some(max_width) = max_width {
1189            AvailableSpace::Definite(max_width)
1190        } else {
1191            AvailableSpace::MaxContent
1192        };
1193        let scroll_top = scroll_position.y * line_height;
1194        let start_x = em_width * 1;
1195
1196        let mut last_used_color: Option<(PlayerColor, Oid)> = None;
1197
1198        let shaped_lines = blamed_rows
1199            .into_iter()
1200            .enumerate()
1201            .flat_map(|(ix, blame_entry)| {
1202                if let Some(blame_entry) = blame_entry {
1203                    let mut element = render_blame_entry(
1204                        ix,
1205                        &blame,
1206                        blame_entry,
1207                        &self.style,
1208                        &mut last_used_color,
1209                        self.editor.clone(),
1210                        cx,
1211                    );
1212
1213                    let start_y = ix as f32 * line_height - (scroll_top % line_height);
1214                    let absolute_offset = gutter_hitbox.origin + point(start_x, start_y);
1215
1216                    element.layout(absolute_offset, size(width, AvailableSpace::MinContent), cx);
1217
1218                    Some(element)
1219                } else {
1220                    None
1221                }
1222            })
1223            .collect();
1224
1225        Some(shaped_lines)
1226    }
1227
1228    fn layout_code_actions_indicator(
1229        &self,
1230        line_height: Pixels,
1231        newest_selection_head: DisplayPoint,
1232        scroll_pixel_position: gpui::Point<Pixels>,
1233        gutter_dimensions: &GutterDimensions,
1234        gutter_hitbox: &Hitbox,
1235        cx: &mut ElementContext,
1236    ) -> Option<AnyElement> {
1237        let mut active = false;
1238        let mut button = None;
1239        self.editor.update(cx, |editor, cx| {
1240            active = matches!(
1241                editor.context_menu.read().as_ref(),
1242                Some(crate::ContextMenu::CodeActions(_))
1243            );
1244            button = editor.render_code_actions_indicator(&self.style, active, cx);
1245        });
1246
1247        let mut button = button?.into_any_element();
1248        let available_space = size(
1249            AvailableSpace::MinContent,
1250            AvailableSpace::Definite(line_height),
1251        );
1252        let indicator_size = button.measure(available_space, cx);
1253
1254        let blame_width = gutter_dimensions
1255            .git_blame_entries_width
1256            .unwrap_or(Pixels::ZERO);
1257
1258        let mut x = blame_width;
1259        let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
1260            - indicator_size.width
1261            - blame_width;
1262        x += available_width / 2.;
1263
1264        let mut y = newest_selection_head.row() as f32 * line_height - scroll_pixel_position.y;
1265        y += (line_height - indicator_size.height) / 2.;
1266
1267        button.layout(gutter_hitbox.origin + point(x, y), available_space, cx);
1268        Some(button)
1269    }
1270
1271    fn calculate_relative_line_numbers(
1272        &self,
1273        buffer_rows: Vec<Option<u32>>,
1274        rows: &Range<u32>,
1275        relative_to: Option<u32>,
1276    ) -> HashMap<u32, u32> {
1277        let mut relative_rows: HashMap<u32, u32> = Default::default();
1278        let Some(relative_to) = relative_to else {
1279            return relative_rows;
1280        };
1281
1282        let start = rows.start.min(relative_to);
1283
1284        let head_idx = relative_to - start;
1285        let mut delta = 1;
1286        let mut i = head_idx + 1;
1287        while i < buffer_rows.len() as u32 {
1288            if buffer_rows[i as usize].is_some() {
1289                if rows.contains(&(i + start)) {
1290                    relative_rows.insert(i + start, delta);
1291                }
1292                delta += 1;
1293            }
1294            i += 1;
1295        }
1296        delta = 1;
1297        i = head_idx.min(buffer_rows.len() as u32 - 1);
1298        while i > 0 && buffer_rows[i as usize].is_none() {
1299            i -= 1;
1300        }
1301
1302        while i > 0 {
1303            i -= 1;
1304            if buffer_rows[i as usize].is_some() {
1305                if rows.contains(&(i + start)) {
1306                    relative_rows.insert(i + start, delta);
1307                }
1308                delta += 1;
1309            }
1310        }
1311
1312        relative_rows
1313    }
1314
1315    fn layout_line_numbers(
1316        &self,
1317        rows: Range<u32>,
1318        buffer_rows: impl Iterator<Item = Option<u32>>,
1319        active_rows: &BTreeMap<u32, bool>,
1320        newest_selection_head: Option<DisplayPoint>,
1321        snapshot: &EditorSnapshot,
1322        cx: &ElementContext,
1323    ) -> (
1324        Vec<Option<ShapedLine>>,
1325        Vec<Option<(FoldStatus, BufferRow, bool)>>,
1326    ) {
1327        let editor = self.editor.read(cx);
1328        let is_singleton = editor.is_singleton(cx);
1329        let newest_selection_head = newest_selection_head.unwrap_or_else(|| {
1330            let newest = editor.selections.newest::<Point>(cx);
1331            SelectionLayout::new(
1332                newest,
1333                editor.selections.line_mode,
1334                editor.cursor_shape,
1335                &snapshot.display_snapshot,
1336                true,
1337                true,
1338                None,
1339            )
1340            .head
1341        });
1342        let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1343        let include_line_numbers =
1344            EditorSettings::get_global(cx).gutter.line_numbers && snapshot.mode == EditorMode::Full;
1345        let include_fold_statuses =
1346            EditorSettings::get_global(cx).gutter.folds && snapshot.mode == EditorMode::Full;
1347        let mut shaped_line_numbers = Vec::with_capacity(rows.len());
1348        let mut fold_statuses = Vec::with_capacity(rows.len());
1349        let mut line_number = String::new();
1350        let is_relative = EditorSettings::get_global(cx).relative_line_numbers;
1351        let relative_to = if is_relative {
1352            Some(newest_selection_head.row())
1353        } else {
1354            None
1355        };
1356
1357        let buffer_rows = buffer_rows.collect::<Vec<_>>();
1358        let relative_rows =
1359            self.calculate_relative_line_numbers(buffer_rows.clone(), &rows, relative_to);
1360
1361        for (ix, row) in buffer_rows.into_iter().enumerate() {
1362            let display_row = rows.start + ix as u32;
1363            let (active, color) = if active_rows.contains_key(&display_row) {
1364                (true, cx.theme().colors().editor_active_line_number)
1365            } else {
1366                (false, cx.theme().colors().editor_line_number)
1367            };
1368            if let Some(buffer_row) = row {
1369                if include_line_numbers {
1370                    line_number.clear();
1371                    let default_number = buffer_row + 1;
1372                    let number = relative_rows
1373                        .get(&(ix as u32 + rows.start))
1374                        .unwrap_or(&default_number);
1375                    write!(&mut line_number, "{}", number).unwrap();
1376                    let run = TextRun {
1377                        len: line_number.len(),
1378                        font: self.style.text.font(),
1379                        color,
1380                        background_color: None,
1381                        underline: None,
1382                        strikethrough: None,
1383                    };
1384                    let shaped_line = cx
1385                        .text_system()
1386                        .shape_line(line_number.clone().into(), font_size, &[run])
1387                        .unwrap();
1388                    shaped_line_numbers.push(Some(shaped_line));
1389                }
1390                if include_fold_statuses {
1391                    fold_statuses.push(
1392                        is_singleton
1393                            .then(|| {
1394                                snapshot
1395                                    .fold_for_line(buffer_row)
1396                                    .map(|fold_status| (fold_status, buffer_row, active))
1397                            })
1398                            .flatten(),
1399                    )
1400                }
1401            } else {
1402                fold_statuses.push(None);
1403                shaped_line_numbers.push(None);
1404            }
1405        }
1406
1407        (shaped_line_numbers, fold_statuses)
1408    }
1409
1410    fn layout_lines(
1411        &self,
1412        rows: Range<u32>,
1413        line_number_layouts: &[Option<ShapedLine>],
1414        snapshot: &EditorSnapshot,
1415        cx: &ElementContext,
1416    ) -> Vec<LineWithInvisibles> {
1417        if rows.start >= rows.end {
1418            return Vec::new();
1419        }
1420
1421        // Show the placeholder when the editor is empty
1422        if snapshot.is_empty() {
1423            let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1424            let placeholder_color = cx.theme().colors().text_placeholder;
1425            let placeholder_text = snapshot.placeholder_text();
1426
1427            let placeholder_lines = placeholder_text
1428                .as_ref()
1429                .map_or("", AsRef::as_ref)
1430                .split('\n')
1431                .skip(rows.start as usize)
1432                .chain(iter::repeat(""))
1433                .take(rows.len());
1434            placeholder_lines
1435                .filter_map(move |line| {
1436                    let run = TextRun {
1437                        len: line.len(),
1438                        font: self.style.text.font(),
1439                        color: placeholder_color,
1440                        background_color: None,
1441                        underline: Default::default(),
1442                        strikethrough: None,
1443                    };
1444                    cx.text_system()
1445                        .shape_line(line.to_string().into(), font_size, &[run])
1446                        .log_err()
1447                })
1448                .map(|line| LineWithInvisibles {
1449                    line,
1450                    invisibles: Vec::new(),
1451                })
1452                .collect()
1453        } else {
1454            let chunks = snapshot.highlighted_chunks(rows.clone(), true, &self.style);
1455            LineWithInvisibles::from_chunks(
1456                chunks,
1457                &self.style.text,
1458                MAX_LINE_LEN,
1459                rows.len(),
1460                line_number_layouts,
1461                snapshot.mode,
1462                cx,
1463            )
1464        }
1465    }
1466
1467    #[allow(clippy::too_many_arguments)]
1468    fn build_blocks(
1469        &self,
1470        rows: Range<u32>,
1471        snapshot: &EditorSnapshot,
1472        hitbox: &Hitbox,
1473        text_hitbox: &Hitbox,
1474        scroll_width: &mut Pixels,
1475        gutter_dimensions: &GutterDimensions,
1476        em_width: Pixels,
1477        text_x: Pixels,
1478        line_height: Pixels,
1479        line_layouts: &[LineWithInvisibles],
1480        cx: &mut ElementContext,
1481    ) -> Vec<BlockLayout> {
1482        let mut block_id = 0;
1483        let (fixed_blocks, non_fixed_blocks) = snapshot
1484            .blocks_in_range(rows.clone())
1485            .partition::<Vec<_>, _>(|(_, block)| match block {
1486                TransformBlock::ExcerptHeader { .. } => false,
1487                TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
1488            });
1489
1490        let render_block = |block: &TransformBlock,
1491                            available_space: Size<AvailableSpace>,
1492                            block_id: usize,
1493                            block_row_start: u32,
1494                            cx: &mut ElementContext| {
1495            let mut element = match block {
1496                TransformBlock::Custom(block) => {
1497                    let align_to = block
1498                        .position()
1499                        .to_point(&snapshot.buffer_snapshot)
1500                        .to_display_point(snapshot);
1501                    let anchor_x = text_x
1502                        + if rows.contains(&align_to.row()) {
1503                            line_layouts[(align_to.row() - rows.start) as usize]
1504                                .line
1505                                .x_for_index(align_to.column() as usize)
1506                        } else {
1507                            layout_line(align_to.row(), snapshot, &self.style, cx)
1508                                .unwrap()
1509                                .x_for_index(align_to.column() as usize)
1510                        };
1511
1512                    block.render(&mut BlockContext {
1513                        context: cx,
1514                        anchor_x,
1515                        gutter_dimensions,
1516                        line_height,
1517                        em_width,
1518                        block_id,
1519                        max_width: text_hitbox.size.width.max(*scroll_width),
1520                        editor_style: &self.style,
1521                    })
1522                }
1523
1524                TransformBlock::ExcerptHeader {
1525                    buffer,
1526                    range,
1527                    starts_new_buffer,
1528                    height,
1529                    ..
1530                } => {
1531                    let include_root = self
1532                        .editor
1533                        .read(cx)
1534                        .project
1535                        .as_ref()
1536                        .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
1537                        .unwrap_or_default();
1538
1539                    #[derive(Clone)]
1540                    struct JumpData {
1541                        position: Point,
1542                        anchor: text::Anchor,
1543                        path: ProjectPath,
1544                        line_offset_from_top: u32,
1545                    }
1546
1547                    let jump_data = project::File::from_dyn(buffer.file()).map(|file| {
1548                        let jump_path = ProjectPath {
1549                            worktree_id: file.worktree_id(cx),
1550                            path: file.path.clone(),
1551                        };
1552                        let jump_anchor = range
1553                            .primary
1554                            .as_ref()
1555                            .map_or(range.context.start, |primary| primary.start);
1556
1557                        let excerpt_start = range.context.start;
1558                        let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
1559                        let offset_from_excerpt_start = if jump_anchor == excerpt_start {
1560                            0
1561                        } else {
1562                            let excerpt_start_row =
1563                                language::ToPoint::to_point(&jump_anchor, buffer).row;
1564                            jump_position.row - excerpt_start_row
1565                        };
1566
1567                        let line_offset_from_top =
1568                            block_row_start + *height as u32 + offset_from_excerpt_start
1569                                - snapshot
1570                                    .scroll_anchor
1571                                    .scroll_position(&snapshot.display_snapshot)
1572                                    .y as u32;
1573
1574                        JumpData {
1575                            position: jump_position,
1576                            anchor: jump_anchor,
1577                            path: jump_path,
1578                            line_offset_from_top,
1579                        }
1580                    });
1581
1582                    let element = if *starts_new_buffer {
1583                        let path = buffer.resolve_file_path(cx, include_root);
1584                        let mut filename = None;
1585                        let mut parent_path = None;
1586                        // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
1587                        if let Some(path) = path {
1588                            filename = path.file_name().map(|f| f.to_string_lossy().to_string());
1589                            parent_path = path
1590                                .parent()
1591                                .map(|p| SharedString::from(p.to_string_lossy().to_string() + "/"));
1592                        }
1593
1594                        v_flex()
1595                            .id(("path header container", block_id))
1596                            .size_full()
1597                            .justify_center()
1598                            .p(gpui::px(6.))
1599                            .child(
1600                                h_flex()
1601                                    .id("path header block")
1602                                    .size_full()
1603                                    .pl(gpui::px(12.))
1604                                    .pr(gpui::px(8.))
1605                                    .rounded_md()
1606                                    .shadow_md()
1607                                    .border()
1608                                    .border_color(cx.theme().colors().border)
1609                                    .bg(cx.theme().colors().editor_subheader_background)
1610                                    .justify_between()
1611                                    .hover(|style| style.bg(cx.theme().colors().element_hover))
1612                                    .child(
1613                                        h_flex().gap_3().child(
1614                                            h_flex()
1615                                                .gap_2()
1616                                                .child(
1617                                                    filename
1618                                                        .map(SharedString::from)
1619                                                        .unwrap_or_else(|| "untitled".into()),
1620                                                )
1621                                                .when_some(parent_path, |then, path| {
1622                                                    then.child(
1623                                                        div().child(path).text_color(
1624                                                            cx.theme().colors().text_muted,
1625                                                        ),
1626                                                    )
1627                                                }),
1628                                        ),
1629                                    )
1630                                    .when_some(jump_data.clone(), |this, jump_data| {
1631                                        this.cursor_pointer()
1632                                            .tooltip(|cx| {
1633                                                Tooltip::for_action(
1634                                                    "Jump to File",
1635                                                    &OpenExcerpts,
1636                                                    cx,
1637                                                )
1638                                            })
1639                                            .on_mouse_down(MouseButton::Left, |_, cx| {
1640                                                cx.stop_propagation()
1641                                            })
1642                                            .on_click(cx.listener_for(&self.editor, {
1643                                                move |editor, _, cx| {
1644                                                    editor.jump(
1645                                                        jump_data.path.clone(),
1646                                                        jump_data.position,
1647                                                        jump_data.anchor,
1648                                                        jump_data.line_offset_from_top,
1649                                                        cx,
1650                                                    );
1651                                                }
1652                                            }))
1653                                    }),
1654                            )
1655                    } else {
1656                        v_flex()
1657                            .id(("collapsed context", block_id))
1658                            .size_full()
1659                            .child(
1660                                div()
1661                                    .flex()
1662                                    .v_flex()
1663                                    .justify_start()
1664                                    .id("jump to collapsed context")
1665                                    .w(relative(1.0))
1666                                    .h_full()
1667                                    .child(
1668                                        div()
1669                                            .h_px()
1670                                            .w_full()
1671                                            .bg(cx.theme().colors().border_variant)
1672                                            .group_hover("excerpt-jump-action", |style| {
1673                                                style.bg(cx.theme().colors().border)
1674                                            }),
1675                                    ),
1676                            )
1677                            .child(
1678                                h_flex()
1679                                    .justify_end()
1680                                    .flex_none()
1681                                    .w(
1682                                        gutter_dimensions.width - (gutter_dimensions.left_padding), // + gutter_dimensions.right_padding)
1683                                    )
1684                                    .h_full()
1685                                    .child(
1686                                        ButtonLike::new("jump-icon")
1687                                            .style(ButtonStyle::Transparent)
1688                                            .child(
1689                                                svg()
1690                                                    .path(IconName::ArrowUpRight.path())
1691                                                    .size(IconSize::XSmall.rems())
1692                                                    .text_color(cx.theme().colors().border)
1693                                                    .group_hover("excerpt-jump-action", |style| {
1694                                                        style.text_color(
1695                                                            cx.theme().colors().editor_line_number,
1696                                                        )
1697                                                    }),
1698                                            )
1699                                            .when_some(jump_data.clone(), |this, jump_data| {
1700                                                this.on_click(cx.listener_for(&self.editor, {
1701                                                    let path = jump_data.path.clone();
1702                                                    move |editor, _, cx| {
1703                                                        editor.jump(
1704                                                            path.clone(),
1705                                                            jump_data.position,
1706                                                            jump_data.anchor,
1707                                                            jump_data.line_offset_from_top,
1708                                                            cx,
1709                                                        );
1710                                                    }
1711                                                }))
1712                                                .tooltip({
1713                                                    move |cx| {
1714                                                        Tooltip::for_action(
1715                                                            format!(
1716                                                                "Jump to {}:L{}",
1717                                                                jump_data.path.path.display(),
1718                                                                jump_data.position.row + 1
1719                                                            ),
1720                                                            &OpenExcerpts,
1721                                                            cx,
1722                                                        )
1723                                                    }
1724                                                })
1725                                            }),
1726                                    ),
1727                            )
1728                            .group("excerpt-jump-action")
1729                            .cursor_pointer()
1730                            .when_some(jump_data.clone(), |this, jump_data| {
1731                                this.on_click(cx.listener_for(&self.editor, {
1732                                    let path = jump_data.path.clone();
1733                                    move |editor, _, cx| {
1734                                        cx.stop_propagation();
1735
1736                                        editor.jump(
1737                                            path.clone(),
1738                                            jump_data.position,
1739                                            jump_data.anchor,
1740                                            jump_data.line_offset_from_top,
1741                                            cx,
1742                                        );
1743                                    }
1744                                }))
1745                                .tooltip(move |cx| {
1746                                    Tooltip::for_action(
1747                                        format!(
1748                                            "Jump to {}:L{}",
1749                                            jump_data.path.path.display(),
1750                                            jump_data.position.row + 1
1751                                        ),
1752                                        &OpenExcerpts,
1753                                        cx,
1754                                    )
1755                                })
1756                            })
1757                    };
1758                    element.into_any()
1759                }
1760            };
1761
1762            let size = element.measure(available_space, cx);
1763            (element, size)
1764        };
1765
1766        let mut fixed_block_max_width = Pixels::ZERO;
1767        let mut blocks = Vec::new();
1768        for (row, block) in fixed_blocks {
1769            let available_space = size(
1770                AvailableSpace::MinContent,
1771                AvailableSpace::Definite(block.height() as f32 * line_height),
1772            );
1773            let (element, element_size) = render_block(block, available_space, block_id, row, cx);
1774            block_id += 1;
1775            fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
1776            blocks.push(BlockLayout {
1777                row,
1778                element,
1779                available_space,
1780                style: BlockStyle::Fixed,
1781            });
1782        }
1783        for (row, block) in non_fixed_blocks {
1784            let style = match block {
1785                TransformBlock::Custom(block) => block.style(),
1786                TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
1787            };
1788            let width = match style {
1789                BlockStyle::Sticky => hitbox.size.width,
1790                BlockStyle::Flex => hitbox
1791                    .size
1792                    .width
1793                    .max(fixed_block_max_width)
1794                    .max(gutter_dimensions.width + *scroll_width),
1795                BlockStyle::Fixed => unreachable!(),
1796            };
1797            let available_space = size(
1798                AvailableSpace::Definite(width),
1799                AvailableSpace::Definite(block.height() as f32 * line_height),
1800            );
1801            let (element, _) = render_block(block, available_space, block_id, row, cx);
1802            block_id += 1;
1803            blocks.push(BlockLayout {
1804                row,
1805                element,
1806                available_space,
1807                style,
1808            });
1809        }
1810
1811        *scroll_width = (*scroll_width).max(fixed_block_max_width - gutter_dimensions.width);
1812        blocks
1813    }
1814
1815    fn layout_blocks(
1816        &self,
1817        blocks: &mut Vec<BlockLayout>,
1818        hitbox: &Hitbox,
1819        line_height: Pixels,
1820        scroll_pixel_position: gpui::Point<Pixels>,
1821        cx: &mut ElementContext,
1822    ) {
1823        for block in blocks {
1824            let mut origin = hitbox.origin
1825                + point(
1826                    Pixels::ZERO,
1827                    block.row as f32 * line_height - scroll_pixel_position.y,
1828                );
1829            if !matches!(block.style, BlockStyle::Sticky) {
1830                origin += point(-scroll_pixel_position.x, Pixels::ZERO);
1831            }
1832            block.element.layout(origin, block.available_space, cx);
1833        }
1834    }
1835
1836    #[allow(clippy::too_many_arguments)]
1837    fn layout_context_menu(
1838        &self,
1839        line_height: Pixels,
1840        hitbox: &Hitbox,
1841        text_hitbox: &Hitbox,
1842        content_origin: gpui::Point<Pixels>,
1843        start_row: u32,
1844        scroll_pixel_position: gpui::Point<Pixels>,
1845        line_layouts: &[LineWithInvisibles],
1846        newest_selection_head: DisplayPoint,
1847        cx: &mut ElementContext,
1848    ) -> bool {
1849        let max_height = cmp::min(
1850            12. * line_height,
1851            cmp::max(3. * line_height, (hitbox.size.height - line_height) / 2.),
1852        );
1853        let Some((position, mut context_menu)) = self.editor.update(cx, |editor, cx| {
1854            if editor.context_menu_visible() {
1855                editor.render_context_menu(newest_selection_head, &self.style, max_height, cx)
1856            } else {
1857                None
1858            }
1859        }) else {
1860            return false;
1861        };
1862
1863        let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1864        let context_menu_size = context_menu.measure(available_space, cx);
1865
1866        let cursor_row_layout = &line_layouts[(position.row() - start_row) as usize].line;
1867        let x = cursor_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
1868        let y = (position.row() + 1) as f32 * line_height - scroll_pixel_position.y;
1869        let mut list_origin = content_origin + point(x, y);
1870        let list_width = context_menu_size.width;
1871        let list_height = context_menu_size.height;
1872
1873        // Snap the right edge of the list to the right edge of the window if
1874        // its horizontal bounds overflow.
1875        if list_origin.x + list_width > cx.viewport_size().width {
1876            list_origin.x = (cx.viewport_size().width - list_width).max(Pixels::ZERO);
1877        }
1878
1879        if list_origin.y + list_height > text_hitbox.lower_right().y {
1880            list_origin.y -= line_height + list_height;
1881        }
1882
1883        cx.defer_draw(context_menu, list_origin, 1);
1884        true
1885    }
1886
1887    fn layout_mouse_context_menu(&self, cx: &mut ElementContext) -> Option<AnyElement> {
1888        let mouse_context_menu = self.editor.read(cx).mouse_context_menu.as_ref()?;
1889        let mut element = deferred(
1890            anchored()
1891                .position(mouse_context_menu.position)
1892                .child(mouse_context_menu.context_menu.clone())
1893                .anchor(AnchorCorner::TopLeft)
1894                .snap_to_window(),
1895        )
1896        .with_priority(1)
1897        .into_any();
1898
1899        element.layout(gpui::Point::default(), AvailableSpace::min_size(), cx);
1900        Some(element)
1901    }
1902
1903    #[allow(clippy::too_many_arguments)]
1904    fn layout_hover_popovers(
1905        &self,
1906        snapshot: &EditorSnapshot,
1907        hitbox: &Hitbox,
1908        text_hitbox: &Hitbox,
1909        visible_display_row_range: Range<u32>,
1910        content_origin: gpui::Point<Pixels>,
1911        scroll_pixel_position: gpui::Point<Pixels>,
1912        line_layouts: &[LineWithInvisibles],
1913        line_height: Pixels,
1914        em_width: Pixels,
1915        cx: &mut ElementContext,
1916    ) {
1917        struct MeasuredHoverPopover {
1918            element: AnyElement,
1919            size: Size<Pixels>,
1920            horizontal_offset: Pixels,
1921        }
1922
1923        let max_size = size(
1924            (120. * em_width) // Default size
1925                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
1926                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
1927            (16. * line_height) // Default size
1928                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
1929                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
1930        );
1931
1932        let hover_popovers = self.editor.update(cx, |editor, cx| {
1933            editor.hover_state.render(
1934                &snapshot,
1935                &self.style,
1936                visible_display_row_range.clone(),
1937                max_size,
1938                editor.workspace.as_ref().map(|(w, _)| w.clone()),
1939                cx,
1940            )
1941        });
1942        let Some((position, hover_popovers)) = hover_popovers else {
1943            return;
1944        };
1945
1946        let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1947
1948        // This is safe because we check on layout whether the required row is available
1949        let hovered_row_layout =
1950            &line_layouts[(position.row() - visible_display_row_range.start) as usize].line;
1951
1952        // Compute Hovered Point
1953        let x =
1954            hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
1955        let y = position.row() as f32 * line_height - scroll_pixel_position.y;
1956        let hovered_point = content_origin + point(x, y);
1957
1958        let mut overall_height = Pixels::ZERO;
1959        let mut measured_hover_popovers = Vec::new();
1960        for mut hover_popover in hover_popovers {
1961            let size = hover_popover.measure(available_space, cx);
1962            let horizontal_offset =
1963                (text_hitbox.upper_right().x - (hovered_point.x + size.width)).min(Pixels::ZERO);
1964
1965            overall_height += HOVER_POPOVER_GAP + size.height;
1966
1967            measured_hover_popovers.push(MeasuredHoverPopover {
1968                element: hover_popover,
1969                size,
1970                horizontal_offset,
1971            });
1972        }
1973        overall_height += HOVER_POPOVER_GAP;
1974
1975        fn draw_occluder(width: Pixels, origin: gpui::Point<Pixels>, cx: &mut ElementContext) {
1976            let mut occlusion = div()
1977                .size_full()
1978                .occlude()
1979                .on_mouse_move(|_, cx| cx.stop_propagation())
1980                .into_any_element();
1981            occlusion.measure(size(width, HOVER_POPOVER_GAP).into(), cx);
1982            cx.defer_draw(occlusion, origin, 2);
1983        }
1984
1985        if hovered_point.y > overall_height {
1986            // There is enough space above. Render popovers above the hovered point
1987            let mut current_y = hovered_point.y;
1988            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
1989                let size = popover.size;
1990                let popover_origin = point(
1991                    hovered_point.x + popover.horizontal_offset,
1992                    current_y - size.height,
1993                );
1994
1995                cx.defer_draw(popover.element, popover_origin, 2);
1996                if position != itertools::Position::Last {
1997                    let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
1998                    draw_occluder(size.width, origin, cx);
1999                }
2000
2001                current_y = popover_origin.y - HOVER_POPOVER_GAP;
2002            }
2003        } else {
2004            // There is not enough space above. Render popovers below the hovered point
2005            let mut current_y = hovered_point.y + line_height;
2006            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
2007                let size = popover.size;
2008                let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
2009
2010                cx.defer_draw(popover.element, popover_origin, 2);
2011                if position != itertools::Position::Last {
2012                    let origin = point(popover_origin.x, popover_origin.y + size.height);
2013                    draw_occluder(size.width, origin, cx);
2014                }
2015
2016                current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
2017            }
2018        }
2019    }
2020
2021    fn paint_background(&self, layout: &EditorLayout, cx: &mut ElementContext) {
2022        cx.paint_layer(layout.hitbox.bounds, |cx| {
2023            let scroll_top = layout.position_map.snapshot.scroll_position().y;
2024            let gutter_bg = cx.theme().colors().editor_gutter_background;
2025            cx.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
2026            cx.paint_quad(fill(layout.text_hitbox.bounds, self.style.background));
2027
2028            if let EditorMode::Full = layout.mode {
2029                let mut active_rows = layout.active_rows.iter().peekable();
2030                while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
2031                    let mut end_row = *start_row;
2032                    while active_rows.peek().map_or(false, |r| {
2033                        *r.0 == end_row + 1 && r.1 == contains_non_empty_selection
2034                    }) {
2035                        active_rows.next().unwrap();
2036                        end_row += 1;
2037                    }
2038
2039                    if !contains_non_empty_selection {
2040                        let origin = point(
2041                            layout.hitbox.origin.x,
2042                            layout.hitbox.origin.y
2043                                + (*start_row as f32 - scroll_top)
2044                                    * layout.position_map.line_height,
2045                        );
2046                        let size = size(
2047                            layout.hitbox.size.width,
2048                            layout.position_map.line_height * (end_row - start_row + 1) as f32,
2049                        );
2050                        let active_line_bg = cx.theme().colors().editor_active_line_background;
2051                        cx.paint_quad(fill(Bounds { origin, size }, active_line_bg));
2052                    }
2053                }
2054
2055                let mut paint_highlight =
2056                    |highlight_row_start: u32, highlight_row_end: u32, color| {
2057                        let origin = point(
2058                            layout.hitbox.origin.x,
2059                            layout.hitbox.origin.y
2060                                + (highlight_row_start as f32 - scroll_top)
2061                                    * layout.position_map.line_height,
2062                        );
2063                        let size = size(
2064                            layout.hitbox.size.width,
2065                            layout.position_map.line_height
2066                                * (highlight_row_end + 1 - highlight_row_start) as f32,
2067                        );
2068                        cx.paint_quad(fill(Bounds { origin, size }, color));
2069                    };
2070
2071                let mut last_row = None;
2072                let mut highlight_row_start = 0u32;
2073                let mut highlight_row_end = 0u32;
2074                for (&row, &color) in &layout.highlighted_rows {
2075                    let paint = last_row.map_or(false, |(last_row, last_color)| {
2076                        last_color != color || last_row + 1 < row
2077                    });
2078
2079                    if paint {
2080                        let paint_range_is_unfinished = highlight_row_end == 0;
2081                        if paint_range_is_unfinished {
2082                            highlight_row_end = row;
2083                            last_row = None;
2084                        }
2085                        paint_highlight(highlight_row_start, highlight_row_end, color);
2086                        highlight_row_start = 0;
2087                        highlight_row_end = 0;
2088                        if !paint_range_is_unfinished {
2089                            highlight_row_start = row;
2090                            last_row = Some((row, color));
2091                        }
2092                    } else {
2093                        if last_row.is_none() {
2094                            highlight_row_start = row;
2095                        } else {
2096                            highlight_row_end = row;
2097                        }
2098                        last_row = Some((row, color));
2099                    }
2100                }
2101                if let Some((row, hsla)) = last_row {
2102                    highlight_row_end = row;
2103                    paint_highlight(highlight_row_start, highlight_row_end, hsla);
2104                }
2105
2106                let scroll_left =
2107                    layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
2108
2109                for (wrap_position, active) in layout.wrap_guides.iter() {
2110                    let x = (layout.text_hitbox.origin.x
2111                        + *wrap_position
2112                        + layout.position_map.em_width / 2.)
2113                        - scroll_left;
2114
2115                    let show_scrollbars = layout
2116                        .scrollbar_layout
2117                        .as_ref()
2118                        .map_or(false, |scrollbar| scrollbar.visible);
2119                    if x < layout.text_hitbox.origin.x
2120                        || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
2121                    {
2122                        continue;
2123                    }
2124
2125                    let color = if *active {
2126                        cx.theme().colors().editor_active_wrap_guide
2127                    } else {
2128                        cx.theme().colors().editor_wrap_guide
2129                    };
2130                    cx.paint_quad(fill(
2131                        Bounds {
2132                            origin: point(x, layout.text_hitbox.origin.y),
2133                            size: size(px(1.), layout.text_hitbox.size.height),
2134                        },
2135                        color,
2136                    ));
2137                }
2138            }
2139        })
2140    }
2141
2142    fn paint_gutter(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2143        let line_height = layout.position_map.line_height;
2144
2145        let scroll_position = layout.position_map.snapshot.scroll_position();
2146        let scroll_top = scroll_position.y * line_height;
2147
2148        cx.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
2149
2150        let show_git_gutter = matches!(
2151            ProjectSettings::get_global(cx).git.git_gutter,
2152            Some(GitGutterSetting::TrackedFiles)
2153        );
2154
2155        if show_git_gutter {
2156            Self::paint_diff_hunks(layout, cx);
2157        }
2158
2159        if layout.blamed_display_rows.is_some() {
2160            self.paint_blamed_display_rows(layout, cx);
2161        }
2162
2163        for (ix, line) in layout.line_numbers.iter().enumerate() {
2164            if let Some(line) = line {
2165                let line_origin = layout.gutter_hitbox.origin
2166                    + point(
2167                        layout.gutter_hitbox.size.width
2168                            - line.width
2169                            - layout.gutter_dimensions.right_padding,
2170                        ix as f32 * line_height - (scroll_top % line_height),
2171                    );
2172
2173                line.paint(line_origin, line_height, cx).log_err();
2174            }
2175        }
2176
2177        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2178            cx.with_element_id(Some("gutter_fold_indicators"), |cx| {
2179                for fold_indicator in layout.fold_indicators.iter_mut().flatten() {
2180                    fold_indicator.paint(cx);
2181                }
2182            });
2183
2184            if let Some(indicator) = layout.code_actions_indicator.as_mut() {
2185                indicator.paint(cx);
2186            }
2187        })
2188    }
2189
2190    fn paint_diff_hunks(layout: &EditorLayout, cx: &mut ElementContext) {
2191        if layout.display_hunks.is_empty() {
2192            return;
2193        }
2194
2195        let line_height = layout.position_map.line_height;
2196
2197        let scroll_position = layout.position_map.snapshot.scroll_position();
2198        let scroll_top = scroll_position.y * line_height;
2199
2200        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2201            for hunk in &layout.display_hunks {
2202                let (display_row_range, status) = match hunk {
2203                    //TODO: This rendering is entirely a horrible hack
2204                    &DisplayDiffHunk::Folded { display_row: row } => {
2205                        let start_y = row as f32 * line_height - scroll_top;
2206                        let end_y = start_y + line_height;
2207
2208                        let width = 0.275 * line_height;
2209                        let highlight_origin = layout.gutter_hitbox.origin + point(-width, start_y);
2210                        let highlight_size = size(width * 2., end_y - start_y);
2211                        let highlight_bounds = Bounds::new(highlight_origin, highlight_size);
2212                        cx.paint_quad(quad(
2213                            highlight_bounds,
2214                            Corners::all(1. * line_height),
2215                            cx.theme().status().modified,
2216                            Edges::default(),
2217                            transparent_black(),
2218                        ));
2219
2220                        continue;
2221                    }
2222
2223                    DisplayDiffHunk::Unfolded {
2224                        display_row_range,
2225                        status,
2226                    } => (display_row_range, status),
2227                };
2228
2229                let color = match status {
2230                    DiffHunkStatus::Added => cx.theme().status().created,
2231                    DiffHunkStatus::Modified => cx.theme().status().modified,
2232
2233                    //TODO: This rendering is entirely a horrible hack
2234                    DiffHunkStatus::Removed => {
2235                        let row = display_row_range.start;
2236
2237                        let offset = line_height / 2.;
2238                        let start_y = row as f32 * line_height - offset - scroll_top;
2239                        let end_y = start_y + line_height;
2240
2241                        let width = 0.275 * line_height;
2242                        let highlight_origin = layout.gutter_hitbox.origin + point(-width, start_y);
2243                        let highlight_size = size(width * 2., end_y - start_y);
2244                        let highlight_bounds = Bounds::new(highlight_origin, highlight_size);
2245                        cx.paint_quad(quad(
2246                            highlight_bounds,
2247                            Corners::all(1. * line_height),
2248                            cx.theme().status().deleted,
2249                            Edges::default(),
2250                            transparent_black(),
2251                        ));
2252
2253                        continue;
2254                    }
2255                };
2256
2257                let start_row = display_row_range.start;
2258                let end_row = display_row_range.end;
2259                // If we're in a multibuffer, row range span might include an
2260                // excerpt header, so if we were to draw the marker straight away,
2261                // the hunk might include the rows of that header.
2262                // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
2263                // Instead, we simply check whether the range we're dealing with includes
2264                // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
2265                let end_row_in_current_excerpt = layout
2266                    .position_map
2267                    .snapshot
2268                    .blocks_in_range(start_row..end_row)
2269                    .find_map(|(start_row, block)| {
2270                        if matches!(block, TransformBlock::ExcerptHeader { .. }) {
2271                            Some(start_row)
2272                        } else {
2273                            None
2274                        }
2275                    })
2276                    .unwrap_or(end_row);
2277
2278                let start_y = start_row as f32 * line_height - scroll_top;
2279                let end_y = end_row_in_current_excerpt as f32 * line_height - scroll_top;
2280
2281                let width = 0.275 * line_height;
2282                let highlight_origin = layout.gutter_hitbox.origin + point(-width, start_y);
2283                let highlight_size = size(width * 2., end_y - start_y);
2284                let highlight_bounds = Bounds::new(highlight_origin, highlight_size);
2285                cx.paint_quad(quad(
2286                    highlight_bounds,
2287                    Corners::all(0.05 * line_height),
2288                    color,
2289                    Edges::default(),
2290                    transparent_black(),
2291                ));
2292            }
2293        })
2294    }
2295
2296    fn paint_blamed_display_rows(&self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2297        let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
2298            return;
2299        };
2300
2301        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2302            for mut blame_element in blamed_display_rows.into_iter() {
2303                blame_element.paint(cx);
2304            }
2305        })
2306    }
2307
2308    fn paint_text(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2309        cx.with_content_mask(
2310            Some(ContentMask {
2311                bounds: layout.text_hitbox.bounds,
2312            }),
2313            |cx| {
2314                let cursor_style = if self
2315                    .editor
2316                    .read(cx)
2317                    .hovered_link_state
2318                    .as_ref()
2319                    .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
2320                {
2321                    CursorStyle::PointingHand
2322                } else {
2323                    CursorStyle::IBeam
2324                };
2325                cx.set_cursor_style(cursor_style, &layout.text_hitbox);
2326
2327                cx.with_element_id(Some("folds"), |cx| self.paint_folds(layout, cx));
2328                let invisible_display_ranges = self.paint_highlights(layout, cx);
2329                self.paint_lines(&invisible_display_ranges, layout, cx);
2330                self.paint_redactions(layout, cx);
2331                self.paint_cursors(layout, cx);
2332                self.paint_inline_blame(layout, cx);
2333            },
2334        )
2335    }
2336
2337    fn paint_highlights(
2338        &mut self,
2339        layout: &mut EditorLayout,
2340        cx: &mut ElementContext,
2341    ) -> SmallVec<[Range<DisplayPoint>; 32]> {
2342        cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2343            let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
2344            let line_end_overshoot = 0.15 * layout.position_map.line_height;
2345            for (range, color) in &layout.highlighted_ranges {
2346                self.paint_highlighted_range(
2347                    range.clone(),
2348                    *color,
2349                    Pixels::ZERO,
2350                    line_end_overshoot,
2351                    layout,
2352                    cx,
2353                );
2354            }
2355
2356            let corner_radius = 0.15 * layout.position_map.line_height;
2357
2358            for (player_color, selections) in &layout.selections {
2359                for selection in selections.into_iter() {
2360                    self.paint_highlighted_range(
2361                        selection.range.clone(),
2362                        player_color.selection,
2363                        corner_radius,
2364                        corner_radius * 2.,
2365                        layout,
2366                        cx,
2367                    );
2368
2369                    if selection.is_local && !selection.range.is_empty() {
2370                        invisible_display_ranges.push(selection.range.clone());
2371                    }
2372                }
2373            }
2374            invisible_display_ranges
2375        })
2376    }
2377
2378    fn paint_lines(
2379        &mut self,
2380        invisible_display_ranges: &[Range<DisplayPoint>],
2381        layout: &EditorLayout,
2382        cx: &mut ElementContext,
2383    ) {
2384        let whitespace_setting = self
2385            .editor
2386            .read(cx)
2387            .buffer
2388            .read(cx)
2389            .settings_at(0, cx)
2390            .show_whitespaces;
2391
2392        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
2393            let row = layout.visible_display_row_range.start + ix as u32;
2394            line_with_invisibles.draw(
2395                layout,
2396                row,
2397                layout.content_origin,
2398                whitespace_setting,
2399                invisible_display_ranges,
2400                cx,
2401            )
2402        }
2403    }
2404
2405    fn paint_redactions(&mut self, layout: &EditorLayout, cx: &mut ElementContext) {
2406        if layout.redacted_ranges.is_empty() {
2407            return;
2408        }
2409
2410        let line_end_overshoot = layout.line_end_overshoot();
2411
2412        // A softer than perfect black
2413        let redaction_color = gpui::rgb(0x0e1111);
2414
2415        cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2416            for range in layout.redacted_ranges.iter() {
2417                self.paint_highlighted_range(
2418                    range.clone(),
2419                    redaction_color.into(),
2420                    Pixels::ZERO,
2421                    line_end_overshoot,
2422                    layout,
2423                    cx,
2424                );
2425            }
2426        });
2427    }
2428
2429    fn paint_cursors(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2430        for cursor in &mut layout.cursors {
2431            cursor.paint(layout.content_origin, cx);
2432        }
2433    }
2434
2435    fn paint_scrollbar(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2436        let Some(scrollbar_layout) = layout.scrollbar_layout.as_ref() else {
2437            return;
2438        };
2439
2440        let thumb_bounds = scrollbar_layout.thumb_bounds();
2441        if scrollbar_layout.visible {
2442            cx.paint_layer(scrollbar_layout.hitbox.bounds, |cx| {
2443                cx.paint_quad(quad(
2444                    scrollbar_layout.hitbox.bounds,
2445                    Corners::default(),
2446                    cx.theme().colors().scrollbar_track_background,
2447                    Edges {
2448                        top: Pixels::ZERO,
2449                        right: Pixels::ZERO,
2450                        bottom: Pixels::ZERO,
2451                        left: ScrollbarLayout::BORDER_WIDTH,
2452                    },
2453                    cx.theme().colors().scrollbar_track_border,
2454                ));
2455
2456                // Refresh scrollbar markers in the background. Below, we paint whatever markers have already been computed.
2457                self.refresh_scrollbar_markers(layout, scrollbar_layout, cx);
2458
2459                let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
2460                for marker in markers.iter() {
2461                    let mut marker = marker.clone();
2462                    marker.bounds.origin += scrollbar_layout.hitbox.origin;
2463                    cx.paint_quad(marker);
2464                }
2465
2466                cx.paint_quad(quad(
2467                    thumb_bounds,
2468                    Corners::default(),
2469                    cx.theme().colors().scrollbar_thumb_background,
2470                    Edges {
2471                        top: Pixels::ZERO,
2472                        right: Pixels::ZERO,
2473                        bottom: Pixels::ZERO,
2474                        left: ScrollbarLayout::BORDER_WIDTH,
2475                    },
2476                    cx.theme().colors().scrollbar_thumb_border,
2477                ));
2478            });
2479        }
2480
2481        cx.set_cursor_style(CursorStyle::Arrow, &scrollbar_layout.hitbox);
2482
2483        let scroll_height = scrollbar_layout.scroll_height;
2484        let height = scrollbar_layout.height;
2485        let row_range = scrollbar_layout.visible_row_range.clone();
2486
2487        cx.on_mouse_event({
2488            let editor = self.editor.clone();
2489            let hitbox = scrollbar_layout.hitbox.clone();
2490            let mut mouse_position = cx.mouse_position();
2491            move |event: &MouseMoveEvent, phase, cx| {
2492                if phase == DispatchPhase::Capture {
2493                    return;
2494                }
2495
2496                editor.update(cx, |editor, cx| {
2497                    if event.pressed_button == Some(MouseButton::Left)
2498                        && editor.scroll_manager.is_dragging_scrollbar()
2499                    {
2500                        let y = mouse_position.y;
2501                        let new_y = event.position.y;
2502                        if (hitbox.top()..hitbox.bottom()).contains(&y) {
2503                            let mut position = editor.scroll_position(cx);
2504                            position.y += (new_y - y) * scroll_height / height;
2505                            if position.y < 0.0 {
2506                                position.y = 0.0;
2507                            }
2508                            editor.set_scroll_position(position, cx);
2509                        }
2510
2511                        mouse_position = event.position;
2512                        cx.stop_propagation();
2513                    } else {
2514                        editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
2515                        if hitbox.is_hovered(cx) {
2516                            editor.scroll_manager.show_scrollbar(cx);
2517                        }
2518                    }
2519                })
2520            }
2521        });
2522
2523        if self.editor.read(cx).scroll_manager.is_dragging_scrollbar() {
2524            cx.on_mouse_event({
2525                let editor = self.editor.clone();
2526                move |_: &MouseUpEvent, phase, cx| {
2527                    if phase == DispatchPhase::Capture {
2528                        return;
2529                    }
2530
2531                    editor.update(cx, |editor, cx| {
2532                        editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
2533                        cx.stop_propagation();
2534                    });
2535                }
2536            });
2537        } else {
2538            cx.on_mouse_event({
2539                let editor = self.editor.clone();
2540                let hitbox = scrollbar_layout.hitbox.clone();
2541                move |event: &MouseDownEvent, phase, cx| {
2542                    if phase == DispatchPhase::Capture || !hitbox.is_hovered(cx) {
2543                        return;
2544                    }
2545
2546                    editor.update(cx, |editor, cx| {
2547                        editor.scroll_manager.set_is_dragging_scrollbar(true, cx);
2548
2549                        let y = event.position.y;
2550                        if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
2551                            let center_row =
2552                                ((y - hitbox.top()) * scroll_height / height).round() as u32;
2553                            let top_row = center_row
2554                                .saturating_sub((row_range.end - row_range.start) as u32 / 2);
2555                            let mut position = editor.scroll_position(cx);
2556                            position.y = top_row as f32;
2557                            editor.set_scroll_position(position, cx);
2558                        } else {
2559                            editor.scroll_manager.show_scrollbar(cx);
2560                        }
2561
2562                        cx.stop_propagation();
2563                    });
2564                }
2565            });
2566        }
2567    }
2568
2569    fn refresh_scrollbar_markers(
2570        &self,
2571        layout: &EditorLayout,
2572        scrollbar_layout: &ScrollbarLayout,
2573        cx: &mut ElementContext,
2574    ) {
2575        self.editor.update(cx, |editor, cx| {
2576            if !editor.is_singleton(cx)
2577                || !editor
2578                    .scrollbar_marker_state
2579                    .should_refresh(scrollbar_layout.hitbox.size)
2580            {
2581                return;
2582            }
2583
2584            let scrollbar_layout = scrollbar_layout.clone();
2585            let background_highlights = editor.background_highlights.clone();
2586            let snapshot = layout.position_map.snapshot.clone();
2587            let theme = cx.theme().clone();
2588            let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
2589            let max_row = layout.max_row;
2590
2591            editor.scrollbar_marker_state.dirty = false;
2592            editor.scrollbar_marker_state.pending_refresh =
2593                Some(cx.spawn(|editor, mut cx| async move {
2594                    let scrollbar_size = scrollbar_layout.hitbox.size;
2595                    let scrollbar_markers = cx
2596                        .background_executor()
2597                        .spawn(async move {
2598                            let mut marker_quads = Vec::new();
2599
2600                            if scrollbar_settings.git_diff {
2601                                let marker_row_ranges = snapshot
2602                                    .buffer_snapshot
2603                                    .git_diff_hunks_in_range(0..max_row)
2604                                    .map(|hunk| {
2605                                        let start_display_row =
2606                                            Point::new(hunk.associated_range.start, 0)
2607                                                .to_display_point(&snapshot.display_snapshot)
2608                                                .row();
2609                                        let mut end_display_row =
2610                                            Point::new(hunk.associated_range.end, 0)
2611                                                .to_display_point(&snapshot.display_snapshot)
2612                                                .row();
2613                                        if end_display_row != start_display_row {
2614                                            end_display_row -= 1;
2615                                        }
2616                                        let color = match hunk.status() {
2617                                            DiffHunkStatus::Added => theme.status().created,
2618                                            DiffHunkStatus::Modified => theme.status().modified,
2619                                            DiffHunkStatus::Removed => theme.status().deleted,
2620                                        };
2621                                        ColoredRange {
2622                                            start: start_display_row,
2623                                            end: end_display_row,
2624                                            color,
2625                                        }
2626                                    });
2627
2628                                marker_quads.extend(
2629                                    scrollbar_layout.marker_quads_for_ranges(marker_row_ranges, 0),
2630                                );
2631                            }
2632
2633                            for (background_highlight_id, (_, background_ranges)) in
2634                                background_highlights.iter()
2635                            {
2636                                let is_search_highlights = *background_highlight_id
2637                                    == TypeId::of::<BufferSearchHighlights>();
2638                                let is_symbol_occurrences = *background_highlight_id
2639                                    == TypeId::of::<DocumentHighlightRead>()
2640                                    || *background_highlight_id
2641                                        == TypeId::of::<DocumentHighlightWrite>();
2642                                if (is_search_highlights && scrollbar_settings.search_results)
2643                                    || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
2644                                {
2645                                    let marker_row_ranges =
2646                                        background_ranges.into_iter().map(|range| {
2647                                            let display_start = range
2648                                                .start
2649                                                .to_display_point(&snapshot.display_snapshot);
2650                                            let display_end = range
2651                                                .end
2652                                                .to_display_point(&snapshot.display_snapshot);
2653                                            ColoredRange {
2654                                                start: display_start.row(),
2655                                                end: display_end.row(),
2656                                                color: theme.status().info,
2657                                            }
2658                                        });
2659                                    marker_quads.extend(
2660                                        scrollbar_layout
2661                                            .marker_quads_for_ranges(marker_row_ranges, 1),
2662                                    );
2663                                }
2664                            }
2665
2666                            if scrollbar_settings.diagnostics {
2667                                let max_point =
2668                                    snapshot.display_snapshot.buffer_snapshot.max_point();
2669
2670                                let diagnostics = snapshot
2671                                    .buffer_snapshot
2672                                    .diagnostics_in_range::<_, Point>(
2673                                        Point::zero()..max_point,
2674                                        false,
2675                                    )
2676                                    // We want to sort by severity, in order to paint the most severe diagnostics last.
2677                                    .sorted_by_key(|diagnostic| {
2678                                        std::cmp::Reverse(diagnostic.diagnostic.severity)
2679                                    });
2680
2681                                let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
2682                                    let start_display = diagnostic
2683                                        .range
2684                                        .start
2685                                        .to_display_point(&snapshot.display_snapshot);
2686                                    let end_display = diagnostic
2687                                        .range
2688                                        .end
2689                                        .to_display_point(&snapshot.display_snapshot);
2690                                    let color = match diagnostic.diagnostic.severity {
2691                                        DiagnosticSeverity::ERROR => theme.status().error,
2692                                        DiagnosticSeverity::WARNING => theme.status().warning,
2693                                        DiagnosticSeverity::INFORMATION => theme.status().info,
2694                                        _ => theme.status().hint,
2695                                    };
2696                                    ColoredRange {
2697                                        start: start_display.row(),
2698                                        end: end_display.row(),
2699                                        color,
2700                                    }
2701                                });
2702                                marker_quads.extend(
2703                                    scrollbar_layout.marker_quads_for_ranges(marker_row_ranges, 2),
2704                                );
2705                            }
2706
2707                            Arc::from(marker_quads)
2708                        })
2709                        .await;
2710
2711                    editor.update(&mut cx, |editor, cx| {
2712                        editor.scrollbar_marker_state.markers = scrollbar_markers;
2713                        editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
2714                        editor.scrollbar_marker_state.pending_refresh = None;
2715                        cx.notify();
2716                    })?;
2717
2718                    Ok(())
2719                }));
2720        });
2721    }
2722
2723    #[allow(clippy::too_many_arguments)]
2724    fn paint_highlighted_range(
2725        &self,
2726        range: Range<DisplayPoint>,
2727        color: Hsla,
2728        corner_radius: Pixels,
2729        line_end_overshoot: Pixels,
2730        layout: &EditorLayout,
2731        cx: &mut ElementContext,
2732    ) {
2733        let start_row = layout.visible_display_row_range.start;
2734        let end_row = layout.visible_display_row_range.end;
2735        if range.start != range.end {
2736            let row_range = if range.end.column() == 0 {
2737                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
2738            } else {
2739                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
2740            };
2741
2742            let highlighted_range = HighlightedRange {
2743                color,
2744                line_height: layout.position_map.line_height,
2745                corner_radius,
2746                start_y: layout.content_origin.y
2747                    + row_range.start as f32 * layout.position_map.line_height
2748                    - layout.position_map.scroll_pixel_position.y,
2749                lines: row_range
2750                    .into_iter()
2751                    .map(|row| {
2752                        let line_layout =
2753                            &layout.position_map.line_layouts[(row - start_row) as usize].line;
2754                        HighlightedRangeLine {
2755                            start_x: if row == range.start.row() {
2756                                layout.content_origin.x
2757                                    + line_layout.x_for_index(range.start.column() as usize)
2758                                    - layout.position_map.scroll_pixel_position.x
2759                            } else {
2760                                layout.content_origin.x
2761                                    - layout.position_map.scroll_pixel_position.x
2762                            },
2763                            end_x: if row == range.end.row() {
2764                                layout.content_origin.x
2765                                    + line_layout.x_for_index(range.end.column() as usize)
2766                                    - layout.position_map.scroll_pixel_position.x
2767                            } else {
2768                                layout.content_origin.x + line_layout.width + line_end_overshoot
2769                                    - layout.position_map.scroll_pixel_position.x
2770                            },
2771                        }
2772                    })
2773                    .collect(),
2774            };
2775
2776            highlighted_range.paint(layout.text_hitbox.bounds, cx);
2777        }
2778    }
2779
2780    fn paint_folds(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2781        if layout.folds.is_empty() {
2782            return;
2783        }
2784
2785        cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2786            let fold_corner_radius = 0.15 * layout.position_map.line_height;
2787            for mut fold in mem::take(&mut layout.folds) {
2788                fold.hover_element.paint(cx);
2789
2790                let hover_element = fold.hover_element.downcast_mut::<Stateful<Div>>().unwrap();
2791                let fold_background = if hover_element.interactivity().active.unwrap() {
2792                    cx.theme().colors().ghost_element_active
2793                } else if hover_element.interactivity().hovered.unwrap() {
2794                    cx.theme().colors().ghost_element_hover
2795                } else {
2796                    cx.theme().colors().ghost_element_background
2797                };
2798
2799                self.paint_highlighted_range(
2800                    fold.display_range.clone(),
2801                    fold_background,
2802                    fold_corner_radius,
2803                    fold_corner_radius * 2.,
2804                    layout,
2805                    cx,
2806                );
2807            }
2808        })
2809    }
2810
2811    fn paint_inline_blame(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2812        if let Some(mut inline_blame) = layout.inline_blame.take() {
2813            cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2814                inline_blame.paint(cx);
2815            })
2816        }
2817    }
2818
2819    fn paint_blocks(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2820        for mut block in layout.blocks.drain(..) {
2821            block.element.paint(cx);
2822        }
2823    }
2824
2825    fn paint_mouse_context_menu(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2826        if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
2827            mouse_context_menu.paint(cx);
2828        }
2829    }
2830
2831    fn paint_scroll_wheel_listener(&mut self, layout: &EditorLayout, cx: &mut ElementContext) {
2832        cx.on_mouse_event({
2833            let position_map = layout.position_map.clone();
2834            let editor = self.editor.clone();
2835            let hitbox = layout.hitbox.clone();
2836            let mut delta = ScrollDelta::default();
2837
2838            // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
2839            // accidentally turn off their scrolling.
2840            let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
2841
2842            move |event: &ScrollWheelEvent, phase, cx| {
2843                if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
2844                    delta = delta.coalesce(event.delta);
2845                    editor.update(cx, |editor, cx| {
2846                        let position_map: &PositionMap = &position_map;
2847
2848                        let line_height = position_map.line_height;
2849                        let max_glyph_width = position_map.em_width;
2850                        let (delta, axis) = match delta {
2851                            gpui::ScrollDelta::Pixels(mut pixels) => {
2852                                //Trackpad
2853                                let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
2854                                (pixels, axis)
2855                            }
2856
2857                            gpui::ScrollDelta::Lines(lines) => {
2858                                //Not trackpad
2859                                let pixels =
2860                                    point(lines.x * max_glyph_width, lines.y * line_height);
2861                                (pixels, None)
2862                            }
2863                        };
2864
2865                        let scroll_position = position_map.snapshot.scroll_position();
2866                        let x = (scroll_position.x * max_glyph_width
2867                            - (delta.x * scroll_sensitivity))
2868                            / max_glyph_width;
2869                        let y = (scroll_position.y * line_height - (delta.y * scroll_sensitivity))
2870                            / line_height;
2871                        let scroll_position =
2872                            point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
2873                        editor.scroll(scroll_position, axis, cx);
2874                        cx.stop_propagation();
2875                    });
2876                }
2877            }
2878        });
2879    }
2880
2881    fn paint_mouse_listeners(&mut self, layout: &EditorLayout, cx: &mut ElementContext) {
2882        self.paint_scroll_wheel_listener(layout, cx);
2883
2884        cx.on_mouse_event({
2885            let position_map = layout.position_map.clone();
2886            let editor = self.editor.clone();
2887            let text_hitbox = layout.text_hitbox.clone();
2888            let gutter_hitbox = layout.gutter_hitbox.clone();
2889
2890            move |event: &MouseDownEvent, phase, cx| {
2891                if phase == DispatchPhase::Bubble {
2892                    match event.button {
2893                        MouseButton::Left => editor.update(cx, |editor, cx| {
2894                            Self::mouse_left_down(
2895                                editor,
2896                                event,
2897                                &position_map,
2898                                &text_hitbox,
2899                                &gutter_hitbox,
2900                                cx,
2901                            );
2902                        }),
2903                        MouseButton::Right => editor.update(cx, |editor, cx| {
2904                            Self::mouse_right_down(editor, event, &position_map, &text_hitbox, cx);
2905                        }),
2906                        _ => {}
2907                    };
2908                }
2909            }
2910        });
2911
2912        cx.on_mouse_event({
2913            let editor = self.editor.clone();
2914            let position_map = layout.position_map.clone();
2915            let text_hitbox = layout.text_hitbox.clone();
2916
2917            move |event: &MouseUpEvent, phase, cx| {
2918                if phase == DispatchPhase::Bubble {
2919                    editor.update(cx, |editor, cx| {
2920                        Self::mouse_up(editor, event, &position_map, &text_hitbox, cx)
2921                    });
2922                }
2923            }
2924        });
2925        cx.on_mouse_event({
2926            let position_map = layout.position_map.clone();
2927            let editor = self.editor.clone();
2928            let text_hitbox = layout.text_hitbox.clone();
2929            let gutter_hitbox = layout.gutter_hitbox.clone();
2930
2931            move |event: &MouseMoveEvent, phase, cx| {
2932                if phase == DispatchPhase::Bubble {
2933                    editor.update(cx, |editor, cx| {
2934                        if event.pressed_button == Some(MouseButton::Left) {
2935                            Self::mouse_dragged(
2936                                editor,
2937                                event,
2938                                &position_map,
2939                                text_hitbox.bounds,
2940                                cx,
2941                            )
2942                        }
2943
2944                        Self::mouse_moved(
2945                            editor,
2946                            event,
2947                            &position_map,
2948                            &text_hitbox,
2949                            &gutter_hitbox,
2950                            cx,
2951                        )
2952                    });
2953                }
2954            }
2955        });
2956    }
2957
2958    fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
2959        bounds.upper_right().x - self.style.scrollbar_width
2960    }
2961
2962    fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
2963        let style = &self.style;
2964        let font_size = style.text.font_size.to_pixels(cx.rem_size());
2965        let layout = cx
2966            .text_system()
2967            .shape_line(
2968                SharedString::from(" ".repeat(column)),
2969                font_size,
2970                &[TextRun {
2971                    len: column,
2972                    font: style.text.font(),
2973                    color: Hsla::default(),
2974                    background_color: None,
2975                    underline: None,
2976                    strikethrough: None,
2977                }],
2978            )
2979            .unwrap();
2980
2981        layout.width
2982    }
2983
2984    fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
2985        let digit_count = (snapshot.max_buffer_row() as f32 + 1.).log10().floor() as usize + 1;
2986        self.column_pixels(digit_count, cx)
2987    }
2988}
2989
2990fn render_inline_blame_entry(
2991    blame: &gpui::Model<GitBlame>,
2992    blame_entry: BlameEntry,
2993    style: &EditorStyle,
2994    workspace: Option<WeakView<Workspace>>,
2995    cx: &mut ElementContext<'_>,
2996) -> AnyElement {
2997    let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
2998
2999    let author = blame_entry.author.as_deref().unwrap_or_default();
3000    let text = format!("{}, {}", author, relative_timestamp);
3001
3002    let details = blame.read(cx).details_for_entry(&blame_entry);
3003
3004    let tooltip = cx.new_view(|_| BlameEntryTooltip::new(blame_entry, details, style, workspace));
3005
3006    h_flex()
3007        .id("inline-blame")
3008        .w_full()
3009        .font(style.text.font().family)
3010        .text_color(cx.theme().status().hint)
3011        .line_height(style.text.line_height)
3012        .child(Icon::new(IconName::FileGit).color(Color::Hint))
3013        .child(text)
3014        .gap_2()
3015        .hoverable_tooltip(move |_| tooltip.clone().into())
3016        .into_any()
3017}
3018
3019fn blame_entry_timestamp(
3020    blame_entry: &BlameEntry,
3021    format: time_format::TimestampFormat,
3022    cx: &WindowContext,
3023) -> String {
3024    match blame_entry.author_offset_date_time() {
3025        Ok(timestamp) => time_format::format_localized_timestamp(
3026            timestamp,
3027            time::OffsetDateTime::now_utc(),
3028            cx.local_timezone(),
3029            format,
3030        ),
3031        Err(_) => "Error parsing date".to_string(),
3032    }
3033}
3034
3035fn blame_entry_relative_timestamp(blame_entry: &BlameEntry, cx: &WindowContext) -> String {
3036    blame_entry_timestamp(blame_entry, time_format::TimestampFormat::Relative, cx)
3037}
3038
3039fn blame_entry_absolute_timestamp(blame_entry: &BlameEntry, cx: &WindowContext) -> String {
3040    blame_entry_timestamp(
3041        blame_entry,
3042        time_format::TimestampFormat::MediumAbsolute,
3043        cx,
3044    )
3045}
3046
3047struct BlameEntryTooltip {
3048    blame_entry: BlameEntry,
3049    details: Option<CommitDetails>,
3050    style: EditorStyle,
3051    workspace: Option<WeakView<Workspace>>,
3052    scroll_handle: ScrollHandle,
3053}
3054
3055impl BlameEntryTooltip {
3056    fn new(
3057        blame_entry: BlameEntry,
3058        details: Option<CommitDetails>,
3059        style: &EditorStyle,
3060        workspace: Option<WeakView<Workspace>>,
3061    ) -> Self {
3062        Self {
3063            style: style.clone(),
3064            blame_entry,
3065            details,
3066            workspace,
3067            scroll_handle: ScrollHandle::new(),
3068        }
3069    }
3070}
3071
3072impl Render for BlameEntryTooltip {
3073    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
3074        let author = self
3075            .blame_entry
3076            .author
3077            .clone()
3078            .unwrap_or("<no name>".to_string());
3079
3080        let author_email = self.blame_entry.author_mail.clone();
3081
3082        let pretty_commit_id = format!("{}", self.blame_entry.sha);
3083        let short_commit_id = pretty_commit_id.chars().take(6).collect::<String>();
3084        let absolute_timestamp = blame_entry_absolute_timestamp(&self.blame_entry, cx);
3085
3086        let message = self
3087            .details
3088            .as_ref()
3089            .map(|details| {
3090                crate::render_parsed_markdown(
3091                    "blame-message",
3092                    &details.parsed_message,
3093                    &self.style,
3094                    self.workspace.clone(),
3095                    cx,
3096                )
3097                .into_any()
3098            })
3099            .unwrap_or("<no commit message>".into_any());
3100
3101        let ui_font_size = ThemeSettings::get_global(cx).ui_font_size;
3102        let message_max_height = cx.line_height() * 12 + (ui_font_size / 0.4);
3103
3104        tooltip_container(cx, move |this, cx| {
3105            this.occlude()
3106                .on_mouse_move(|_, cx| cx.stop_propagation())
3107                .child(
3108                    v_flex()
3109                        .w(gpui::rems(30.))
3110                        .gap_4()
3111                        .child(
3112                            h_flex()
3113                                .gap_x_2()
3114                                .overflow_x_hidden()
3115                                .flex_wrap()
3116                                .child(author)
3117                                .when_some(author_email, |this, author_email| {
3118                                    this.child(
3119                                        div()
3120                                            .text_color(cx.theme().colors().text_muted)
3121                                            .child(author_email),
3122                                    )
3123                                })
3124                                .pb_1()
3125                                .border_b_1()
3126                                .border_color(cx.theme().colors().border),
3127                        )
3128                        .child(
3129                            div()
3130                                .id("inline-blame-commit-message")
3131                                .occlude()
3132                                .child(message)
3133                                .max_h(message_max_height)
3134                                .overflow_y_scroll()
3135                                .track_scroll(&self.scroll_handle),
3136                        )
3137                        .child(
3138                            h_flex()
3139                                .text_color(cx.theme().colors().text_muted)
3140                                .w_full()
3141                                .justify_between()
3142                                .child(absolute_timestamp)
3143                                .child(
3144                                    Button::new("commit-sha-button", short_commit_id.clone())
3145                                        .style(ButtonStyle::Transparent)
3146                                        .color(Color::Muted)
3147                                        .icon(IconName::FileGit)
3148                                        .icon_color(Color::Muted)
3149                                        .icon_position(IconPosition::Start)
3150                                        .disabled(
3151                                            self.details.as_ref().map_or(true, |details| {
3152                                                details.permalink.is_none()
3153                                            }),
3154                                        )
3155                                        .when_some(
3156                                            self.details
3157                                                .as_ref()
3158                                                .and_then(|details| details.permalink.clone()),
3159                                            |this, url| {
3160                                                this.on_click(move |_, cx| {
3161                                                    cx.stop_propagation();
3162                                                    cx.open_url(url.as_str())
3163                                                })
3164                                            },
3165                                        ),
3166                                ),
3167                        ),
3168                )
3169        })
3170    }
3171}
3172
3173fn render_blame_entry(
3174    ix: usize,
3175    blame: &gpui::Model<GitBlame>,
3176    blame_entry: BlameEntry,
3177    style: &EditorStyle,
3178    last_used_color: &mut Option<(PlayerColor, Oid)>,
3179    editor: View<Editor>,
3180    cx: &mut ElementContext<'_>,
3181) -> AnyElement {
3182    let mut sha_color = cx
3183        .theme()
3184        .players()
3185        .color_for_participant(blame_entry.sha.into());
3186    // If the last color we used is the same as the one we get for this line, but
3187    // the commit SHAs are different, then we try again to get a different color.
3188    match *last_used_color {
3189        Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
3190            let index: u32 = blame_entry.sha.into();
3191            sha_color = cx.theme().players().color_for_participant(index + 1);
3192        }
3193        _ => {}
3194    };
3195    last_used_color.replace((sha_color, blame_entry.sha));
3196
3197    let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
3198
3199    let pretty_commit_id = format!("{}", blame_entry.sha);
3200    let short_commit_id = pretty_commit_id.chars().take(6).collect::<String>();
3201
3202    let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
3203    let name = util::truncate_and_trailoff(author_name, 20);
3204
3205    let details = blame.read(cx).details_for_entry(&blame_entry);
3206
3207    let workspace = editor.read(cx).workspace.as_ref().map(|(w, _)| w.clone());
3208
3209    let tooltip = cx.new_view(|_| {
3210        BlameEntryTooltip::new(blame_entry.clone(), details.clone(), style, workspace)
3211    });
3212
3213    h_flex()
3214        .w_full()
3215        .font(style.text.font().family)
3216        .line_height(style.text.line_height)
3217        .id(("blame", ix))
3218        .children([
3219            div()
3220                .text_color(sha_color.cursor)
3221                .child(short_commit_id)
3222                .mr_2(),
3223            div()
3224                .w_full()
3225                .h_flex()
3226                .justify_between()
3227                .text_color(cx.theme().status().hint)
3228                .child(name)
3229                .child(relative_timestamp),
3230        ])
3231        .on_mouse_down(MouseButton::Right, {
3232            let blame_entry = blame_entry.clone();
3233            move |event, cx| {
3234                deploy_blame_entry_context_menu(&blame_entry, editor.clone(), event.position, cx);
3235            }
3236        })
3237        .hover(|style| style.bg(cx.theme().colors().element_hover))
3238        .when_some(
3239            details.and_then(|details| details.permalink),
3240            |this, url| {
3241                let url = url.clone();
3242                this.cursor_pointer().on_click(move |_, cx| {
3243                    cx.stop_propagation();
3244                    cx.open_url(url.as_str())
3245                })
3246            },
3247        )
3248        .hoverable_tooltip(move |_| tooltip.clone().into())
3249        .into_any()
3250}
3251
3252fn deploy_blame_entry_context_menu(
3253    blame_entry: &BlameEntry,
3254    editor: View<Editor>,
3255    position: gpui::Point<Pixels>,
3256    cx: &mut WindowContext<'_>,
3257) {
3258    let context_menu = ContextMenu::build(cx, move |this, _| {
3259        let sha = format!("{}", blame_entry.sha);
3260        this.entry("Copy commit SHA", None, move |cx| {
3261            cx.write_to_clipboard(ClipboardItem::new(sha.clone()));
3262        })
3263    });
3264
3265    editor.update(cx, move |editor, cx| {
3266        editor.mouse_context_menu = Some(MouseContextMenu::new(position, context_menu, cx));
3267        cx.notify();
3268    });
3269}
3270
3271#[derive(Debug)]
3272pub(crate) struct LineWithInvisibles {
3273    pub line: ShapedLine,
3274    invisibles: Vec<Invisible>,
3275}
3276
3277impl LineWithInvisibles {
3278    fn from_chunks<'a>(
3279        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
3280        text_style: &TextStyle,
3281        max_line_len: usize,
3282        max_line_count: usize,
3283        line_number_layouts: &[Option<ShapedLine>],
3284        editor_mode: EditorMode,
3285        cx: &WindowContext,
3286    ) -> Vec<Self> {
3287        let mut layouts = Vec::with_capacity(max_line_count);
3288        let mut line = String::new();
3289        let mut invisibles = Vec::new();
3290        let mut styles = Vec::new();
3291        let mut non_whitespace_added = false;
3292        let mut row = 0;
3293        let mut line_exceeded_max_len = false;
3294        let font_size = text_style.font_size.to_pixels(cx.rem_size());
3295
3296        for highlighted_chunk in chunks.chain([HighlightedChunk {
3297            chunk: "\n",
3298            style: None,
3299            is_tab: false,
3300        }]) {
3301            for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
3302                if ix > 0 {
3303                    let shaped_line = cx
3304                        .text_system()
3305                        .shape_line(line.clone().into(), font_size, &styles)
3306                        .unwrap();
3307                    layouts.push(Self {
3308                        line: shaped_line,
3309                        invisibles: std::mem::take(&mut invisibles),
3310                    });
3311
3312                    line.clear();
3313                    styles.clear();
3314                    row += 1;
3315                    line_exceeded_max_len = false;
3316                    non_whitespace_added = false;
3317                    if row == max_line_count {
3318                        return layouts;
3319                    }
3320                }
3321
3322                if !line_chunk.is_empty() && !line_exceeded_max_len {
3323                    let text_style = if let Some(style) = highlighted_chunk.style {
3324                        Cow::Owned(text_style.clone().highlight(style))
3325                    } else {
3326                        Cow::Borrowed(text_style)
3327                    };
3328
3329                    if line.len() + line_chunk.len() > max_line_len {
3330                        let mut chunk_len = max_line_len - line.len();
3331                        while !line_chunk.is_char_boundary(chunk_len) {
3332                            chunk_len -= 1;
3333                        }
3334                        line_chunk = &line_chunk[..chunk_len];
3335                        line_exceeded_max_len = true;
3336                    }
3337
3338                    styles.push(TextRun {
3339                        len: line_chunk.len(),
3340                        font: text_style.font(),
3341                        color: text_style.color,
3342                        background_color: text_style.background_color,
3343                        underline: text_style.underline,
3344                        strikethrough: text_style.strikethrough,
3345                    });
3346
3347                    if editor_mode == EditorMode::Full {
3348                        // Line wrap pads its contents with fake whitespaces,
3349                        // avoid printing them
3350                        let inside_wrapped_string = line_number_layouts
3351                            .get(row)
3352                            .and_then(|layout| layout.as_ref())
3353                            .is_none();
3354                        if highlighted_chunk.is_tab {
3355                            if non_whitespace_added || !inside_wrapped_string {
3356                                invisibles.push(Invisible::Tab {
3357                                    line_start_offset: line.len(),
3358                                });
3359                            }
3360                        } else {
3361                            invisibles.extend(
3362                                line_chunk
3363                                    .chars()
3364                                    .enumerate()
3365                                    .filter(|(_, line_char)| {
3366                                        let is_whitespace = line_char.is_whitespace();
3367                                        non_whitespace_added |= !is_whitespace;
3368                                        is_whitespace
3369                                            && (non_whitespace_added || !inside_wrapped_string)
3370                                    })
3371                                    .map(|(whitespace_index, _)| Invisible::Whitespace {
3372                                        line_offset: line.len() + whitespace_index,
3373                                    }),
3374                            )
3375                        }
3376                    }
3377
3378                    line.push_str(line_chunk);
3379                }
3380            }
3381        }
3382
3383        layouts
3384    }
3385
3386    fn draw(
3387        &self,
3388        layout: &EditorLayout,
3389        row: u32,
3390        content_origin: gpui::Point<Pixels>,
3391        whitespace_setting: ShowWhitespaceSetting,
3392        selection_ranges: &[Range<DisplayPoint>],
3393        cx: &mut ElementContext,
3394    ) {
3395        let line_height = layout.position_map.line_height;
3396        let line_y =
3397            line_height * (row as f32 - layout.position_map.scroll_pixel_position.y / line_height);
3398
3399        let line_origin =
3400            content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
3401        self.line.paint(line_origin, line_height, cx).log_err();
3402
3403        self.draw_invisibles(
3404            &selection_ranges,
3405            layout,
3406            content_origin,
3407            line_y,
3408            row,
3409            line_height,
3410            whitespace_setting,
3411            cx,
3412        );
3413    }
3414
3415    #[allow(clippy::too_many_arguments)]
3416    fn draw_invisibles(
3417        &self,
3418        selection_ranges: &[Range<DisplayPoint>],
3419        layout: &EditorLayout,
3420        content_origin: gpui::Point<Pixels>,
3421        line_y: Pixels,
3422        row: u32,
3423        line_height: Pixels,
3424        whitespace_setting: ShowWhitespaceSetting,
3425        cx: &mut ElementContext,
3426    ) {
3427        let allowed_invisibles_regions = match whitespace_setting {
3428            ShowWhitespaceSetting::None => return,
3429            ShowWhitespaceSetting::Selection => Some(selection_ranges),
3430            ShowWhitespaceSetting::All => None,
3431        };
3432
3433        for invisible in &self.invisibles {
3434            let (&token_offset, invisible_symbol) = match invisible {
3435                Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
3436                Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
3437            };
3438
3439            let x_offset = self.line.x_for_index(token_offset);
3440            let invisible_offset =
3441                (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
3442            let origin = content_origin
3443                + gpui::point(
3444                    x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
3445                    line_y,
3446                );
3447
3448            if let Some(allowed_regions) = allowed_invisibles_regions {
3449                let invisible_point = DisplayPoint::new(row, token_offset as u32);
3450                if !allowed_regions
3451                    .iter()
3452                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
3453                {
3454                    continue;
3455                }
3456            }
3457            invisible_symbol.paint(origin, line_height, cx).log_err();
3458        }
3459    }
3460}
3461
3462#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3463enum Invisible {
3464    Tab { line_start_offset: usize },
3465    Whitespace { line_offset: usize },
3466}
3467
3468impl Element for EditorElement {
3469    type BeforeLayout = ();
3470    type AfterLayout = EditorLayout;
3471
3472    fn before_layout(&mut self, cx: &mut ElementContext) -> (gpui::LayoutId, ()) {
3473        self.editor.update(cx, |editor, cx| {
3474            editor.set_style(self.style.clone(), cx);
3475
3476            let layout_id = match editor.mode {
3477                EditorMode::SingleLine => {
3478                    let rem_size = cx.rem_size();
3479                    let mut style = Style::default();
3480                    style.size.width = relative(1.).into();
3481                    style.size.height = self.style.text.line_height_in_pixels(rem_size).into();
3482                    cx.with_element_context(|cx| cx.request_layout(&style, None))
3483                }
3484                EditorMode::AutoHeight { max_lines } => {
3485                    let editor_handle = cx.view().clone();
3486                    let max_line_number_width =
3487                        self.max_line_number_width(&editor.snapshot(cx), cx);
3488                    cx.with_element_context(|cx| {
3489                        cx.request_measured_layout(
3490                            Style::default(),
3491                            move |known_dimensions, _, cx| {
3492                                editor_handle
3493                                    .update(cx, |editor, cx| {
3494                                        compute_auto_height_layout(
3495                                            editor,
3496                                            max_lines,
3497                                            max_line_number_width,
3498                                            known_dimensions,
3499                                            cx,
3500                                        )
3501                                    })
3502                                    .unwrap_or_default()
3503                            },
3504                        )
3505                    })
3506                }
3507                EditorMode::Full => {
3508                    let mut style = Style::default();
3509                    style.size.width = relative(1.).into();
3510                    style.size.height = relative(1.).into();
3511                    cx.with_element_context(|cx| cx.request_layout(&style, None))
3512                }
3513            };
3514
3515            (layout_id, ())
3516        })
3517    }
3518
3519    fn after_layout(
3520        &mut self,
3521        bounds: Bounds<Pixels>,
3522        _: &mut Self::BeforeLayout,
3523        cx: &mut ElementContext,
3524    ) -> Self::AfterLayout {
3525        let text_style = TextStyleRefinement {
3526            font_size: Some(self.style.text.font_size),
3527            line_height: Some(self.style.text.line_height),
3528            ..Default::default()
3529        };
3530        cx.with_text_style(Some(text_style), |cx| {
3531            cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
3532                let mut snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
3533                let style = self.style.clone();
3534
3535                let font_id = cx.text_system().resolve_font(&style.text.font());
3536                let font_size = style.text.font_size.to_pixels(cx.rem_size());
3537                let line_height = style.text.line_height_in_pixels(cx.rem_size());
3538                let em_width = cx
3539                    .text_system()
3540                    .typographic_bounds(font_id, font_size, 'm')
3541                    .unwrap()
3542                    .size
3543                    .width;
3544                let em_advance = cx
3545                    .text_system()
3546                    .advance(font_id, font_size, 'm')
3547                    .unwrap()
3548                    .width;
3549
3550                let gutter_dimensions = snapshot.gutter_dimensions(
3551                    font_id,
3552                    font_size,
3553                    em_width,
3554                    self.max_line_number_width(&snapshot, cx),
3555                    cx,
3556                );
3557                let text_width = bounds.size.width - gutter_dimensions.width;
3558                let overscroll = size(em_width, px(0.));
3559
3560                snapshot = self.editor.update(cx, |editor, cx| {
3561                    editor.last_bounds = Some(bounds);
3562                    editor.gutter_width = gutter_dimensions.width;
3563                    editor.set_visible_line_count(bounds.size.height / line_height, cx);
3564
3565                    let editor_width =
3566                        text_width - gutter_dimensions.margin - overscroll.width - em_width;
3567                    let wrap_width = match editor.soft_wrap_mode(cx) {
3568                        SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
3569                        SoftWrap::EditorWidth => editor_width,
3570                        SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
3571                    };
3572
3573                    if editor.set_wrap_width(Some(wrap_width), cx) {
3574                        editor.snapshot(cx)
3575                    } else {
3576                        snapshot
3577                    }
3578                });
3579
3580                let wrap_guides = self
3581                    .editor
3582                    .read(cx)
3583                    .wrap_guides(cx)
3584                    .iter()
3585                    .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
3586                    .collect::<SmallVec<[_; 2]>>();
3587
3588                let hitbox = cx.insert_hitbox(bounds, false);
3589                let gutter_hitbox = cx.insert_hitbox(
3590                    Bounds {
3591                        origin: bounds.origin,
3592                        size: size(gutter_dimensions.width, bounds.size.height),
3593                    },
3594                    false,
3595                );
3596                let text_hitbox = cx.insert_hitbox(
3597                    Bounds {
3598                        origin: gutter_hitbox.upper_right(),
3599                        size: size(text_width, bounds.size.height),
3600                    },
3601                    false,
3602                );
3603                // Offset the content_bounds from the text_bounds by the gutter margin (which
3604                // is roughly half a character wide) to make hit testing work more like how we want.
3605                let content_origin =
3606                    text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
3607
3608                let autoscroll_horizontally = self.editor.update(cx, |editor, cx| {
3609                    let autoscroll_horizontally =
3610                        editor.autoscroll_vertically(bounds, line_height, cx);
3611                    snapshot = editor.snapshot(cx);
3612                    autoscroll_horizontally
3613                });
3614
3615                let mut scroll_position = snapshot.scroll_position();
3616                // The scroll position is a fractional point, the whole number of which represents
3617                // the top of the window in terms of display rows.
3618                let start_row = scroll_position.y as u32;
3619                let height_in_lines = bounds.size.height / line_height;
3620                let max_row = snapshot.max_point().row();
3621
3622                // Add 1 to ensure selections bleed off screen
3623                let end_row =
3624                    1 + cmp::min((scroll_position.y + height_in_lines).ceil() as u32, max_row);
3625
3626                let buffer_rows = snapshot
3627                    .buffer_rows(start_row)
3628                    .take((start_row..end_row).len());
3629
3630                let start_anchor = if start_row == 0 {
3631                    Anchor::min()
3632                } else {
3633                    snapshot.buffer_snapshot.anchor_before(
3634                        DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
3635                    )
3636                };
3637                let end_anchor = if end_row > max_row {
3638                    Anchor::max()
3639                } else {
3640                    snapshot.buffer_snapshot.anchor_before(
3641                        DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
3642                    )
3643                };
3644
3645                let highlighted_rows = self
3646                    .editor
3647                    .update(cx, |editor, cx| editor.highlighted_display_rows(cx));
3648                let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
3649                    start_anchor..end_anchor,
3650                    &snapshot.display_snapshot,
3651                    cx.theme().colors(),
3652                );
3653
3654                let redacted_ranges = self.editor.read(cx).redacted_ranges(
3655                    start_anchor..end_anchor,
3656                    &snapshot.display_snapshot,
3657                    cx,
3658                );
3659
3660                let (selections, active_rows, newest_selection_head) = self.layout_selections(
3661                    start_anchor,
3662                    end_anchor,
3663                    &snapshot,
3664                    start_row,
3665                    end_row,
3666                    cx,
3667                );
3668
3669                let (line_numbers, fold_statuses) = self.layout_line_numbers(
3670                    start_row..end_row,
3671                    buffer_rows.clone(),
3672                    &active_rows,
3673                    newest_selection_head,
3674                    &snapshot,
3675                    cx,
3676                );
3677
3678                let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
3679
3680                let mut max_visible_line_width = Pixels::ZERO;
3681                let line_layouts =
3682                    self.layout_lines(start_row..end_row, &line_numbers, &snapshot, cx);
3683                for line_with_invisibles in &line_layouts {
3684                    if line_with_invisibles.line.width > max_visible_line_width {
3685                        max_visible_line_width = line_with_invisibles.line.width;
3686                    }
3687                }
3688
3689                let longest_line_width = layout_line(snapshot.longest_row(), &snapshot, &style, cx)
3690                    .unwrap()
3691                    .width;
3692                let mut scroll_width =
3693                    longest_line_width.max(max_visible_line_width) + overscroll.width;
3694                let mut blocks = self.build_blocks(
3695                    start_row..end_row,
3696                    &snapshot,
3697                    &hitbox,
3698                    &text_hitbox,
3699                    &mut scroll_width,
3700                    &gutter_dimensions,
3701                    em_width,
3702                    gutter_dimensions.width + gutter_dimensions.margin,
3703                    line_height,
3704                    &line_layouts,
3705                    cx,
3706                );
3707
3708                let scroll_pixel_position = point(
3709                    scroll_position.x * em_width,
3710                    scroll_position.y * line_height,
3711                );
3712
3713                let mut inline_blame = None;
3714                if let Some(newest_selection_head) = newest_selection_head {
3715                    let display_row = newest_selection_head.row();
3716                    if (start_row..end_row).contains(&display_row) {
3717                        let line_layout = &line_layouts[(display_row - start_row) as usize];
3718                        inline_blame = self.layout_inline_blame(
3719                            display_row,
3720                            &snapshot.display_snapshot,
3721                            line_layout,
3722                            em_width,
3723                            content_origin,
3724                            scroll_pixel_position,
3725                            line_height,
3726                            cx,
3727                        );
3728                    }
3729                }
3730
3731                let blamed_display_rows = self.layout_blame_entries(
3732                    buffer_rows,
3733                    em_width,
3734                    scroll_position,
3735                    line_height,
3736                    &gutter_hitbox,
3737                    gutter_dimensions.git_blame_entries_width,
3738                    cx,
3739                );
3740
3741                let scroll_max = point(
3742                    ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
3743                    max_row as f32,
3744                );
3745
3746                self.editor.update(cx, |editor, cx| {
3747                    let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
3748
3749                    let autoscrolled = if autoscroll_horizontally {
3750                        editor.autoscroll_horizontally(
3751                            start_row,
3752                            text_hitbox.size.width,
3753                            scroll_width,
3754                            em_width,
3755                            &line_layouts,
3756                            cx,
3757                        )
3758                    } else {
3759                        false
3760                    };
3761
3762                    if clamped || autoscrolled {
3763                        snapshot = editor.snapshot(cx);
3764                        scroll_position = snapshot.scroll_position();
3765                    }
3766                });
3767
3768                cx.with_element_id(Some("blocks"), |cx| {
3769                    self.layout_blocks(
3770                        &mut blocks,
3771                        &hitbox,
3772                        line_height,
3773                        scroll_pixel_position,
3774                        cx,
3775                    );
3776                });
3777
3778                let cursors = self.layout_cursors(
3779                    &snapshot,
3780                    &selections,
3781                    start_row..end_row,
3782                    &line_layouts,
3783                    &text_hitbox,
3784                    content_origin,
3785                    scroll_pixel_position,
3786                    line_height,
3787                    em_width,
3788                    cx,
3789                );
3790
3791                let scrollbar_layout = self.layout_scrollbar(
3792                    &snapshot,
3793                    bounds,
3794                    scroll_position,
3795                    line_height,
3796                    height_in_lines,
3797                    cx,
3798                );
3799
3800                let folds = cx.with_element_id(Some("folds"), |cx| {
3801                    self.layout_folds(
3802                        &snapshot,
3803                        content_origin,
3804                        start_anchor..end_anchor,
3805                        start_row..end_row,
3806                        scroll_pixel_position,
3807                        line_height,
3808                        &line_layouts,
3809                        cx,
3810                    )
3811                });
3812
3813                let gutter_settings = EditorSettings::get_global(cx).gutter;
3814
3815                let mut context_menu_visible = false;
3816                let mut code_actions_indicator = None;
3817                if let Some(newest_selection_head) = newest_selection_head {
3818                    if (start_row..end_row).contains(&newest_selection_head.row()) {
3819                        context_menu_visible = self.layout_context_menu(
3820                            line_height,
3821                            &hitbox,
3822                            &text_hitbox,
3823                            content_origin,
3824                            start_row,
3825                            scroll_pixel_position,
3826                            &line_layouts,
3827                            newest_selection_head,
3828                            cx,
3829                        );
3830                        if gutter_settings.code_actions {
3831                            code_actions_indicator = self.layout_code_actions_indicator(
3832                                line_height,
3833                                newest_selection_head,
3834                                scroll_pixel_position,
3835                                &gutter_dimensions,
3836                                &gutter_hitbox,
3837                                cx,
3838                            );
3839                        }
3840                    }
3841                }
3842
3843                if !context_menu_visible && !cx.has_active_drag() {
3844                    self.layout_hover_popovers(
3845                        &snapshot,
3846                        &hitbox,
3847                        &text_hitbox,
3848                        start_row..end_row,
3849                        content_origin,
3850                        scroll_pixel_position,
3851                        &line_layouts,
3852                        line_height,
3853                        em_width,
3854                        cx,
3855                    );
3856                }
3857
3858                let mouse_context_menu = self.layout_mouse_context_menu(cx);
3859
3860                let fold_indicators = if gutter_settings.folds {
3861                    cx.with_element_id(Some("gutter_fold_indicators"), |cx| {
3862                        self.layout_gutter_fold_indicators(
3863                            fold_statuses,
3864                            line_height,
3865                            &gutter_dimensions,
3866                            gutter_settings,
3867                            scroll_pixel_position,
3868                            &gutter_hitbox,
3869                            cx,
3870                        )
3871                    })
3872                } else {
3873                    Vec::new()
3874                };
3875
3876                let invisible_symbol_font_size = font_size / 2.;
3877                let tab_invisible = cx
3878                    .text_system()
3879                    .shape_line(
3880                        "".into(),
3881                        invisible_symbol_font_size,
3882                        &[TextRun {
3883                            len: "".len(),
3884                            font: self.style.text.font(),
3885                            color: cx.theme().colors().editor_invisible,
3886                            background_color: None,
3887                            underline: None,
3888                            strikethrough: None,
3889                        }],
3890                    )
3891                    .unwrap();
3892                let space_invisible = cx
3893                    .text_system()
3894                    .shape_line(
3895                        "".into(),
3896                        invisible_symbol_font_size,
3897                        &[TextRun {
3898                            len: "".len(),
3899                            font: self.style.text.font(),
3900                            color: cx.theme().colors().editor_invisible,
3901                            background_color: None,
3902                            underline: None,
3903                            strikethrough: None,
3904                        }],
3905                    )
3906                    .unwrap();
3907
3908                EditorLayout {
3909                    mode: snapshot.mode,
3910                    position_map: Arc::new(PositionMap {
3911                        size: bounds.size,
3912                        scroll_pixel_position,
3913                        scroll_max,
3914                        line_layouts,
3915                        line_height,
3916                        em_width,
3917                        em_advance,
3918                        snapshot,
3919                    }),
3920                    visible_display_row_range: start_row..end_row,
3921                    wrap_guides,
3922                    hitbox,
3923                    text_hitbox,
3924                    gutter_hitbox,
3925                    gutter_dimensions,
3926                    content_origin,
3927                    scrollbar_layout,
3928                    max_row,
3929                    active_rows,
3930                    highlighted_rows,
3931                    highlighted_ranges,
3932                    redacted_ranges,
3933                    line_numbers,
3934                    display_hunks,
3935                    blamed_display_rows,
3936                    inline_blame,
3937                    folds,
3938                    blocks,
3939                    cursors,
3940                    selections,
3941                    mouse_context_menu,
3942                    code_actions_indicator,
3943                    fold_indicators,
3944                    tab_invisible,
3945                    space_invisible,
3946                }
3947            })
3948        })
3949    }
3950
3951    fn paint(
3952        &mut self,
3953        bounds: Bounds<gpui::Pixels>,
3954        _: &mut Self::BeforeLayout,
3955        layout: &mut Self::AfterLayout,
3956        cx: &mut ElementContext,
3957    ) {
3958        let focus_handle = self.editor.focus_handle(cx);
3959        let key_context = self.editor.read(cx).key_context(cx);
3960        cx.set_focus_handle(&focus_handle);
3961        cx.set_key_context(key_context);
3962        cx.set_view_id(self.editor.entity_id());
3963        cx.handle_input(
3964            &focus_handle,
3965            ElementInputHandler::new(bounds, self.editor.clone()),
3966        );
3967        self.register_actions(cx);
3968        self.register_key_listeners(cx, layout);
3969
3970        let text_style = TextStyleRefinement {
3971            font_size: Some(self.style.text.font_size),
3972            line_height: Some(self.style.text.line_height),
3973            ..Default::default()
3974        };
3975        cx.with_text_style(Some(text_style), |cx| {
3976            cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
3977                self.paint_mouse_listeners(layout, cx);
3978
3979                self.paint_background(layout, cx);
3980                if layout.gutter_hitbox.size.width > Pixels::ZERO {
3981                    self.paint_gutter(layout, cx);
3982                }
3983                self.paint_text(layout, cx);
3984
3985                if !layout.blocks.is_empty() {
3986                    cx.with_element_id(Some("blocks"), |cx| {
3987                        self.paint_blocks(layout, cx);
3988                    });
3989                }
3990
3991                self.paint_scrollbar(layout, cx);
3992                self.paint_mouse_context_menu(layout, cx);
3993            });
3994        })
3995    }
3996}
3997
3998impl IntoElement for EditorElement {
3999    type Element = Self;
4000
4001    fn into_element(self) -> Self::Element {
4002        self
4003    }
4004}
4005
4006type BufferRow = u32;
4007
4008pub struct EditorLayout {
4009    position_map: Arc<PositionMap>,
4010    hitbox: Hitbox,
4011    text_hitbox: Hitbox,
4012    gutter_hitbox: Hitbox,
4013    gutter_dimensions: GutterDimensions,
4014    content_origin: gpui::Point<Pixels>,
4015    scrollbar_layout: Option<ScrollbarLayout>,
4016    mode: EditorMode,
4017    wrap_guides: SmallVec<[(Pixels, bool); 2]>,
4018    visible_display_row_range: Range<u32>,
4019    active_rows: BTreeMap<u32, bool>,
4020    highlighted_rows: BTreeMap<u32, Hsla>,
4021    line_numbers: Vec<Option<ShapedLine>>,
4022    display_hunks: Vec<DisplayDiffHunk>,
4023    blamed_display_rows: Option<Vec<AnyElement>>,
4024    inline_blame: Option<AnyElement>,
4025    folds: Vec<FoldLayout>,
4026    blocks: Vec<BlockLayout>,
4027    highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
4028    redacted_ranges: Vec<Range<DisplayPoint>>,
4029    cursors: Vec<CursorLayout>,
4030    selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
4031    max_row: u32,
4032    code_actions_indicator: Option<AnyElement>,
4033    fold_indicators: Vec<Option<AnyElement>>,
4034    mouse_context_menu: Option<AnyElement>,
4035    tab_invisible: ShapedLine,
4036    space_invisible: ShapedLine,
4037}
4038
4039impl EditorLayout {
4040    fn line_end_overshoot(&self) -> Pixels {
4041        0.15 * self.position_map.line_height
4042    }
4043}
4044
4045struct ColoredRange<T> {
4046    start: T,
4047    end: T,
4048    color: Hsla,
4049}
4050
4051#[derive(Clone)]
4052struct ScrollbarLayout {
4053    hitbox: Hitbox,
4054    visible_row_range: Range<f32>,
4055    visible: bool,
4056    height: Pixels,
4057    scroll_height: f32,
4058    first_row_y_offset: Pixels,
4059    row_height: Pixels,
4060}
4061
4062impl ScrollbarLayout {
4063    const BORDER_WIDTH: Pixels = px(1.0);
4064    const MIN_MARKER_HEIGHT: Pixels = px(2.0);
4065
4066    fn thumb_bounds(&self) -> Bounds<Pixels> {
4067        let thumb_top = self.y_for_row(self.visible_row_range.start) - self.first_row_y_offset;
4068        let thumb_bottom = self.y_for_row(self.visible_row_range.end) + self.first_row_y_offset;
4069        Bounds::from_corners(
4070            point(self.hitbox.left(), thumb_top),
4071            point(self.hitbox.right(), thumb_bottom),
4072        )
4073    }
4074
4075    fn y_for_row(&self, row: f32) -> Pixels {
4076        self.hitbox.top() + self.first_row_y_offset + row * self.row_height
4077    }
4078
4079    fn marker_quads_for_ranges(
4080        &self,
4081        row_ranges: impl IntoIterator<Item = ColoredRange<u32>>,
4082        column: usize,
4083    ) -> Vec<PaintQuad> {
4084        let column_width =
4085            px(((self.hitbox.size.width - ScrollbarLayout::BORDER_WIDTH).0 / 3.0).floor());
4086
4087        let left_x = ScrollbarLayout::BORDER_WIDTH + (column as f32 * column_width);
4088        let right_x = left_x + column_width;
4089
4090        let mut background_pixel_ranges = row_ranges
4091            .into_iter()
4092            .map(|range| {
4093                let start_y = self.first_row_y_offset + range.start as f32 * self.row_height;
4094                let end_y = self.first_row_y_offset + (range.end + 1) as f32 * self.row_height;
4095                ColoredRange {
4096                    start: start_y,
4097                    end: end_y,
4098                    color: range.color,
4099                }
4100            })
4101            .peekable();
4102
4103        let mut quads = Vec::new();
4104        while let Some(mut pixel_range) = background_pixel_ranges.next() {
4105            pixel_range.end = pixel_range
4106                .end
4107                .max(pixel_range.start + Self::MIN_MARKER_HEIGHT);
4108            while let Some(next_pixel_range) = background_pixel_ranges.peek() {
4109                if pixel_range.end >= next_pixel_range.start
4110                    && pixel_range.color == next_pixel_range.color
4111                {
4112                    pixel_range.end = next_pixel_range.end.max(pixel_range.end);
4113                    background_pixel_ranges.next();
4114                } else {
4115                    break;
4116                }
4117            }
4118
4119            let bounds = Bounds::from_corners(
4120                point(left_x, pixel_range.start),
4121                point(right_x, pixel_range.end),
4122            );
4123            quads.push(quad(
4124                bounds,
4125                Corners::default(),
4126                pixel_range.color,
4127                Edges::default(),
4128                Hsla::transparent_black(),
4129            ));
4130        }
4131
4132        quads
4133    }
4134}
4135
4136struct FoldLayout {
4137    display_range: Range<DisplayPoint>,
4138    hover_element: AnyElement,
4139}
4140
4141struct PositionMap {
4142    size: Size<Pixels>,
4143    line_height: Pixels,
4144    scroll_pixel_position: gpui::Point<Pixels>,
4145    scroll_max: gpui::Point<f32>,
4146    em_width: Pixels,
4147    em_advance: Pixels,
4148    line_layouts: Vec<LineWithInvisibles>,
4149    snapshot: EditorSnapshot,
4150}
4151
4152#[derive(Debug, Copy, Clone)]
4153pub struct PointForPosition {
4154    pub previous_valid: DisplayPoint,
4155    pub next_valid: DisplayPoint,
4156    pub exact_unclipped: DisplayPoint,
4157    pub column_overshoot_after_line_end: u32,
4158}
4159
4160impl PointForPosition {
4161    pub fn as_valid(&self) -> Option<DisplayPoint> {
4162        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
4163            Some(self.previous_valid)
4164        } else {
4165            None
4166        }
4167    }
4168}
4169
4170impl PositionMap {
4171    fn point_for_position(
4172        &self,
4173        text_bounds: Bounds<Pixels>,
4174        position: gpui::Point<Pixels>,
4175    ) -> PointForPosition {
4176        let scroll_position = self.snapshot.scroll_position();
4177        let position = position - text_bounds.origin;
4178        let y = position.y.max(px(0.)).min(self.size.height);
4179        let x = position.x + (scroll_position.x * self.em_width);
4180        let row = ((y / self.line_height) + scroll_position.y) as u32;
4181
4182        let (column, x_overshoot_after_line_end) = if let Some(line) = self
4183            .line_layouts
4184            .get(row as usize - scroll_position.y as usize)
4185            .map(|LineWithInvisibles { line, .. }| line)
4186        {
4187            if let Some(ix) = line.index_for_x(x) {
4188                (ix as u32, px(0.))
4189            } else {
4190                (line.len as u32, px(0.).max(x - line.width))
4191            }
4192        } else {
4193            (0, x)
4194        };
4195
4196        let mut exact_unclipped = DisplayPoint::new(row, column);
4197        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
4198        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
4199
4200        let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
4201        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
4202        PointForPosition {
4203            previous_valid,
4204            next_valid,
4205            exact_unclipped,
4206            column_overshoot_after_line_end,
4207        }
4208    }
4209}
4210
4211struct BlockLayout {
4212    row: u32,
4213    element: AnyElement,
4214    available_space: Size<AvailableSpace>,
4215    style: BlockStyle,
4216}
4217
4218fn layout_line(
4219    row: u32,
4220    snapshot: &EditorSnapshot,
4221    style: &EditorStyle,
4222    cx: &WindowContext,
4223) -> Result<ShapedLine> {
4224    let mut line = snapshot.line(row);
4225
4226    if line.len() > MAX_LINE_LEN {
4227        let mut len = MAX_LINE_LEN;
4228        while !line.is_char_boundary(len) {
4229            len -= 1;
4230        }
4231
4232        line.truncate(len);
4233    }
4234
4235    cx.text_system().shape_line(
4236        line.into(),
4237        style.text.font_size.to_pixels(cx.rem_size()),
4238        &[TextRun {
4239            len: snapshot.line_len(row) as usize,
4240            font: style.text.font(),
4241            color: Hsla::default(),
4242            background_color: None,
4243            underline: None,
4244            strikethrough: None,
4245        }],
4246    )
4247}
4248
4249pub struct CursorLayout {
4250    origin: gpui::Point<Pixels>,
4251    block_width: Pixels,
4252    line_height: Pixels,
4253    color: Hsla,
4254    shape: CursorShape,
4255    block_text: Option<ShapedLine>,
4256    cursor_name: Option<AnyElement>,
4257}
4258
4259#[derive(Debug)]
4260pub struct CursorName {
4261    string: SharedString,
4262    color: Hsla,
4263    is_top_row: bool,
4264}
4265
4266impl CursorLayout {
4267    pub fn new(
4268        origin: gpui::Point<Pixels>,
4269        block_width: Pixels,
4270        line_height: Pixels,
4271        color: Hsla,
4272        shape: CursorShape,
4273        block_text: Option<ShapedLine>,
4274    ) -> CursorLayout {
4275        CursorLayout {
4276            origin,
4277            block_width,
4278            line_height,
4279            color,
4280            shape,
4281            block_text,
4282            cursor_name: None,
4283        }
4284    }
4285
4286    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
4287        Bounds {
4288            origin: self.origin + origin,
4289            size: size(self.block_width, self.line_height),
4290        }
4291    }
4292
4293    fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
4294        match self.shape {
4295            CursorShape::Bar => Bounds {
4296                origin: self.origin + origin,
4297                size: size(px(2.0), self.line_height),
4298            },
4299            CursorShape::Block | CursorShape::Hollow => Bounds {
4300                origin: self.origin + origin,
4301                size: size(self.block_width, self.line_height),
4302            },
4303            CursorShape::Underscore => Bounds {
4304                origin: self.origin
4305                    + origin
4306                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
4307                size: size(self.block_width, px(2.0)),
4308            },
4309        }
4310    }
4311
4312    pub fn layout(
4313        &mut self,
4314        origin: gpui::Point<Pixels>,
4315        cursor_name: Option<CursorName>,
4316        cx: &mut ElementContext,
4317    ) {
4318        if let Some(cursor_name) = cursor_name {
4319            let bounds = self.bounds(origin);
4320            let text_size = self.line_height / 1.5;
4321
4322            let name_origin = if cursor_name.is_top_row {
4323                point(bounds.right() - px(1.), bounds.top())
4324            } else {
4325                point(bounds.left(), bounds.top() - text_size / 2. - px(1.))
4326            };
4327            let mut name_element = div()
4328                .bg(self.color)
4329                .text_size(text_size)
4330                .px_0p5()
4331                .line_height(text_size + px(2.))
4332                .text_color(cursor_name.color)
4333                .child(cursor_name.string.clone())
4334                .into_any_element();
4335
4336            name_element.layout(
4337                name_origin,
4338                size(AvailableSpace::MinContent, AvailableSpace::MinContent),
4339                cx,
4340            );
4341
4342            self.cursor_name = Some(name_element);
4343        }
4344    }
4345
4346    pub fn paint(&mut self, origin: gpui::Point<Pixels>, cx: &mut ElementContext) {
4347        let bounds = self.bounds(origin);
4348
4349        //Draw background or border quad
4350        let cursor = if matches!(self.shape, CursorShape::Hollow) {
4351            outline(bounds, self.color)
4352        } else {
4353            fill(bounds, self.color)
4354        };
4355
4356        if let Some(name) = &mut self.cursor_name {
4357            name.paint(cx);
4358        }
4359
4360        cx.paint_quad(cursor);
4361
4362        if let Some(block_text) = &self.block_text {
4363            block_text
4364                .paint(self.origin + origin, self.line_height, cx)
4365                .log_err();
4366        }
4367    }
4368
4369    pub fn shape(&self) -> CursorShape {
4370        self.shape
4371    }
4372}
4373
4374#[derive(Debug)]
4375pub struct HighlightedRange {
4376    pub start_y: Pixels,
4377    pub line_height: Pixels,
4378    pub lines: Vec<HighlightedRangeLine>,
4379    pub color: Hsla,
4380    pub corner_radius: Pixels,
4381}
4382
4383#[derive(Debug)]
4384pub struct HighlightedRangeLine {
4385    pub start_x: Pixels,
4386    pub end_x: Pixels,
4387}
4388
4389impl HighlightedRange {
4390    pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut ElementContext) {
4391        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
4392            self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
4393            self.paint_lines(
4394                self.start_y + self.line_height,
4395                &self.lines[1..],
4396                bounds,
4397                cx,
4398            );
4399        } else {
4400            self.paint_lines(self.start_y, &self.lines, bounds, cx);
4401        }
4402    }
4403
4404    fn paint_lines(
4405        &self,
4406        start_y: Pixels,
4407        lines: &[HighlightedRangeLine],
4408        _bounds: Bounds<Pixels>,
4409        cx: &mut ElementContext,
4410    ) {
4411        if lines.is_empty() {
4412            return;
4413        }
4414
4415        let first_line = lines.first().unwrap();
4416        let last_line = lines.last().unwrap();
4417
4418        let first_top_left = point(first_line.start_x, start_y);
4419        let first_top_right = point(first_line.end_x, start_y);
4420
4421        let curve_height = point(Pixels::ZERO, self.corner_radius);
4422        let curve_width = |start_x: Pixels, end_x: Pixels| {
4423            let max = (end_x - start_x) / 2.;
4424            let width = if max < self.corner_radius {
4425                max
4426            } else {
4427                self.corner_radius
4428            };
4429
4430            point(width, Pixels::ZERO)
4431        };
4432
4433        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
4434        let mut path = gpui::Path::new(first_top_right - top_curve_width);
4435        path.curve_to(first_top_right + curve_height, first_top_right);
4436
4437        let mut iter = lines.iter().enumerate().peekable();
4438        while let Some((ix, line)) = iter.next() {
4439            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
4440
4441            if let Some((_, next_line)) = iter.peek() {
4442                let next_top_right = point(next_line.end_x, bottom_right.y);
4443
4444                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
4445                    Ordering::Equal => {
4446                        path.line_to(bottom_right);
4447                    }
4448                    Ordering::Less => {
4449                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
4450                        path.line_to(bottom_right - curve_height);
4451                        if self.corner_radius > Pixels::ZERO {
4452                            path.curve_to(bottom_right - curve_width, bottom_right);
4453                        }
4454                        path.line_to(next_top_right + curve_width);
4455                        if self.corner_radius > Pixels::ZERO {
4456                            path.curve_to(next_top_right + curve_height, next_top_right);
4457                        }
4458                    }
4459                    Ordering::Greater => {
4460                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
4461                        path.line_to(bottom_right - curve_height);
4462                        if self.corner_radius > Pixels::ZERO {
4463                            path.curve_to(bottom_right + curve_width, bottom_right);
4464                        }
4465                        path.line_to(next_top_right - curve_width);
4466                        if self.corner_radius > Pixels::ZERO {
4467                            path.curve_to(next_top_right + curve_height, next_top_right);
4468                        }
4469                    }
4470                }
4471            } else {
4472                let curve_width = curve_width(line.start_x, line.end_x);
4473                path.line_to(bottom_right - curve_height);
4474                if self.corner_radius > Pixels::ZERO {
4475                    path.curve_to(bottom_right - curve_width, bottom_right);
4476                }
4477
4478                let bottom_left = point(line.start_x, bottom_right.y);
4479                path.line_to(bottom_left + curve_width);
4480                if self.corner_radius > Pixels::ZERO {
4481                    path.curve_to(bottom_left - curve_height, bottom_left);
4482                }
4483            }
4484        }
4485
4486        if first_line.start_x > last_line.start_x {
4487            let curve_width = curve_width(last_line.start_x, first_line.start_x);
4488            let second_top_left = point(last_line.start_x, start_y + self.line_height);
4489            path.line_to(second_top_left + curve_height);
4490            if self.corner_radius > Pixels::ZERO {
4491                path.curve_to(second_top_left + curve_width, second_top_left);
4492            }
4493            let first_bottom_left = point(first_line.start_x, second_top_left.y);
4494            path.line_to(first_bottom_left - curve_width);
4495            if self.corner_radius > Pixels::ZERO {
4496                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
4497            }
4498        }
4499
4500        path.line_to(first_top_left + curve_height);
4501        if self.corner_radius > Pixels::ZERO {
4502            path.curve_to(first_top_left + top_curve_width, first_top_left);
4503        }
4504        path.line_to(first_top_right - top_curve_width);
4505
4506        cx.paint_path(path, self.color);
4507    }
4508}
4509
4510pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
4511    (delta.pow(1.5) / 100.0).into()
4512}
4513
4514fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
4515    (delta.pow(1.2) / 300.0).into()
4516}
4517
4518#[cfg(test)]
4519mod tests {
4520    use super::*;
4521    use crate::{
4522        display_map::{BlockDisposition, BlockProperties},
4523        editor_tests::{init_test, update_test_language_settings},
4524        Editor, MultiBuffer,
4525    };
4526    use gpui::TestAppContext;
4527    use language::language_settings;
4528    use log::info;
4529    use std::num::NonZeroU32;
4530    use util::test::sample_text;
4531
4532    #[gpui::test]
4533    fn test_shape_line_numbers(cx: &mut TestAppContext) {
4534        init_test(cx, |_| {});
4535        let window = cx.add_window(|cx| {
4536            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
4537            Editor::new(EditorMode::Full, buffer, None, cx)
4538        });
4539
4540        let editor = window.root(cx).unwrap();
4541        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4542        let element = EditorElement::new(&editor, style);
4543        let snapshot = window.update(cx, |editor, cx| editor.snapshot(cx)).unwrap();
4544
4545        let layouts = cx
4546            .update_window(*window, |_, cx| {
4547                cx.with_element_context(|cx| {
4548                    element
4549                        .layout_line_numbers(
4550                            0..6,
4551                            (0..6).map(Some),
4552                            &Default::default(),
4553                            Some(DisplayPoint::new(0, 0)),
4554                            &snapshot,
4555                            cx,
4556                        )
4557                        .0
4558                })
4559            })
4560            .unwrap();
4561        assert_eq!(layouts.len(), 6);
4562
4563        let relative_rows =
4564            element.calculate_relative_line_numbers((0..6).map(Some).collect(), &(0..6), Some(3));
4565        assert_eq!(relative_rows[&0], 3);
4566        assert_eq!(relative_rows[&1], 2);
4567        assert_eq!(relative_rows[&2], 1);
4568        // current line has no relative number
4569        assert_eq!(relative_rows[&4], 1);
4570        assert_eq!(relative_rows[&5], 2);
4571
4572        // works if cursor is before screen
4573        let relative_rows =
4574            element.calculate_relative_line_numbers((0..6).map(Some).collect(), &(3..6), Some(1));
4575        assert_eq!(relative_rows.len(), 3);
4576        assert_eq!(relative_rows[&3], 2);
4577        assert_eq!(relative_rows[&4], 3);
4578        assert_eq!(relative_rows[&5], 4);
4579
4580        // works if cursor is after screen
4581        let relative_rows =
4582            element.calculate_relative_line_numbers((0..6).map(Some).collect(), &(0..3), Some(6));
4583        assert_eq!(relative_rows.len(), 3);
4584        assert_eq!(relative_rows[&0], 5);
4585        assert_eq!(relative_rows[&1], 4);
4586        assert_eq!(relative_rows[&2], 3);
4587    }
4588
4589    #[gpui::test]
4590    async fn test_vim_visual_selections(cx: &mut TestAppContext) {
4591        init_test(cx, |_| {});
4592
4593        let window = cx.add_window(|cx| {
4594            let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
4595            Editor::new(EditorMode::Full, buffer, None, cx)
4596        });
4597        let editor = window.root(cx).unwrap();
4598        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4599        let mut element = EditorElement::new(&editor, style);
4600
4601        window
4602            .update(cx, |editor, cx| {
4603                editor.cursor_shape = CursorShape::Block;
4604                editor.change_selections(None, cx, |s| {
4605                    s.select_ranges([
4606                        Point::new(0, 0)..Point::new(1, 0),
4607                        Point::new(3, 2)..Point::new(3, 3),
4608                        Point::new(5, 6)..Point::new(6, 0),
4609                    ]);
4610                });
4611            })
4612            .unwrap();
4613        let state = cx
4614            .update_window(window.into(), |_view, cx| {
4615                cx.with_element_context(|cx| {
4616                    element.after_layout(
4617                        Bounds {
4618                            origin: point(px(500.), px(500.)),
4619                            size: size(px(500.), px(500.)),
4620                        },
4621                        &mut (),
4622                        cx,
4623                    )
4624                })
4625            })
4626            .unwrap();
4627
4628        assert_eq!(state.selections.len(), 1);
4629        let local_selections = &state.selections[0].1;
4630        assert_eq!(local_selections.len(), 3);
4631        // moves cursor back one line
4632        assert_eq!(local_selections[0].head, DisplayPoint::new(0, 6));
4633        assert_eq!(
4634            local_selections[0].range,
4635            DisplayPoint::new(0, 0)..DisplayPoint::new(1, 0)
4636        );
4637
4638        // moves cursor back one column
4639        assert_eq!(
4640            local_selections[1].range,
4641            DisplayPoint::new(3, 2)..DisplayPoint::new(3, 3)
4642        );
4643        assert_eq!(local_selections[1].head, DisplayPoint::new(3, 2));
4644
4645        // leaves cursor on the max point
4646        assert_eq!(
4647            local_selections[2].range,
4648            DisplayPoint::new(5, 6)..DisplayPoint::new(6, 0)
4649        );
4650        assert_eq!(local_selections[2].head, DisplayPoint::new(6, 0));
4651
4652        // active lines does not include 1 (even though the range of the selection does)
4653        assert_eq!(
4654            state.active_rows.keys().cloned().collect::<Vec<u32>>(),
4655            vec![0, 3, 5, 6]
4656        );
4657
4658        // multi-buffer support
4659        // in DisplayPoint coordinates, this is what we're dealing with:
4660        //  0: [[file
4661        //  1:   header]]
4662        //  2: aaaaaa
4663        //  3: bbbbbb
4664        //  4: cccccc
4665        //  5:
4666        //  6: ...
4667        //  7: ffffff
4668        //  8: gggggg
4669        //  9: hhhhhh
4670        // 10:
4671        // 11: [[file
4672        // 12:   header]]
4673        // 13: bbbbbb
4674        // 14: cccccc
4675        // 15: dddddd
4676        let window = cx.add_window(|cx| {
4677            let buffer = MultiBuffer::build_multi(
4678                [
4679                    (
4680                        &(sample_text(8, 6, 'a') + "\n"),
4681                        vec![
4682                            Point::new(0, 0)..Point::new(3, 0),
4683                            Point::new(4, 0)..Point::new(7, 0),
4684                        ],
4685                    ),
4686                    (
4687                        &(sample_text(8, 6, 'a') + "\n"),
4688                        vec![Point::new(1, 0)..Point::new(3, 0)],
4689                    ),
4690                ],
4691                cx,
4692            );
4693            Editor::new(EditorMode::Full, buffer, None, cx)
4694        });
4695        let editor = window.root(cx).unwrap();
4696        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4697        let mut element = EditorElement::new(&editor, style);
4698        let _state = window.update(cx, |editor, cx| {
4699            editor.cursor_shape = CursorShape::Block;
4700            editor.change_selections(None, cx, |s| {
4701                s.select_display_ranges([
4702                    DisplayPoint::new(4, 0)..DisplayPoint::new(7, 0),
4703                    DisplayPoint::new(10, 0)..DisplayPoint::new(13, 0),
4704                ]);
4705            });
4706        });
4707
4708        let state = cx
4709            .update_window(window.into(), |_view, cx| {
4710                cx.with_element_context(|cx| {
4711                    element.after_layout(
4712                        Bounds {
4713                            origin: point(px(500.), px(500.)),
4714                            size: size(px(500.), px(500.)),
4715                        },
4716                        &mut (),
4717                        cx,
4718                    )
4719                })
4720            })
4721            .unwrap();
4722        assert_eq!(state.selections.len(), 1);
4723        let local_selections = &state.selections[0].1;
4724        assert_eq!(local_selections.len(), 2);
4725
4726        // moves cursor on excerpt boundary back a line
4727        // and doesn't allow selection to bleed through
4728        assert_eq!(
4729            local_selections[0].range,
4730            DisplayPoint::new(4, 0)..DisplayPoint::new(6, 0)
4731        );
4732        assert_eq!(local_selections[0].head, DisplayPoint::new(5, 0));
4733        // moves cursor on buffer boundary back two lines
4734        // and doesn't allow selection to bleed through
4735        assert_eq!(
4736            local_selections[1].range,
4737            DisplayPoint::new(10, 0)..DisplayPoint::new(11, 0)
4738        );
4739        assert_eq!(local_selections[1].head, DisplayPoint::new(10, 0));
4740    }
4741
4742    #[gpui::test]
4743    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
4744        init_test(cx, |_| {});
4745
4746        let window = cx.add_window(|cx| {
4747            let buffer = MultiBuffer::build_simple("", cx);
4748            Editor::new(EditorMode::Full, buffer, None, cx)
4749        });
4750        let editor = window.root(cx).unwrap();
4751        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4752        window
4753            .update(cx, |editor, cx| {
4754                editor.set_placeholder_text("hello", cx);
4755                editor.insert_blocks(
4756                    [BlockProperties {
4757                        style: BlockStyle::Fixed,
4758                        disposition: BlockDisposition::Above,
4759                        height: 3,
4760                        position: Anchor::min(),
4761                        render: Box::new(|_| div().into_any()),
4762                    }],
4763                    None,
4764                    cx,
4765                );
4766
4767                // Blur the editor so that it displays placeholder text.
4768                cx.blur();
4769            })
4770            .unwrap();
4771
4772        let mut element = EditorElement::new(&editor, style);
4773        let state = cx
4774            .update_window(window.into(), |_view, cx| {
4775                cx.with_element_context(|cx| {
4776                    element.after_layout(
4777                        Bounds {
4778                            origin: point(px(500.), px(500.)),
4779                            size: size(px(500.), px(500.)),
4780                        },
4781                        &mut (),
4782                        cx,
4783                    )
4784                })
4785            })
4786            .unwrap();
4787
4788        assert_eq!(state.position_map.line_layouts.len(), 4);
4789        assert_eq!(
4790            state
4791                .line_numbers
4792                .iter()
4793                .map(Option::is_some)
4794                .collect::<Vec<_>>(),
4795            &[false, false, false, true]
4796        );
4797    }
4798
4799    #[gpui::test]
4800    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
4801        const TAB_SIZE: u32 = 4;
4802
4803        let input_text = "\t \t|\t| a b";
4804        let expected_invisibles = vec![
4805            Invisible::Tab {
4806                line_start_offset: 0,
4807            },
4808            Invisible::Whitespace {
4809                line_offset: TAB_SIZE as usize,
4810            },
4811            Invisible::Tab {
4812                line_start_offset: TAB_SIZE as usize + 1,
4813            },
4814            Invisible::Tab {
4815                line_start_offset: TAB_SIZE as usize * 2 + 1,
4816            },
4817            Invisible::Whitespace {
4818                line_offset: TAB_SIZE as usize * 3 + 1,
4819            },
4820            Invisible::Whitespace {
4821                line_offset: TAB_SIZE as usize * 3 + 3,
4822            },
4823        ];
4824        assert_eq!(
4825            expected_invisibles.len(),
4826            input_text
4827                .chars()
4828                .filter(|initial_char| initial_char.is_whitespace())
4829                .count(),
4830            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
4831        );
4832
4833        init_test(cx, |s| {
4834            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4835            s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
4836        });
4837
4838        let actual_invisibles =
4839            collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, px(500.0));
4840
4841        assert_eq!(expected_invisibles, actual_invisibles);
4842    }
4843
4844    #[gpui::test]
4845    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
4846        init_test(cx, |s| {
4847            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4848            s.defaults.tab_size = NonZeroU32::new(4);
4849        });
4850
4851        for editor_mode_without_invisibles in [
4852            EditorMode::SingleLine,
4853            EditorMode::AutoHeight { max_lines: 100 },
4854        ] {
4855            let invisibles = collect_invisibles_from_new_editor(
4856                cx,
4857                editor_mode_without_invisibles,
4858                "\t\t\t| | a b",
4859                px(500.0),
4860            );
4861            assert!(invisibles.is_empty(),
4862                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
4863        }
4864    }
4865
4866    #[gpui::test]
4867    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
4868        let tab_size = 4;
4869        let input_text = "a\tbcd   ".repeat(9);
4870        let repeated_invisibles = [
4871            Invisible::Tab {
4872                line_start_offset: 1,
4873            },
4874            Invisible::Whitespace {
4875                line_offset: tab_size as usize + 3,
4876            },
4877            Invisible::Whitespace {
4878                line_offset: tab_size as usize + 4,
4879            },
4880            Invisible::Whitespace {
4881                line_offset: tab_size as usize + 5,
4882            },
4883        ];
4884        let expected_invisibles = std::iter::once(repeated_invisibles)
4885            .cycle()
4886            .take(9)
4887            .flatten()
4888            .collect::<Vec<_>>();
4889        assert_eq!(
4890            expected_invisibles.len(),
4891            input_text
4892                .chars()
4893                .filter(|initial_char| initial_char.is_whitespace())
4894                .count(),
4895            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
4896        );
4897        info!("Expected invisibles: {expected_invisibles:?}");
4898
4899        init_test(cx, |_| {});
4900
4901        // Put the same string with repeating whitespace pattern into editors of various size,
4902        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
4903        let resize_step = 10.0;
4904        let mut editor_width = 200.0;
4905        while editor_width <= 1000.0 {
4906            update_test_language_settings(cx, |s| {
4907                s.defaults.tab_size = NonZeroU32::new(tab_size);
4908                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4909                s.defaults.preferred_line_length = Some(editor_width as u32);
4910                s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
4911            });
4912
4913            let actual_invisibles = collect_invisibles_from_new_editor(
4914                cx,
4915                EditorMode::Full,
4916                &input_text,
4917                px(editor_width),
4918            );
4919
4920            // Whatever the editor size is, ensure it has the same invisible kinds in the same order
4921            // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
4922            let mut i = 0;
4923            for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
4924                i = actual_index;
4925                match expected_invisibles.get(i) {
4926                    Some(expected_invisible) => match (expected_invisible, actual_invisible) {
4927                        (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
4928                        | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
4929                        _ => {
4930                            panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
4931                        }
4932                    },
4933                    None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
4934                }
4935            }
4936            let missing_expected_invisibles = &expected_invisibles[i + 1..];
4937            assert!(
4938                missing_expected_invisibles.is_empty(),
4939                "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
4940            );
4941
4942            editor_width += resize_step;
4943        }
4944    }
4945
4946    fn collect_invisibles_from_new_editor(
4947        cx: &mut TestAppContext,
4948        editor_mode: EditorMode,
4949        input_text: &str,
4950        editor_width: Pixels,
4951    ) -> Vec<Invisible> {
4952        info!(
4953            "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
4954            editor_width.0
4955        );
4956        let window = cx.add_window(|cx| {
4957            let buffer = MultiBuffer::build_simple(&input_text, cx);
4958            Editor::new(editor_mode, buffer, None, cx)
4959        });
4960        let editor = window.root(cx).unwrap();
4961        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4962        let mut element = EditorElement::new(&editor, style);
4963        window
4964            .update(cx, |editor, cx| {
4965                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
4966                editor.set_wrap_width(Some(editor_width), cx);
4967            })
4968            .unwrap();
4969        let layout_state = cx
4970            .update_window(window.into(), |_, cx| {
4971                cx.with_element_context(|cx| {
4972                    element.after_layout(
4973                        Bounds {
4974                            origin: point(px(500.), px(500.)),
4975                            size: size(px(500.), px(500.)),
4976                        },
4977                        &mut (),
4978                        cx,
4979                    )
4980                })
4981            })
4982            .unwrap();
4983
4984        layout_state
4985            .position_map
4986            .line_layouts
4987            .iter()
4988            .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
4989            .cloned()
4990            .collect()
4991    }
4992}
4993
4994pub fn register_action<T: Action>(
4995    view: &View<Editor>,
4996    cx: &mut WindowContext,
4997    listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
4998) {
4999    let view = view.clone();
5000    cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
5001        let action = action.downcast_ref().unwrap();
5002        if phase == DispatchPhase::Bubble {
5003            view.update(cx, |editor, cx| {
5004                listener(editor, action, cx);
5005            })
5006        }
5007    })
5008}
5009
5010fn compute_auto_height_layout(
5011    editor: &mut Editor,
5012    max_lines: usize,
5013    max_line_number_width: Pixels,
5014    known_dimensions: Size<Option<Pixels>>,
5015    cx: &mut ViewContext<Editor>,
5016) -> Option<Size<Pixels>> {
5017    let width = known_dimensions.width?;
5018    if let Some(height) = known_dimensions.height {
5019        return Some(size(width, height));
5020    }
5021
5022    let style = editor.style.as_ref().unwrap();
5023    let font_id = cx.text_system().resolve_font(&style.text.font());
5024    let font_size = style.text.font_size.to_pixels(cx.rem_size());
5025    let line_height = style.text.line_height_in_pixels(cx.rem_size());
5026    let em_width = cx
5027        .text_system()
5028        .typographic_bounds(font_id, font_size, 'm')
5029        .unwrap()
5030        .size
5031        .width;
5032
5033    let mut snapshot = editor.snapshot(cx);
5034    let gutter_dimensions =
5035        snapshot.gutter_dimensions(font_id, font_size, em_width, max_line_number_width, cx);
5036
5037    editor.gutter_width = gutter_dimensions.width;
5038    let text_width = width - gutter_dimensions.width;
5039    let overscroll = size(em_width, px(0.));
5040
5041    let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
5042    if editor.set_wrap_width(Some(editor_width), cx) {
5043        snapshot = editor.snapshot(cx);
5044    }
5045
5046    let scroll_height = Pixels::from(snapshot.max_point().row() + 1) * line_height;
5047    let height = scroll_height
5048        .max(line_height)
5049        .min(line_height * max_lines as f32);
5050
5051    Some(size(width, height))
5052}