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, 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 line_width = line_layout.line.width;
1145            content_origin.x + line_width + (em_width * INLINE_BLAME_PADDING_EM_WIDTHS)
1146        };
1147
1148        let absolute_offset = point(start_x, start_y);
1149        let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1150
1151        element.layout(absolute_offset, available_space, cx);
1152
1153        Some(element)
1154    }
1155
1156    #[allow(clippy::too_many_arguments)]
1157    fn layout_blame_entries(
1158        &self,
1159        buffer_rows: impl Iterator<Item = Option<u32>>,
1160        em_width: Pixels,
1161        scroll_position: gpui::Point<f32>,
1162        line_height: Pixels,
1163        gutter_hitbox: &Hitbox,
1164        max_width: Option<Pixels>,
1165        cx: &mut ElementContext,
1166    ) -> Option<Vec<AnyElement>> {
1167        if !self
1168            .editor
1169            .update(cx, |editor, cx| editor.render_git_blame_gutter(cx))
1170        {
1171            return None;
1172        }
1173
1174        let blame = self.editor.read(cx).blame.clone()?;
1175        let blamed_rows: Vec<_> = blame.update(cx, |blame, cx| {
1176            blame.blame_for_rows(buffer_rows, cx).collect()
1177        });
1178
1179        let width = if let Some(max_width) = max_width {
1180            AvailableSpace::Definite(max_width)
1181        } else {
1182            AvailableSpace::MaxContent
1183        };
1184        let scroll_top = scroll_position.y * line_height;
1185        let start_x = em_width * 1;
1186
1187        let mut last_used_color: Option<(PlayerColor, Oid)> = None;
1188
1189        let shaped_lines = blamed_rows
1190            .into_iter()
1191            .enumerate()
1192            .flat_map(|(ix, blame_entry)| {
1193                if let Some(blame_entry) = blame_entry {
1194                    let mut element = render_blame_entry(
1195                        ix,
1196                        &blame,
1197                        blame_entry,
1198                        &self.style,
1199                        &mut last_used_color,
1200                        self.editor.clone(),
1201                        cx,
1202                    );
1203
1204                    let start_y = ix as f32 * line_height - (scroll_top % line_height);
1205                    let absolute_offset = gutter_hitbox.origin + point(start_x, start_y);
1206
1207                    element.layout(absolute_offset, size(width, AvailableSpace::MinContent), cx);
1208
1209                    Some(element)
1210                } else {
1211                    None
1212                }
1213            })
1214            .collect();
1215
1216        Some(shaped_lines)
1217    }
1218
1219    fn layout_code_actions_indicator(
1220        &self,
1221        line_height: Pixels,
1222        newest_selection_head: DisplayPoint,
1223        scroll_pixel_position: gpui::Point<Pixels>,
1224        gutter_dimensions: &GutterDimensions,
1225        gutter_hitbox: &Hitbox,
1226        cx: &mut ElementContext,
1227    ) -> Option<AnyElement> {
1228        let mut active = false;
1229        let mut button = None;
1230        self.editor.update(cx, |editor, cx| {
1231            active = matches!(
1232                editor.context_menu.read().as_ref(),
1233                Some(crate::ContextMenu::CodeActions(_))
1234            );
1235            button = editor.render_code_actions_indicator(&self.style, active, cx);
1236        });
1237
1238        let mut button = button?.into_any_element();
1239        let available_space = size(
1240            AvailableSpace::MinContent,
1241            AvailableSpace::Definite(line_height),
1242        );
1243        let indicator_size = button.measure(available_space, cx);
1244
1245        let blame_width = gutter_dimensions
1246            .git_blame_entries_width
1247            .unwrap_or(Pixels::ZERO);
1248
1249        let mut x = blame_width;
1250        let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
1251            - indicator_size.width
1252            - blame_width;
1253        x += available_width / 2.;
1254
1255        let mut y = newest_selection_head.row() as f32 * line_height - scroll_pixel_position.y;
1256        y += (line_height - indicator_size.height) / 2.;
1257
1258        button.layout(gutter_hitbox.origin + point(x, y), available_space, cx);
1259        Some(button)
1260    }
1261
1262    fn calculate_relative_line_numbers(
1263        &self,
1264        buffer_rows: Vec<Option<u32>>,
1265        rows: &Range<u32>,
1266        relative_to: Option<u32>,
1267    ) -> HashMap<u32, u32> {
1268        let mut relative_rows: HashMap<u32, u32> = Default::default();
1269        let Some(relative_to) = relative_to else {
1270            return relative_rows;
1271        };
1272
1273        let start = rows.start.min(relative_to);
1274
1275        let head_idx = relative_to - start;
1276        let mut delta = 1;
1277        let mut i = head_idx + 1;
1278        while i < buffer_rows.len() as u32 {
1279            if buffer_rows[i as usize].is_some() {
1280                if rows.contains(&(i + start)) {
1281                    relative_rows.insert(i + start, delta);
1282                }
1283                delta += 1;
1284            }
1285            i += 1;
1286        }
1287        delta = 1;
1288        i = head_idx.min(buffer_rows.len() as u32 - 1);
1289        while i > 0 && buffer_rows[i as usize].is_none() {
1290            i -= 1;
1291        }
1292
1293        while i > 0 {
1294            i -= 1;
1295            if buffer_rows[i as usize].is_some() {
1296                if rows.contains(&(i + start)) {
1297                    relative_rows.insert(i + start, delta);
1298                }
1299                delta += 1;
1300            }
1301        }
1302
1303        relative_rows
1304    }
1305
1306    fn layout_line_numbers(
1307        &self,
1308        rows: Range<u32>,
1309        buffer_rows: impl Iterator<Item = Option<u32>>,
1310        active_rows: &BTreeMap<u32, bool>,
1311        newest_selection_head: Option<DisplayPoint>,
1312        snapshot: &EditorSnapshot,
1313        cx: &ElementContext,
1314    ) -> (
1315        Vec<Option<ShapedLine>>,
1316        Vec<Option<(FoldStatus, BufferRow, bool)>>,
1317    ) {
1318        let editor = self.editor.read(cx);
1319        let is_singleton = editor.is_singleton(cx);
1320        let newest_selection_head = newest_selection_head.unwrap_or_else(|| {
1321            let newest = editor.selections.newest::<Point>(cx);
1322            SelectionLayout::new(
1323                newest,
1324                editor.selections.line_mode,
1325                editor.cursor_shape,
1326                &snapshot.display_snapshot,
1327                true,
1328                true,
1329                None,
1330            )
1331            .head
1332        });
1333        let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1334        let include_line_numbers =
1335            EditorSettings::get_global(cx).gutter.line_numbers && snapshot.mode == EditorMode::Full;
1336        let include_fold_statuses =
1337            EditorSettings::get_global(cx).gutter.folds && snapshot.mode == EditorMode::Full;
1338        let mut shaped_line_numbers = Vec::with_capacity(rows.len());
1339        let mut fold_statuses = Vec::with_capacity(rows.len());
1340        let mut line_number = String::new();
1341        let is_relative = EditorSettings::get_global(cx).relative_line_numbers;
1342        let relative_to = if is_relative {
1343            Some(newest_selection_head.row())
1344        } else {
1345            None
1346        };
1347
1348        let buffer_rows = buffer_rows.collect::<Vec<_>>();
1349        let relative_rows =
1350            self.calculate_relative_line_numbers(buffer_rows.clone(), &rows, relative_to);
1351
1352        for (ix, row) in buffer_rows.into_iter().enumerate() {
1353            let display_row = rows.start + ix as u32;
1354            let (active, color) = if active_rows.contains_key(&display_row) {
1355                (true, cx.theme().colors().editor_active_line_number)
1356            } else {
1357                (false, cx.theme().colors().editor_line_number)
1358            };
1359            if let Some(buffer_row) = row {
1360                if include_line_numbers {
1361                    line_number.clear();
1362                    let default_number = buffer_row + 1;
1363                    let number = relative_rows
1364                        .get(&(ix as u32 + rows.start))
1365                        .unwrap_or(&default_number);
1366                    write!(&mut line_number, "{}", number).unwrap();
1367                    let run = TextRun {
1368                        len: line_number.len(),
1369                        font: self.style.text.font(),
1370                        color,
1371                        background_color: None,
1372                        underline: None,
1373                        strikethrough: None,
1374                    };
1375                    let shaped_line = cx
1376                        .text_system()
1377                        .shape_line(line_number.clone().into(), font_size, &[run])
1378                        .unwrap();
1379                    shaped_line_numbers.push(Some(shaped_line));
1380                }
1381                if include_fold_statuses {
1382                    fold_statuses.push(
1383                        is_singleton
1384                            .then(|| {
1385                                snapshot
1386                                    .fold_for_line(buffer_row)
1387                                    .map(|fold_status| (fold_status, buffer_row, active))
1388                            })
1389                            .flatten(),
1390                    )
1391                }
1392            } else {
1393                fold_statuses.push(None);
1394                shaped_line_numbers.push(None);
1395            }
1396        }
1397
1398        (shaped_line_numbers, fold_statuses)
1399    }
1400
1401    fn layout_lines(
1402        &self,
1403        rows: Range<u32>,
1404        line_number_layouts: &[Option<ShapedLine>],
1405        snapshot: &EditorSnapshot,
1406        cx: &ElementContext,
1407    ) -> Vec<LineWithInvisibles> {
1408        if rows.start >= rows.end {
1409            return Vec::new();
1410        }
1411
1412        // Show the placeholder when the editor is empty
1413        if snapshot.is_empty() {
1414            let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1415            let placeholder_color = cx.theme().colors().text_placeholder;
1416            let placeholder_text = snapshot.placeholder_text();
1417
1418            let placeholder_lines = placeholder_text
1419                .as_ref()
1420                .map_or("", AsRef::as_ref)
1421                .split('\n')
1422                .skip(rows.start as usize)
1423                .chain(iter::repeat(""))
1424                .take(rows.len());
1425            placeholder_lines
1426                .filter_map(move |line| {
1427                    let run = TextRun {
1428                        len: line.len(),
1429                        font: self.style.text.font(),
1430                        color: placeholder_color,
1431                        background_color: None,
1432                        underline: Default::default(),
1433                        strikethrough: None,
1434                    };
1435                    cx.text_system()
1436                        .shape_line(line.to_string().into(), font_size, &[run])
1437                        .log_err()
1438                })
1439                .map(|line| LineWithInvisibles {
1440                    line,
1441                    invisibles: Vec::new(),
1442                })
1443                .collect()
1444        } else {
1445            let chunks = snapshot.highlighted_chunks(rows.clone(), true, &self.style);
1446            LineWithInvisibles::from_chunks(
1447                chunks,
1448                &self.style.text,
1449                MAX_LINE_LEN,
1450                rows.len(),
1451                line_number_layouts,
1452                snapshot.mode,
1453                cx,
1454            )
1455        }
1456    }
1457
1458    #[allow(clippy::too_many_arguments)]
1459    fn build_blocks(
1460        &self,
1461        rows: Range<u32>,
1462        snapshot: &EditorSnapshot,
1463        hitbox: &Hitbox,
1464        text_hitbox: &Hitbox,
1465        scroll_width: &mut Pixels,
1466        gutter_dimensions: &GutterDimensions,
1467        em_width: Pixels,
1468        text_x: Pixels,
1469        line_height: Pixels,
1470        line_layouts: &[LineWithInvisibles],
1471        cx: &mut ElementContext,
1472    ) -> Vec<BlockLayout> {
1473        let mut block_id = 0;
1474        let (fixed_blocks, non_fixed_blocks) = snapshot
1475            .blocks_in_range(rows.clone())
1476            .partition::<Vec<_>, _>(|(_, block)| match block {
1477                TransformBlock::ExcerptHeader { .. } => false,
1478                TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
1479            });
1480
1481        let render_block = |block: &TransformBlock,
1482                            available_space: Size<AvailableSpace>,
1483                            block_id: usize,
1484                            block_row_start: u32,
1485                            cx: &mut ElementContext| {
1486            let mut element = match block {
1487                TransformBlock::Custom(block) => {
1488                    let align_to = block
1489                        .position()
1490                        .to_point(&snapshot.buffer_snapshot)
1491                        .to_display_point(snapshot);
1492                    let anchor_x = text_x
1493                        + if rows.contains(&align_to.row()) {
1494                            line_layouts[(align_to.row() - rows.start) as usize]
1495                                .line
1496                                .x_for_index(align_to.column() as usize)
1497                        } else {
1498                            layout_line(align_to.row(), snapshot, &self.style, cx)
1499                                .unwrap()
1500                                .x_for_index(align_to.column() as usize)
1501                        };
1502
1503                    block.render(&mut BlockContext {
1504                        context: cx,
1505                        anchor_x,
1506                        gutter_dimensions,
1507                        line_height,
1508                        em_width,
1509                        block_id,
1510                        max_width: text_hitbox.size.width.max(*scroll_width),
1511                        editor_style: &self.style,
1512                    })
1513                }
1514
1515                TransformBlock::ExcerptHeader {
1516                    buffer,
1517                    range,
1518                    starts_new_buffer,
1519                    height,
1520                    ..
1521                } => {
1522                    let include_root = self
1523                        .editor
1524                        .read(cx)
1525                        .project
1526                        .as_ref()
1527                        .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
1528                        .unwrap_or_default();
1529
1530                    #[derive(Clone)]
1531                    struct JumpData {
1532                        position: Point,
1533                        anchor: text::Anchor,
1534                        path: ProjectPath,
1535                        line_offset_from_top: u32,
1536                    }
1537
1538                    let jump_data = project::File::from_dyn(buffer.file()).map(|file| {
1539                        let jump_path = ProjectPath {
1540                            worktree_id: file.worktree_id(cx),
1541                            path: file.path.clone(),
1542                        };
1543                        let jump_anchor = range
1544                            .primary
1545                            .as_ref()
1546                            .map_or(range.context.start, |primary| primary.start);
1547
1548                        let excerpt_start = range.context.start;
1549                        let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
1550                        let offset_from_excerpt_start = if jump_anchor == excerpt_start {
1551                            0
1552                        } else {
1553                            let excerpt_start_row =
1554                                language::ToPoint::to_point(&jump_anchor, buffer).row;
1555                            jump_position.row - excerpt_start_row
1556                        };
1557
1558                        let line_offset_from_top =
1559                            block_row_start + *height as u32 + offset_from_excerpt_start
1560                                - snapshot
1561                                    .scroll_anchor
1562                                    .scroll_position(&snapshot.display_snapshot)
1563                                    .y as u32;
1564
1565                        JumpData {
1566                            position: jump_position,
1567                            anchor: jump_anchor,
1568                            path: jump_path,
1569                            line_offset_from_top,
1570                        }
1571                    });
1572
1573                    let element = if *starts_new_buffer {
1574                        let path = buffer.resolve_file_path(cx, include_root);
1575                        let mut filename = None;
1576                        let mut parent_path = None;
1577                        // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
1578                        if let Some(path) = path {
1579                            filename = path.file_name().map(|f| f.to_string_lossy().to_string());
1580                            parent_path = path
1581                                .parent()
1582                                .map(|p| SharedString::from(p.to_string_lossy().to_string() + "/"));
1583                        }
1584
1585                        v_flex()
1586                            .id(("path header container", block_id))
1587                            .size_full()
1588                            .justify_center()
1589                            .p(gpui::px(6.))
1590                            .child(
1591                                h_flex()
1592                                    .id("path header block")
1593                                    .size_full()
1594                                    .pl(gpui::px(12.))
1595                                    .pr(gpui::px(8.))
1596                                    .rounded_md()
1597                                    .shadow_md()
1598                                    .border()
1599                                    .border_color(cx.theme().colors().border)
1600                                    .bg(cx.theme().colors().editor_subheader_background)
1601                                    .justify_between()
1602                                    .hover(|style| style.bg(cx.theme().colors().element_hover))
1603                                    .child(
1604                                        h_flex().gap_3().child(
1605                                            h_flex()
1606                                                .gap_2()
1607                                                .child(
1608                                                    filename
1609                                                        .map(SharedString::from)
1610                                                        .unwrap_or_else(|| "untitled".into()),
1611                                                )
1612                                                .when_some(parent_path, |then, path| {
1613                                                    then.child(
1614                                                        div().child(path).text_color(
1615                                                            cx.theme().colors().text_muted,
1616                                                        ),
1617                                                    )
1618                                                }),
1619                                        ),
1620                                    )
1621                                    .when_some(jump_data.clone(), |this, jump_data| {
1622                                        this.cursor_pointer()
1623                                            .tooltip(|cx| {
1624                                                Tooltip::for_action(
1625                                                    "Jump to File",
1626                                                    &OpenExcerpts,
1627                                                    cx,
1628                                                )
1629                                            })
1630                                            .on_mouse_down(MouseButton::Left, |_, cx| {
1631                                                cx.stop_propagation()
1632                                            })
1633                                            .on_click(cx.listener_for(&self.editor, {
1634                                                move |editor, _, cx| {
1635                                                    editor.jump(
1636                                                        jump_data.path.clone(),
1637                                                        jump_data.position,
1638                                                        jump_data.anchor,
1639                                                        jump_data.line_offset_from_top,
1640                                                        cx,
1641                                                    );
1642                                                }
1643                                            }))
1644                                    }),
1645                            )
1646                    } else {
1647                        v_flex()
1648                            .id(("collapsed context", block_id))
1649                            .size_full()
1650                            .child(
1651                                div()
1652                                    .flex()
1653                                    .v_flex()
1654                                    .justify_start()
1655                                    .id("jump to collapsed context")
1656                                    .w(relative(1.0))
1657                                    .h_full()
1658                                    .child(
1659                                        div()
1660                                            .h_px()
1661                                            .w_full()
1662                                            .bg(cx.theme().colors().border_variant)
1663                                            .group_hover("excerpt-jump-action", |style| {
1664                                                style.bg(cx.theme().colors().border)
1665                                            }),
1666                                    ),
1667                            )
1668                            .child(
1669                                h_flex()
1670                                    .justify_end()
1671                                    .flex_none()
1672                                    .w(
1673                                        gutter_dimensions.width - (gutter_dimensions.left_padding), // + gutter_dimensions.right_padding)
1674                                    )
1675                                    .h_full()
1676                                    .child(
1677                                        ButtonLike::new("jump-icon")
1678                                            .style(ButtonStyle::Transparent)
1679                                            .child(
1680                                                svg()
1681                                                    .path(IconName::ArrowUpRight.path())
1682                                                    .size(IconSize::XSmall.rems())
1683                                                    .text_color(cx.theme().colors().border)
1684                                                    .group_hover("excerpt-jump-action", |style| {
1685                                                        style.text_color(
1686                                                            cx.theme().colors().editor_line_number,
1687                                                        )
1688                                                    }),
1689                                            )
1690                                            .when_some(jump_data.clone(), |this, jump_data| {
1691                                                this.on_click(cx.listener_for(&self.editor, {
1692                                                    let path = jump_data.path.clone();
1693                                                    move |editor, _, cx| {
1694                                                        editor.jump(
1695                                                            path.clone(),
1696                                                            jump_data.position,
1697                                                            jump_data.anchor,
1698                                                            jump_data.line_offset_from_top,
1699                                                            cx,
1700                                                        );
1701                                                    }
1702                                                }))
1703                                                .tooltip({
1704                                                    move |cx| {
1705                                                        Tooltip::for_action(
1706                                                            format!(
1707                                                                "Jump to {}:L{}",
1708                                                                jump_data.path.path.display(),
1709                                                                jump_data.position.row + 1
1710                                                            ),
1711                                                            &OpenExcerpts,
1712                                                            cx,
1713                                                        )
1714                                                    }
1715                                                })
1716                                            }),
1717                                    ),
1718                            )
1719                            .group("excerpt-jump-action")
1720                            .cursor_pointer()
1721                            .when_some(jump_data.clone(), |this, jump_data| {
1722                                this.on_click(cx.listener_for(&self.editor, {
1723                                    let path = jump_data.path.clone();
1724                                    move |editor, _, cx| {
1725                                        cx.stop_propagation();
1726
1727                                        editor.jump(
1728                                            path.clone(),
1729                                            jump_data.position,
1730                                            jump_data.anchor,
1731                                            jump_data.line_offset_from_top,
1732                                            cx,
1733                                        );
1734                                    }
1735                                }))
1736                                .tooltip(move |cx| {
1737                                    Tooltip::for_action(
1738                                        format!(
1739                                            "Jump to {}:L{}",
1740                                            jump_data.path.path.display(),
1741                                            jump_data.position.row + 1
1742                                        ),
1743                                        &OpenExcerpts,
1744                                        cx,
1745                                    )
1746                                })
1747                            })
1748                    };
1749                    element.into_any()
1750                }
1751            };
1752
1753            let size = element.measure(available_space, cx);
1754            (element, size)
1755        };
1756
1757        let mut fixed_block_max_width = Pixels::ZERO;
1758        let mut blocks = Vec::new();
1759        for (row, block) in fixed_blocks {
1760            let available_space = size(
1761                AvailableSpace::MinContent,
1762                AvailableSpace::Definite(block.height() as f32 * line_height),
1763            );
1764            let (element, element_size) = render_block(block, available_space, block_id, row, cx);
1765            block_id += 1;
1766            fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
1767            blocks.push(BlockLayout {
1768                row,
1769                element,
1770                available_space,
1771                style: BlockStyle::Fixed,
1772            });
1773        }
1774        for (row, block) in non_fixed_blocks {
1775            let style = match block {
1776                TransformBlock::Custom(block) => block.style(),
1777                TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
1778            };
1779            let width = match style {
1780                BlockStyle::Sticky => hitbox.size.width,
1781                BlockStyle::Flex => hitbox
1782                    .size
1783                    .width
1784                    .max(fixed_block_max_width)
1785                    .max(gutter_dimensions.width + *scroll_width),
1786                BlockStyle::Fixed => unreachable!(),
1787            };
1788            let available_space = size(
1789                AvailableSpace::Definite(width),
1790                AvailableSpace::Definite(block.height() as f32 * line_height),
1791            );
1792            let (element, _) = render_block(block, available_space, block_id, row, cx);
1793            block_id += 1;
1794            blocks.push(BlockLayout {
1795                row,
1796                element,
1797                available_space,
1798                style,
1799            });
1800        }
1801
1802        *scroll_width = (*scroll_width).max(fixed_block_max_width - gutter_dimensions.width);
1803        blocks
1804    }
1805
1806    fn layout_blocks(
1807        &self,
1808        blocks: &mut Vec<BlockLayout>,
1809        hitbox: &Hitbox,
1810        line_height: Pixels,
1811        scroll_pixel_position: gpui::Point<Pixels>,
1812        cx: &mut ElementContext,
1813    ) {
1814        for block in blocks {
1815            let mut origin = hitbox.origin
1816                + point(
1817                    Pixels::ZERO,
1818                    block.row as f32 * line_height - scroll_pixel_position.y,
1819                );
1820            if !matches!(block.style, BlockStyle::Sticky) {
1821                origin += point(-scroll_pixel_position.x, Pixels::ZERO);
1822            }
1823            block.element.layout(origin, block.available_space, cx);
1824        }
1825    }
1826
1827    #[allow(clippy::too_many_arguments)]
1828    fn layout_context_menu(
1829        &self,
1830        line_height: Pixels,
1831        hitbox: &Hitbox,
1832        text_hitbox: &Hitbox,
1833        content_origin: gpui::Point<Pixels>,
1834        start_row: u32,
1835        scroll_pixel_position: gpui::Point<Pixels>,
1836        line_layouts: &[LineWithInvisibles],
1837        newest_selection_head: DisplayPoint,
1838        cx: &mut ElementContext,
1839    ) -> bool {
1840        let max_height = cmp::min(
1841            12. * line_height,
1842            cmp::max(3. * line_height, (hitbox.size.height - line_height) / 2.),
1843        );
1844        let Some((position, mut context_menu)) = self.editor.update(cx, |editor, cx| {
1845            if editor.context_menu_visible() {
1846                editor.render_context_menu(newest_selection_head, &self.style, max_height, cx)
1847            } else {
1848                None
1849            }
1850        }) else {
1851            return false;
1852        };
1853
1854        let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1855        let context_menu_size = context_menu.measure(available_space, cx);
1856
1857        let cursor_row_layout = &line_layouts[(position.row() - start_row) as usize].line;
1858        let x = cursor_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
1859        let y = (position.row() + 1) as f32 * line_height - scroll_pixel_position.y;
1860        let mut list_origin = content_origin + point(x, y);
1861        let list_width = context_menu_size.width;
1862        let list_height = context_menu_size.height;
1863
1864        // Snap the right edge of the list to the right edge of the window if
1865        // its horizontal bounds overflow.
1866        if list_origin.x + list_width > cx.viewport_size().width {
1867            list_origin.x = (cx.viewport_size().width - list_width).max(Pixels::ZERO);
1868        }
1869
1870        if list_origin.y + list_height > text_hitbox.lower_right().y {
1871            list_origin.y -= line_height + list_height;
1872        }
1873
1874        cx.defer_draw(context_menu, list_origin, 1);
1875        true
1876    }
1877
1878    fn layout_mouse_context_menu(&self, cx: &mut ElementContext) -> Option<AnyElement> {
1879        let mouse_context_menu = self.editor.read(cx).mouse_context_menu.as_ref()?;
1880        let mut element = deferred(
1881            anchored()
1882                .position(mouse_context_menu.position)
1883                .child(mouse_context_menu.context_menu.clone())
1884                .anchor(AnchorCorner::TopLeft)
1885                .snap_to_window(),
1886        )
1887        .with_priority(1)
1888        .into_any();
1889
1890        element.layout(gpui::Point::default(), AvailableSpace::min_size(), cx);
1891        Some(element)
1892    }
1893
1894    #[allow(clippy::too_many_arguments)]
1895    fn layout_hover_popovers(
1896        &self,
1897        snapshot: &EditorSnapshot,
1898        hitbox: &Hitbox,
1899        text_hitbox: &Hitbox,
1900        visible_display_row_range: Range<u32>,
1901        content_origin: gpui::Point<Pixels>,
1902        scroll_pixel_position: gpui::Point<Pixels>,
1903        line_layouts: &[LineWithInvisibles],
1904        line_height: Pixels,
1905        em_width: Pixels,
1906        cx: &mut ElementContext,
1907    ) {
1908        struct MeasuredHoverPopover {
1909            element: AnyElement,
1910            size: Size<Pixels>,
1911            horizontal_offset: Pixels,
1912        }
1913
1914        let max_size = size(
1915            (120. * em_width) // Default size
1916                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
1917                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
1918            (16. * line_height) // Default size
1919                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
1920                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
1921        );
1922
1923        let hover_popovers = self.editor.update(cx, |editor, cx| {
1924            editor.hover_state.render(
1925                &snapshot,
1926                &self.style,
1927                visible_display_row_range.clone(),
1928                max_size,
1929                editor.workspace.as_ref().map(|(w, _)| w.clone()),
1930                cx,
1931            )
1932        });
1933        let Some((position, hover_popovers)) = hover_popovers else {
1934            return;
1935        };
1936
1937        let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1938
1939        // This is safe because we check on layout whether the required row is available
1940        let hovered_row_layout =
1941            &line_layouts[(position.row() - visible_display_row_range.start) as usize].line;
1942
1943        // Compute Hovered Point
1944        let x =
1945            hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
1946        let y = position.row() as f32 * line_height - scroll_pixel_position.y;
1947        let hovered_point = content_origin + point(x, y);
1948
1949        let mut overall_height = Pixels::ZERO;
1950        let mut measured_hover_popovers = Vec::new();
1951        for mut hover_popover in hover_popovers {
1952            let size = hover_popover.measure(available_space, cx);
1953            let horizontal_offset =
1954                (text_hitbox.upper_right().x - (hovered_point.x + size.width)).min(Pixels::ZERO);
1955
1956            overall_height += HOVER_POPOVER_GAP + size.height;
1957
1958            measured_hover_popovers.push(MeasuredHoverPopover {
1959                element: hover_popover,
1960                size,
1961                horizontal_offset,
1962            });
1963        }
1964        overall_height += HOVER_POPOVER_GAP;
1965
1966        fn draw_occluder(width: Pixels, origin: gpui::Point<Pixels>, cx: &mut ElementContext) {
1967            let mut occlusion = div()
1968                .size_full()
1969                .occlude()
1970                .on_mouse_move(|_, cx| cx.stop_propagation())
1971                .into_any_element();
1972            occlusion.measure(size(width, HOVER_POPOVER_GAP).into(), cx);
1973            cx.defer_draw(occlusion, origin, 2);
1974        }
1975
1976        if hovered_point.y > overall_height {
1977            // There is enough space above. Render popovers above the hovered point
1978            let mut current_y = hovered_point.y;
1979            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
1980                let size = popover.size;
1981                let popover_origin = point(
1982                    hovered_point.x + popover.horizontal_offset,
1983                    current_y - size.height,
1984                );
1985
1986                cx.defer_draw(popover.element, popover_origin, 2);
1987                if position != itertools::Position::Last {
1988                    let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
1989                    draw_occluder(size.width, origin, cx);
1990                }
1991
1992                current_y = popover_origin.y - HOVER_POPOVER_GAP;
1993            }
1994        } else {
1995            // There is not enough space above. Render popovers below the hovered point
1996            let mut current_y = hovered_point.y + line_height;
1997            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
1998                let size = popover.size;
1999                let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
2000
2001                cx.defer_draw(popover.element, popover_origin, 2);
2002                if position != itertools::Position::Last {
2003                    let origin = point(popover_origin.x, popover_origin.y + size.height);
2004                    draw_occluder(size.width, origin, cx);
2005                }
2006
2007                current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
2008            }
2009        }
2010    }
2011
2012    fn paint_background(&self, layout: &EditorLayout, cx: &mut ElementContext) {
2013        cx.paint_layer(layout.hitbox.bounds, |cx| {
2014            let scroll_top = layout.position_map.snapshot.scroll_position().y;
2015            let gutter_bg = cx.theme().colors().editor_gutter_background;
2016            cx.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
2017            cx.paint_quad(fill(layout.text_hitbox.bounds, self.style.background));
2018
2019            if let EditorMode::Full = layout.mode {
2020                let mut active_rows = layout.active_rows.iter().peekable();
2021                while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
2022                    let mut end_row = *start_row;
2023                    while active_rows.peek().map_or(false, |r| {
2024                        *r.0 == end_row + 1 && r.1 == contains_non_empty_selection
2025                    }) {
2026                        active_rows.next().unwrap();
2027                        end_row += 1;
2028                    }
2029
2030                    if !contains_non_empty_selection {
2031                        let origin = point(
2032                            layout.hitbox.origin.x,
2033                            layout.hitbox.origin.y
2034                                + (*start_row as f32 - scroll_top)
2035                                    * layout.position_map.line_height,
2036                        );
2037                        let size = size(
2038                            layout.hitbox.size.width,
2039                            layout.position_map.line_height * (end_row - start_row + 1) as f32,
2040                        );
2041                        let active_line_bg = cx.theme().colors().editor_active_line_background;
2042                        cx.paint_quad(fill(Bounds { origin, size }, active_line_bg));
2043                    }
2044                }
2045
2046                let mut paint_highlight =
2047                    |highlight_row_start: u32, highlight_row_end: u32, color| {
2048                        let origin = point(
2049                            layout.hitbox.origin.x,
2050                            layout.hitbox.origin.y
2051                                + (highlight_row_start as f32 - scroll_top)
2052                                    * layout.position_map.line_height,
2053                        );
2054                        let size = size(
2055                            layout.hitbox.size.width,
2056                            layout.position_map.line_height
2057                                * (highlight_row_end + 1 - highlight_row_start) as f32,
2058                        );
2059                        cx.paint_quad(fill(Bounds { origin, size }, color));
2060                    };
2061
2062                let mut last_row = None;
2063                let mut highlight_row_start = 0u32;
2064                let mut highlight_row_end = 0u32;
2065                for (&row, &color) in &layout.highlighted_rows {
2066                    let paint = last_row.map_or(false, |(last_row, last_color)| {
2067                        last_color != color || last_row + 1 < row
2068                    });
2069
2070                    if paint {
2071                        let paint_range_is_unfinished = highlight_row_end == 0;
2072                        if paint_range_is_unfinished {
2073                            highlight_row_end = row;
2074                            last_row = None;
2075                        }
2076                        paint_highlight(highlight_row_start, highlight_row_end, color);
2077                        highlight_row_start = 0;
2078                        highlight_row_end = 0;
2079                        if !paint_range_is_unfinished {
2080                            highlight_row_start = row;
2081                            last_row = Some((row, color));
2082                        }
2083                    } else {
2084                        if last_row.is_none() {
2085                            highlight_row_start = row;
2086                        } else {
2087                            highlight_row_end = row;
2088                        }
2089                        last_row = Some((row, color));
2090                    }
2091                }
2092                if let Some((row, hsla)) = last_row {
2093                    highlight_row_end = row;
2094                    paint_highlight(highlight_row_start, highlight_row_end, hsla);
2095                }
2096
2097                let scroll_left =
2098                    layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
2099
2100                for (wrap_position, active) in layout.wrap_guides.iter() {
2101                    let x = (layout.text_hitbox.origin.x
2102                        + *wrap_position
2103                        + layout.position_map.em_width / 2.)
2104                        - scroll_left;
2105
2106                    let show_scrollbars = layout
2107                        .scrollbar_layout
2108                        .as_ref()
2109                        .map_or(false, |scrollbar| scrollbar.visible);
2110                    if x < layout.text_hitbox.origin.x
2111                        || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
2112                    {
2113                        continue;
2114                    }
2115
2116                    let color = if *active {
2117                        cx.theme().colors().editor_active_wrap_guide
2118                    } else {
2119                        cx.theme().colors().editor_wrap_guide
2120                    };
2121                    cx.paint_quad(fill(
2122                        Bounds {
2123                            origin: point(x, layout.text_hitbox.origin.y),
2124                            size: size(px(1.), layout.text_hitbox.size.height),
2125                        },
2126                        color,
2127                    ));
2128                }
2129            }
2130        })
2131    }
2132
2133    fn paint_gutter(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2134        let line_height = layout.position_map.line_height;
2135
2136        let scroll_position = layout.position_map.snapshot.scroll_position();
2137        let scroll_top = scroll_position.y * line_height;
2138
2139        cx.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
2140
2141        let show_git_gutter = matches!(
2142            ProjectSettings::get_global(cx).git.git_gutter,
2143            Some(GitGutterSetting::TrackedFiles)
2144        );
2145
2146        if show_git_gutter {
2147            Self::paint_diff_hunks(layout, cx);
2148        }
2149
2150        if layout.blamed_display_rows.is_some() {
2151            self.paint_blamed_display_rows(layout, cx);
2152        }
2153
2154        for (ix, line) in layout.line_numbers.iter().enumerate() {
2155            if let Some(line) = line {
2156                let line_origin = layout.gutter_hitbox.origin
2157                    + point(
2158                        layout.gutter_hitbox.size.width
2159                            - line.width
2160                            - layout.gutter_dimensions.right_padding,
2161                        ix as f32 * line_height - (scroll_top % line_height),
2162                    );
2163
2164                line.paint(line_origin, line_height, cx).log_err();
2165            }
2166        }
2167
2168        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2169            cx.with_element_id(Some("gutter_fold_indicators"), |cx| {
2170                for fold_indicator in layout.fold_indicators.iter_mut().flatten() {
2171                    fold_indicator.paint(cx);
2172                }
2173            });
2174
2175            if let Some(indicator) = layout.code_actions_indicator.as_mut() {
2176                indicator.paint(cx);
2177            }
2178        })
2179    }
2180
2181    fn paint_diff_hunks(layout: &EditorLayout, cx: &mut ElementContext) {
2182        if layout.display_hunks.is_empty() {
2183            return;
2184        }
2185
2186        let line_height = layout.position_map.line_height;
2187
2188        let scroll_position = layout.position_map.snapshot.scroll_position();
2189        let scroll_top = scroll_position.y * line_height;
2190
2191        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2192            for hunk in &layout.display_hunks {
2193                let (display_row_range, status) = match hunk {
2194                    //TODO: This rendering is entirely a horrible hack
2195                    &DisplayDiffHunk::Folded { display_row: row } => {
2196                        let start_y = row as f32 * line_height - scroll_top;
2197                        let end_y = start_y + line_height;
2198
2199                        let width = 0.275 * line_height;
2200                        let highlight_origin = layout.gutter_hitbox.origin + point(-width, start_y);
2201                        let highlight_size = size(width * 2., end_y - start_y);
2202                        let highlight_bounds = Bounds::new(highlight_origin, highlight_size);
2203                        cx.paint_quad(quad(
2204                            highlight_bounds,
2205                            Corners::all(1. * line_height),
2206                            cx.theme().status().modified,
2207                            Edges::default(),
2208                            transparent_black(),
2209                        ));
2210
2211                        continue;
2212                    }
2213
2214                    DisplayDiffHunk::Unfolded {
2215                        display_row_range,
2216                        status,
2217                    } => (display_row_range, status),
2218                };
2219
2220                let color = match status {
2221                    DiffHunkStatus::Added => cx.theme().status().created,
2222                    DiffHunkStatus::Modified => cx.theme().status().modified,
2223
2224                    //TODO: This rendering is entirely a horrible hack
2225                    DiffHunkStatus::Removed => {
2226                        let row = display_row_range.start;
2227
2228                        let offset = line_height / 2.;
2229                        let start_y = row as f32 * line_height - offset - scroll_top;
2230                        let end_y = start_y + line_height;
2231
2232                        let width = 0.275 * line_height;
2233                        let highlight_origin = layout.gutter_hitbox.origin + point(-width, start_y);
2234                        let highlight_size = size(width * 2., end_y - start_y);
2235                        let highlight_bounds = Bounds::new(highlight_origin, highlight_size);
2236                        cx.paint_quad(quad(
2237                            highlight_bounds,
2238                            Corners::all(1. * line_height),
2239                            cx.theme().status().deleted,
2240                            Edges::default(),
2241                            transparent_black(),
2242                        ));
2243
2244                        continue;
2245                    }
2246                };
2247
2248                let start_row = display_row_range.start;
2249                let end_row = display_row_range.end;
2250                // If we're in a multibuffer, row range span might include an
2251                // excerpt header, so if we were to draw the marker straight away,
2252                // the hunk might include the rows of that header.
2253                // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
2254                // Instead, we simply check whether the range we're dealing with includes
2255                // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
2256                let end_row_in_current_excerpt = layout
2257                    .position_map
2258                    .snapshot
2259                    .blocks_in_range(start_row..end_row)
2260                    .find_map(|(start_row, block)| {
2261                        if matches!(block, TransformBlock::ExcerptHeader { .. }) {
2262                            Some(start_row)
2263                        } else {
2264                            None
2265                        }
2266                    })
2267                    .unwrap_or(end_row);
2268
2269                let start_y = start_row as f32 * line_height - scroll_top;
2270                let end_y = end_row_in_current_excerpt as f32 * line_height - scroll_top;
2271
2272                let width = 0.275 * line_height;
2273                let highlight_origin = layout.gutter_hitbox.origin + point(-width, start_y);
2274                let highlight_size = size(width * 2., end_y - start_y);
2275                let highlight_bounds = Bounds::new(highlight_origin, highlight_size);
2276                cx.paint_quad(quad(
2277                    highlight_bounds,
2278                    Corners::all(0.05 * line_height),
2279                    color,
2280                    Edges::default(),
2281                    transparent_black(),
2282                ));
2283            }
2284        })
2285    }
2286
2287    fn paint_blamed_display_rows(&self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2288        let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
2289            return;
2290        };
2291
2292        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2293            for mut blame_element in blamed_display_rows.into_iter() {
2294                blame_element.paint(cx);
2295            }
2296        })
2297    }
2298
2299    fn paint_text(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2300        cx.with_content_mask(
2301            Some(ContentMask {
2302                bounds: layout.text_hitbox.bounds,
2303            }),
2304            |cx| {
2305                let cursor_style = if self
2306                    .editor
2307                    .read(cx)
2308                    .hovered_link_state
2309                    .as_ref()
2310                    .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
2311                {
2312                    CursorStyle::PointingHand
2313                } else {
2314                    CursorStyle::IBeam
2315                };
2316                cx.set_cursor_style(cursor_style, &layout.text_hitbox);
2317
2318                cx.with_element_id(Some("folds"), |cx| self.paint_folds(layout, cx));
2319                let invisible_display_ranges = self.paint_highlights(layout, cx);
2320                self.paint_lines(&invisible_display_ranges, layout, cx);
2321                self.paint_redactions(layout, cx);
2322                self.paint_cursors(layout, cx);
2323                self.paint_inline_blame(layout, cx);
2324            },
2325        )
2326    }
2327
2328    fn paint_highlights(
2329        &mut self,
2330        layout: &mut EditorLayout,
2331        cx: &mut ElementContext,
2332    ) -> SmallVec<[Range<DisplayPoint>; 32]> {
2333        cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2334            let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
2335            let line_end_overshoot = 0.15 * layout.position_map.line_height;
2336            for (range, color) in &layout.highlighted_ranges {
2337                self.paint_highlighted_range(
2338                    range.clone(),
2339                    *color,
2340                    Pixels::ZERO,
2341                    line_end_overshoot,
2342                    layout,
2343                    cx,
2344                );
2345            }
2346
2347            let corner_radius = 0.15 * layout.position_map.line_height;
2348
2349            for (player_color, selections) in &layout.selections {
2350                for selection in selections.into_iter() {
2351                    self.paint_highlighted_range(
2352                        selection.range.clone(),
2353                        player_color.selection,
2354                        corner_radius,
2355                        corner_radius * 2.,
2356                        layout,
2357                        cx,
2358                    );
2359
2360                    if selection.is_local && !selection.range.is_empty() {
2361                        invisible_display_ranges.push(selection.range.clone());
2362                    }
2363                }
2364            }
2365            invisible_display_ranges
2366        })
2367    }
2368
2369    fn paint_lines(
2370        &mut self,
2371        invisible_display_ranges: &[Range<DisplayPoint>],
2372        layout: &EditorLayout,
2373        cx: &mut ElementContext,
2374    ) {
2375        let whitespace_setting = self
2376            .editor
2377            .read(cx)
2378            .buffer
2379            .read(cx)
2380            .settings_at(0, cx)
2381            .show_whitespaces;
2382
2383        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
2384            let row = layout.visible_display_row_range.start + ix as u32;
2385            line_with_invisibles.draw(
2386                layout,
2387                row,
2388                layout.content_origin,
2389                whitespace_setting,
2390                invisible_display_ranges,
2391                cx,
2392            )
2393        }
2394    }
2395
2396    fn paint_redactions(&mut self, layout: &EditorLayout, cx: &mut ElementContext) {
2397        if layout.redacted_ranges.is_empty() {
2398            return;
2399        }
2400
2401        let line_end_overshoot = layout.line_end_overshoot();
2402
2403        // A softer than perfect black
2404        let redaction_color = gpui::rgb(0x0e1111);
2405
2406        cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2407            for range in layout.redacted_ranges.iter() {
2408                self.paint_highlighted_range(
2409                    range.clone(),
2410                    redaction_color.into(),
2411                    Pixels::ZERO,
2412                    line_end_overshoot,
2413                    layout,
2414                    cx,
2415                );
2416            }
2417        });
2418    }
2419
2420    fn paint_cursors(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2421        for cursor in &mut layout.cursors {
2422            cursor.paint(layout.content_origin, cx);
2423        }
2424    }
2425
2426    fn paint_scrollbar(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2427        let Some(scrollbar_layout) = layout.scrollbar_layout.as_ref() else {
2428            return;
2429        };
2430
2431        let thumb_bounds = scrollbar_layout.thumb_bounds();
2432        if scrollbar_layout.visible {
2433            cx.paint_layer(scrollbar_layout.hitbox.bounds, |cx| {
2434                cx.paint_quad(quad(
2435                    scrollbar_layout.hitbox.bounds,
2436                    Corners::default(),
2437                    cx.theme().colors().scrollbar_track_background,
2438                    Edges {
2439                        top: Pixels::ZERO,
2440                        right: Pixels::ZERO,
2441                        bottom: Pixels::ZERO,
2442                        left: ScrollbarLayout::BORDER_WIDTH,
2443                    },
2444                    cx.theme().colors().scrollbar_track_border,
2445                ));
2446
2447                // Refresh scrollbar markers in the background. Below, we paint whatever markers have already been computed.
2448                self.refresh_scrollbar_markers(layout, scrollbar_layout, cx);
2449
2450                let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
2451                for marker in markers.iter() {
2452                    let mut marker = marker.clone();
2453                    marker.bounds.origin += scrollbar_layout.hitbox.origin;
2454                    cx.paint_quad(marker);
2455                }
2456
2457                cx.paint_quad(quad(
2458                    thumb_bounds,
2459                    Corners::default(),
2460                    cx.theme().colors().scrollbar_thumb_background,
2461                    Edges {
2462                        top: Pixels::ZERO,
2463                        right: Pixels::ZERO,
2464                        bottom: Pixels::ZERO,
2465                        left: ScrollbarLayout::BORDER_WIDTH,
2466                    },
2467                    cx.theme().colors().scrollbar_thumb_border,
2468                ));
2469            });
2470        }
2471
2472        cx.set_cursor_style(CursorStyle::Arrow, &scrollbar_layout.hitbox);
2473
2474        let scroll_height = scrollbar_layout.scroll_height;
2475        let height = scrollbar_layout.height;
2476        let row_range = scrollbar_layout.visible_row_range.clone();
2477
2478        cx.on_mouse_event({
2479            let editor = self.editor.clone();
2480            let hitbox = scrollbar_layout.hitbox.clone();
2481            let mut mouse_position = cx.mouse_position();
2482            move |event: &MouseMoveEvent, phase, cx| {
2483                if phase == DispatchPhase::Capture {
2484                    return;
2485                }
2486
2487                editor.update(cx, |editor, cx| {
2488                    if event.pressed_button == Some(MouseButton::Left)
2489                        && editor.scroll_manager.is_dragging_scrollbar()
2490                    {
2491                        let y = mouse_position.y;
2492                        let new_y = event.position.y;
2493                        if (hitbox.top()..hitbox.bottom()).contains(&y) {
2494                            let mut position = editor.scroll_position(cx);
2495                            position.y += (new_y - y) * scroll_height / height;
2496                            if position.y < 0.0 {
2497                                position.y = 0.0;
2498                            }
2499                            editor.set_scroll_position(position, cx);
2500                        }
2501
2502                        mouse_position = event.position;
2503                        cx.stop_propagation();
2504                    } else {
2505                        editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
2506                        if hitbox.is_hovered(cx) {
2507                            editor.scroll_manager.show_scrollbar(cx);
2508                        }
2509                    }
2510                })
2511            }
2512        });
2513
2514        if self.editor.read(cx).scroll_manager.is_dragging_scrollbar() {
2515            cx.on_mouse_event({
2516                let editor = self.editor.clone();
2517                move |_: &MouseUpEvent, phase, cx| {
2518                    if phase == DispatchPhase::Capture {
2519                        return;
2520                    }
2521
2522                    editor.update(cx, |editor, cx| {
2523                        editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
2524                        cx.stop_propagation();
2525                    });
2526                }
2527            });
2528        } else {
2529            cx.on_mouse_event({
2530                let editor = self.editor.clone();
2531                let hitbox = scrollbar_layout.hitbox.clone();
2532                move |event: &MouseDownEvent, phase, cx| {
2533                    if phase == DispatchPhase::Capture || !hitbox.is_hovered(cx) {
2534                        return;
2535                    }
2536
2537                    editor.update(cx, |editor, cx| {
2538                        editor.scroll_manager.set_is_dragging_scrollbar(true, cx);
2539
2540                        let y = event.position.y;
2541                        if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
2542                            let center_row =
2543                                ((y - hitbox.top()) * scroll_height / height).round() as u32;
2544                            let top_row = center_row
2545                                .saturating_sub((row_range.end - row_range.start) as u32 / 2);
2546                            let mut position = editor.scroll_position(cx);
2547                            position.y = top_row as f32;
2548                            editor.set_scroll_position(position, cx);
2549                        } else {
2550                            editor.scroll_manager.show_scrollbar(cx);
2551                        }
2552
2553                        cx.stop_propagation();
2554                    });
2555                }
2556            });
2557        }
2558    }
2559
2560    fn refresh_scrollbar_markers(
2561        &self,
2562        layout: &EditorLayout,
2563        scrollbar_layout: &ScrollbarLayout,
2564        cx: &mut ElementContext,
2565    ) {
2566        self.editor.update(cx, |editor, cx| {
2567            if !editor.is_singleton(cx)
2568                || !editor
2569                    .scrollbar_marker_state
2570                    .should_refresh(scrollbar_layout.hitbox.size)
2571            {
2572                return;
2573            }
2574
2575            let scrollbar_layout = scrollbar_layout.clone();
2576            let background_highlights = editor.background_highlights.clone();
2577            let snapshot = layout.position_map.snapshot.clone();
2578            let theme = cx.theme().clone();
2579            let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
2580            let max_row = layout.max_row;
2581
2582            editor.scrollbar_marker_state.dirty = false;
2583            editor.scrollbar_marker_state.pending_refresh =
2584                Some(cx.spawn(|editor, mut cx| async move {
2585                    let scrollbar_size = scrollbar_layout.hitbox.size;
2586                    let scrollbar_markers = cx
2587                        .background_executor()
2588                        .spawn(async move {
2589                            let mut marker_quads = Vec::new();
2590
2591                            if scrollbar_settings.git_diff {
2592                                let marker_row_ranges = snapshot
2593                                    .buffer_snapshot
2594                                    .git_diff_hunks_in_range(0..max_row)
2595                                    .map(|hunk| {
2596                                        let start_display_row =
2597                                            Point::new(hunk.associated_range.start, 0)
2598                                                .to_display_point(&snapshot.display_snapshot)
2599                                                .row();
2600                                        let mut end_display_row =
2601                                            Point::new(hunk.associated_range.end, 0)
2602                                                .to_display_point(&snapshot.display_snapshot)
2603                                                .row();
2604                                        if end_display_row != start_display_row {
2605                                            end_display_row -= 1;
2606                                        }
2607                                        let color = match hunk.status() {
2608                                            DiffHunkStatus::Added => theme.status().created,
2609                                            DiffHunkStatus::Modified => theme.status().modified,
2610                                            DiffHunkStatus::Removed => theme.status().deleted,
2611                                        };
2612                                        ColoredRange {
2613                                            start: start_display_row,
2614                                            end: end_display_row,
2615                                            color,
2616                                        }
2617                                    });
2618
2619                                marker_quads.extend(
2620                                    scrollbar_layout.marker_quads_for_ranges(marker_row_ranges, 0),
2621                                );
2622                            }
2623
2624                            for (background_highlight_id, (_, background_ranges)) in
2625                                background_highlights.iter()
2626                            {
2627                                let is_search_highlights = *background_highlight_id
2628                                    == TypeId::of::<BufferSearchHighlights>();
2629                                let is_symbol_occurrences = *background_highlight_id
2630                                    == TypeId::of::<DocumentHighlightRead>()
2631                                    || *background_highlight_id
2632                                        == TypeId::of::<DocumentHighlightWrite>();
2633                                if (is_search_highlights && scrollbar_settings.search_results)
2634                                    || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
2635                                {
2636                                    let marker_row_ranges =
2637                                        background_ranges.into_iter().map(|range| {
2638                                            let display_start = range
2639                                                .start
2640                                                .to_display_point(&snapshot.display_snapshot);
2641                                            let display_end = range
2642                                                .end
2643                                                .to_display_point(&snapshot.display_snapshot);
2644                                            ColoredRange {
2645                                                start: display_start.row(),
2646                                                end: display_end.row(),
2647                                                color: theme.status().info,
2648                                            }
2649                                        });
2650                                    marker_quads.extend(
2651                                        scrollbar_layout
2652                                            .marker_quads_for_ranges(marker_row_ranges, 1),
2653                                    );
2654                                }
2655                            }
2656
2657                            if scrollbar_settings.diagnostics {
2658                                let max_point =
2659                                    snapshot.display_snapshot.buffer_snapshot.max_point();
2660
2661                                let diagnostics = snapshot
2662                                    .buffer_snapshot
2663                                    .diagnostics_in_range::<_, Point>(
2664                                        Point::zero()..max_point,
2665                                        false,
2666                                    )
2667                                    // We want to sort by severity, in order to paint the most severe diagnostics last.
2668                                    .sorted_by_key(|diagnostic| {
2669                                        std::cmp::Reverse(diagnostic.diagnostic.severity)
2670                                    });
2671
2672                                let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
2673                                    let start_display = diagnostic
2674                                        .range
2675                                        .start
2676                                        .to_display_point(&snapshot.display_snapshot);
2677                                    let end_display = diagnostic
2678                                        .range
2679                                        .end
2680                                        .to_display_point(&snapshot.display_snapshot);
2681                                    let color = match diagnostic.diagnostic.severity {
2682                                        DiagnosticSeverity::ERROR => theme.status().error,
2683                                        DiagnosticSeverity::WARNING => theme.status().warning,
2684                                        DiagnosticSeverity::INFORMATION => theme.status().info,
2685                                        _ => theme.status().hint,
2686                                    };
2687                                    ColoredRange {
2688                                        start: start_display.row(),
2689                                        end: end_display.row(),
2690                                        color,
2691                                    }
2692                                });
2693                                marker_quads.extend(
2694                                    scrollbar_layout.marker_quads_for_ranges(marker_row_ranges, 2),
2695                                );
2696                            }
2697
2698                            Arc::from(marker_quads)
2699                        })
2700                        .await;
2701
2702                    editor.update(&mut cx, |editor, cx| {
2703                        editor.scrollbar_marker_state.markers = scrollbar_markers;
2704                        editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
2705                        editor.scrollbar_marker_state.pending_refresh = None;
2706                        cx.notify();
2707                    })?;
2708
2709                    Ok(())
2710                }));
2711        });
2712    }
2713
2714    #[allow(clippy::too_many_arguments)]
2715    fn paint_highlighted_range(
2716        &self,
2717        range: Range<DisplayPoint>,
2718        color: Hsla,
2719        corner_radius: Pixels,
2720        line_end_overshoot: Pixels,
2721        layout: &EditorLayout,
2722        cx: &mut ElementContext,
2723    ) {
2724        let start_row = layout.visible_display_row_range.start;
2725        let end_row = layout.visible_display_row_range.end;
2726        if range.start != range.end {
2727            let row_range = if range.end.column() == 0 {
2728                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
2729            } else {
2730                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
2731            };
2732
2733            let highlighted_range = HighlightedRange {
2734                color,
2735                line_height: layout.position_map.line_height,
2736                corner_radius,
2737                start_y: layout.content_origin.y
2738                    + row_range.start as f32 * layout.position_map.line_height
2739                    - layout.position_map.scroll_pixel_position.y,
2740                lines: row_range
2741                    .into_iter()
2742                    .map(|row| {
2743                        let line_layout =
2744                            &layout.position_map.line_layouts[(row - start_row) as usize].line;
2745                        HighlightedRangeLine {
2746                            start_x: if row == range.start.row() {
2747                                layout.content_origin.x
2748                                    + line_layout.x_for_index(range.start.column() as usize)
2749                                    - layout.position_map.scroll_pixel_position.x
2750                            } else {
2751                                layout.content_origin.x
2752                                    - layout.position_map.scroll_pixel_position.x
2753                            },
2754                            end_x: if row == range.end.row() {
2755                                layout.content_origin.x
2756                                    + line_layout.x_for_index(range.end.column() as usize)
2757                                    - layout.position_map.scroll_pixel_position.x
2758                            } else {
2759                                layout.content_origin.x + line_layout.width + line_end_overshoot
2760                                    - layout.position_map.scroll_pixel_position.x
2761                            },
2762                        }
2763                    })
2764                    .collect(),
2765            };
2766
2767            highlighted_range.paint(layout.text_hitbox.bounds, cx);
2768        }
2769    }
2770
2771    fn paint_folds(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2772        if layout.folds.is_empty() {
2773            return;
2774        }
2775
2776        cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2777            let fold_corner_radius = 0.15 * layout.position_map.line_height;
2778            for mut fold in mem::take(&mut layout.folds) {
2779                fold.hover_element.paint(cx);
2780
2781                let hover_element = fold.hover_element.downcast_mut::<Stateful<Div>>().unwrap();
2782                let fold_background = if hover_element.interactivity().active.unwrap() {
2783                    cx.theme().colors().ghost_element_active
2784                } else if hover_element.interactivity().hovered.unwrap() {
2785                    cx.theme().colors().ghost_element_hover
2786                } else {
2787                    cx.theme().colors().ghost_element_background
2788                };
2789
2790                self.paint_highlighted_range(
2791                    fold.display_range.clone(),
2792                    fold_background,
2793                    fold_corner_radius,
2794                    fold_corner_radius * 2.,
2795                    layout,
2796                    cx,
2797                );
2798            }
2799        })
2800    }
2801
2802    fn paint_inline_blame(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2803        if let Some(mut inline_blame) = layout.inline_blame.take() {
2804            cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2805                inline_blame.paint(cx);
2806            })
2807        }
2808    }
2809
2810    fn paint_blocks(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2811        for mut block in layout.blocks.drain(..) {
2812            block.element.paint(cx);
2813        }
2814    }
2815
2816    fn paint_mouse_context_menu(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2817        if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
2818            mouse_context_menu.paint(cx);
2819        }
2820    }
2821
2822    fn paint_scroll_wheel_listener(&mut self, layout: &EditorLayout, cx: &mut ElementContext) {
2823        cx.on_mouse_event({
2824            let position_map = layout.position_map.clone();
2825            let editor = self.editor.clone();
2826            let hitbox = layout.hitbox.clone();
2827            let mut delta = ScrollDelta::default();
2828
2829            // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
2830            // accidentally turn off their scrolling.
2831            let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
2832
2833            move |event: &ScrollWheelEvent, phase, cx| {
2834                if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
2835                    delta = delta.coalesce(event.delta);
2836                    editor.update(cx, |editor, cx| {
2837                        let position_map: &PositionMap = &position_map;
2838
2839                        let line_height = position_map.line_height;
2840                        let max_glyph_width = position_map.em_width;
2841                        let (delta, axis) = match delta {
2842                            gpui::ScrollDelta::Pixels(mut pixels) => {
2843                                //Trackpad
2844                                let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
2845                                (pixels, axis)
2846                            }
2847
2848                            gpui::ScrollDelta::Lines(lines) => {
2849                                //Not trackpad
2850                                let pixels =
2851                                    point(lines.x * max_glyph_width, lines.y * line_height);
2852                                (pixels, None)
2853                            }
2854                        };
2855
2856                        let scroll_position = position_map.snapshot.scroll_position();
2857                        let x = (scroll_position.x * max_glyph_width
2858                            - (delta.x * scroll_sensitivity))
2859                            / max_glyph_width;
2860                        let y = (scroll_position.y * line_height - (delta.y * scroll_sensitivity))
2861                            / line_height;
2862                        let scroll_position =
2863                            point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
2864                        editor.scroll(scroll_position, axis, cx);
2865                        cx.stop_propagation();
2866                    });
2867                }
2868            }
2869        });
2870    }
2871
2872    fn paint_mouse_listeners(&mut self, layout: &EditorLayout, cx: &mut ElementContext) {
2873        self.paint_scroll_wheel_listener(layout, cx);
2874
2875        cx.on_mouse_event({
2876            let position_map = layout.position_map.clone();
2877            let editor = self.editor.clone();
2878            let text_hitbox = layout.text_hitbox.clone();
2879            let gutter_hitbox = layout.gutter_hitbox.clone();
2880
2881            move |event: &MouseDownEvent, phase, cx| {
2882                if phase == DispatchPhase::Bubble {
2883                    match event.button {
2884                        MouseButton::Left => editor.update(cx, |editor, cx| {
2885                            Self::mouse_left_down(
2886                                editor,
2887                                event,
2888                                &position_map,
2889                                &text_hitbox,
2890                                &gutter_hitbox,
2891                                cx,
2892                            );
2893                        }),
2894                        MouseButton::Right => editor.update(cx, |editor, cx| {
2895                            Self::mouse_right_down(editor, event, &position_map, &text_hitbox, cx);
2896                        }),
2897                        _ => {}
2898                    };
2899                }
2900            }
2901        });
2902
2903        cx.on_mouse_event({
2904            let editor = self.editor.clone();
2905            let position_map = layout.position_map.clone();
2906            let text_hitbox = layout.text_hitbox.clone();
2907
2908            move |event: &MouseUpEvent, phase, cx| {
2909                if phase == DispatchPhase::Bubble {
2910                    editor.update(cx, |editor, cx| {
2911                        Self::mouse_up(editor, event, &position_map, &text_hitbox, cx)
2912                    });
2913                }
2914            }
2915        });
2916        cx.on_mouse_event({
2917            let position_map = layout.position_map.clone();
2918            let editor = self.editor.clone();
2919            let text_hitbox = layout.text_hitbox.clone();
2920            let gutter_hitbox = layout.gutter_hitbox.clone();
2921
2922            move |event: &MouseMoveEvent, phase, cx| {
2923                if phase == DispatchPhase::Bubble {
2924                    editor.update(cx, |editor, cx| {
2925                        if event.pressed_button == Some(MouseButton::Left) {
2926                            Self::mouse_dragged(
2927                                editor,
2928                                event,
2929                                &position_map,
2930                                text_hitbox.bounds,
2931                                cx,
2932                            )
2933                        }
2934
2935                        Self::mouse_moved(
2936                            editor,
2937                            event,
2938                            &position_map,
2939                            &text_hitbox,
2940                            &gutter_hitbox,
2941                            cx,
2942                        )
2943                    });
2944                }
2945            }
2946        });
2947    }
2948
2949    fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
2950        bounds.upper_right().x - self.style.scrollbar_width
2951    }
2952
2953    fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
2954        let style = &self.style;
2955        let font_size = style.text.font_size.to_pixels(cx.rem_size());
2956        let layout = cx
2957            .text_system()
2958            .shape_line(
2959                SharedString::from(" ".repeat(column)),
2960                font_size,
2961                &[TextRun {
2962                    len: column,
2963                    font: style.text.font(),
2964                    color: Hsla::default(),
2965                    background_color: None,
2966                    underline: None,
2967                    strikethrough: None,
2968                }],
2969            )
2970            .unwrap();
2971
2972        layout.width
2973    }
2974
2975    fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
2976        let digit_count = (snapshot.max_buffer_row() as f32 + 1.).log10().floor() as usize + 1;
2977        self.column_pixels(digit_count, cx)
2978    }
2979}
2980
2981fn render_inline_blame_entry(
2982    blame: &gpui::Model<GitBlame>,
2983    blame_entry: BlameEntry,
2984    style: &EditorStyle,
2985    workspace: Option<WeakView<Workspace>>,
2986    cx: &mut ElementContext<'_>,
2987) -> AnyElement {
2988    let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
2989
2990    let author = blame_entry.author.as_deref().unwrap_or_default();
2991    let text = format!("{}, {}", author, relative_timestamp);
2992
2993    let details = blame.read(cx).details_for_entry(&blame_entry);
2994
2995    let tooltip = cx.new_view(|_| BlameEntryTooltip::new(blame_entry, details, style, workspace));
2996
2997    h_flex()
2998        .id("inline-blame")
2999        .w_full()
3000        .font(style.text.font().family)
3001        .text_color(cx.theme().status().hint)
3002        .line_height(style.text.line_height)
3003        .child(Icon::new(IconName::FileGit).color(Color::Hint))
3004        .child(text)
3005        .gap_2()
3006        .hoverable_tooltip(move |_| tooltip.clone().into())
3007        .into_any()
3008}
3009
3010fn blame_entry_timestamp(
3011    blame_entry: &BlameEntry,
3012    format: time_format::TimestampFormat,
3013    cx: &WindowContext,
3014) -> String {
3015    match blame_entry.author_offset_date_time() {
3016        Ok(timestamp) => time_format::format_localized_timestamp(
3017            timestamp,
3018            time::OffsetDateTime::now_utc(),
3019            cx.local_timezone(),
3020            format,
3021        ),
3022        Err(_) => "Error parsing date".to_string(),
3023    }
3024}
3025
3026fn blame_entry_relative_timestamp(blame_entry: &BlameEntry, cx: &WindowContext) -> String {
3027    blame_entry_timestamp(blame_entry, time_format::TimestampFormat::Relative, cx)
3028}
3029
3030fn blame_entry_absolute_timestamp(blame_entry: &BlameEntry, cx: &WindowContext) -> String {
3031    blame_entry_timestamp(
3032        blame_entry,
3033        time_format::TimestampFormat::MediumAbsolute,
3034        cx,
3035    )
3036}
3037
3038struct BlameEntryTooltip {
3039    blame_entry: BlameEntry,
3040    details: Option<CommitDetails>,
3041    style: EditorStyle,
3042    workspace: Option<WeakView<Workspace>>,
3043    scroll_handle: ScrollHandle,
3044}
3045
3046impl BlameEntryTooltip {
3047    fn new(
3048        blame_entry: BlameEntry,
3049        details: Option<CommitDetails>,
3050        style: &EditorStyle,
3051        workspace: Option<WeakView<Workspace>>,
3052    ) -> Self {
3053        Self {
3054            style: style.clone(),
3055            blame_entry,
3056            details,
3057            workspace,
3058            scroll_handle: ScrollHandle::new(),
3059        }
3060    }
3061}
3062
3063impl Render for BlameEntryTooltip {
3064    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
3065        let author = self
3066            .blame_entry
3067            .author
3068            .clone()
3069            .unwrap_or("<no name>".to_string());
3070
3071        let author_email = self.blame_entry.author_mail.clone();
3072
3073        let pretty_commit_id = format!("{}", self.blame_entry.sha);
3074        let short_commit_id = pretty_commit_id.chars().take(6).collect::<String>();
3075        let absolute_timestamp = blame_entry_absolute_timestamp(&self.blame_entry, cx);
3076
3077        let message = self
3078            .details
3079            .as_ref()
3080            .map(|details| {
3081                crate::render_parsed_markdown(
3082                    "blame-message",
3083                    &details.parsed_message,
3084                    &self.style,
3085                    self.workspace.clone(),
3086                    cx,
3087                )
3088                .into_any()
3089            })
3090            .unwrap_or("<no commit message>".into_any());
3091
3092        let ui_font_size = ThemeSettings::get_global(cx).ui_font_size;
3093        let message_max_height = cx.line_height() * 12 + (ui_font_size / 0.4);
3094
3095        tooltip_container(cx, move |this, cx| {
3096            this.occlude()
3097                .on_mouse_move(|_, cx| cx.stop_propagation())
3098                .child(
3099                    v_flex()
3100                        .w(gpui::rems(30.))
3101                        .gap_4()
3102                        .child(
3103                            h_flex()
3104                                .gap_x_2()
3105                                .overflow_x_hidden()
3106                                .flex_wrap()
3107                                .child(author)
3108                                .when_some(author_email, |this, author_email| {
3109                                    this.child(
3110                                        div()
3111                                            .text_color(cx.theme().colors().text_muted)
3112                                            .child(author_email),
3113                                    )
3114                                })
3115                                .pb_1()
3116                                .border_b_1()
3117                                .border_color(cx.theme().colors().border),
3118                        )
3119                        .child(
3120                            div()
3121                                .id("inline-blame-commit-message")
3122                                .occlude()
3123                                .child(message)
3124                                .max_h(message_max_height)
3125                                .overflow_y_scroll()
3126                                .track_scroll(&self.scroll_handle),
3127                        )
3128                        .child(
3129                            h_flex()
3130                                .text_color(cx.theme().colors().text_muted)
3131                                .w_full()
3132                                .justify_between()
3133                                .child(absolute_timestamp)
3134                                .child(
3135                                    Button::new("commit-sha-button", short_commit_id.clone())
3136                                        .style(ButtonStyle::Transparent)
3137                                        .color(Color::Muted)
3138                                        .icon(IconName::FileGit)
3139                                        .icon_color(Color::Muted)
3140                                        .icon_position(IconPosition::Start)
3141                                        .disabled(
3142                                            self.details.as_ref().map_or(true, |details| {
3143                                                details.permalink.is_none()
3144                                            }),
3145                                        )
3146                                        .when_some(
3147                                            self.details
3148                                                .as_ref()
3149                                                .and_then(|details| details.permalink.clone()),
3150                                            |this, url| {
3151                                                this.on_click(move |_, cx| {
3152                                                    cx.stop_propagation();
3153                                                    cx.open_url(url.as_str())
3154                                                })
3155                                            },
3156                                        ),
3157                                ),
3158                        ),
3159                )
3160        })
3161    }
3162}
3163
3164fn render_blame_entry(
3165    ix: usize,
3166    blame: &gpui::Model<GitBlame>,
3167    blame_entry: BlameEntry,
3168    style: &EditorStyle,
3169    last_used_color: &mut Option<(PlayerColor, Oid)>,
3170    editor: View<Editor>,
3171    cx: &mut ElementContext<'_>,
3172) -> AnyElement {
3173    let mut sha_color = cx
3174        .theme()
3175        .players()
3176        .color_for_participant(blame_entry.sha.into());
3177    // If the last color we used is the same as the one we get for this line, but
3178    // the commit SHAs are different, then we try again to get a different color.
3179    match *last_used_color {
3180        Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
3181            let index: u32 = blame_entry.sha.into();
3182            sha_color = cx.theme().players().color_for_participant(index + 1);
3183        }
3184        _ => {}
3185    };
3186    last_used_color.replace((sha_color, blame_entry.sha));
3187
3188    let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
3189
3190    let pretty_commit_id = format!("{}", blame_entry.sha);
3191    let short_commit_id = pretty_commit_id.chars().take(6).collect::<String>();
3192
3193    let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
3194    let name = util::truncate_and_trailoff(author_name, 20);
3195
3196    let details = blame.read(cx).details_for_entry(&blame_entry);
3197
3198    let workspace = editor.read(cx).workspace.as_ref().map(|(w, _)| w.clone());
3199
3200    let tooltip = cx.new_view(|_| {
3201        BlameEntryTooltip::new(blame_entry.clone(), details.clone(), style, workspace)
3202    });
3203
3204    h_flex()
3205        .w_full()
3206        .font(style.text.font().family)
3207        .line_height(style.text.line_height)
3208        .id(("blame", ix))
3209        .children([
3210            div()
3211                .text_color(sha_color.cursor)
3212                .child(short_commit_id)
3213                .mr_2(),
3214            div()
3215                .w_full()
3216                .h_flex()
3217                .justify_between()
3218                .text_color(cx.theme().status().hint)
3219                .child(name)
3220                .child(relative_timestamp),
3221        ])
3222        .on_mouse_down(MouseButton::Right, {
3223            let blame_entry = blame_entry.clone();
3224            move |event, cx| {
3225                deploy_blame_entry_context_menu(&blame_entry, editor.clone(), event.position, cx);
3226            }
3227        })
3228        .hover(|style| style.bg(cx.theme().colors().element_hover))
3229        .when_some(
3230            details.and_then(|details| details.permalink),
3231            |this, url| {
3232                let url = url.clone();
3233                this.cursor_pointer().on_click(move |_, cx| {
3234                    cx.stop_propagation();
3235                    cx.open_url(url.as_str())
3236                })
3237            },
3238        )
3239        .hoverable_tooltip(move |_| tooltip.clone().into())
3240        .into_any()
3241}
3242
3243fn deploy_blame_entry_context_menu(
3244    blame_entry: &BlameEntry,
3245    editor: View<Editor>,
3246    position: gpui::Point<Pixels>,
3247    cx: &mut WindowContext<'_>,
3248) {
3249    let context_menu = ContextMenu::build(cx, move |this, _| {
3250        let sha = format!("{}", blame_entry.sha);
3251        this.entry("Copy commit SHA", None, move |cx| {
3252            cx.write_to_clipboard(ClipboardItem::new(sha.clone()));
3253        })
3254    });
3255
3256    editor.update(cx, move |editor, cx| {
3257        editor.mouse_context_menu = Some(MouseContextMenu::new(position, context_menu, cx));
3258        cx.notify();
3259    });
3260}
3261
3262#[derive(Debug)]
3263pub(crate) struct LineWithInvisibles {
3264    pub line: ShapedLine,
3265    invisibles: Vec<Invisible>,
3266}
3267
3268impl LineWithInvisibles {
3269    fn from_chunks<'a>(
3270        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
3271        text_style: &TextStyle,
3272        max_line_len: usize,
3273        max_line_count: usize,
3274        line_number_layouts: &[Option<ShapedLine>],
3275        editor_mode: EditorMode,
3276        cx: &WindowContext,
3277    ) -> Vec<Self> {
3278        let mut layouts = Vec::with_capacity(max_line_count);
3279        let mut line = String::new();
3280        let mut invisibles = Vec::new();
3281        let mut styles = Vec::new();
3282        let mut non_whitespace_added = false;
3283        let mut row = 0;
3284        let mut line_exceeded_max_len = false;
3285        let font_size = text_style.font_size.to_pixels(cx.rem_size());
3286
3287        for highlighted_chunk in chunks.chain([HighlightedChunk {
3288            chunk: "\n",
3289            style: None,
3290            is_tab: false,
3291        }]) {
3292            for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
3293                if ix > 0 {
3294                    let shaped_line = cx
3295                        .text_system()
3296                        .shape_line(line.clone().into(), font_size, &styles)
3297                        .unwrap();
3298                    layouts.push(Self {
3299                        line: shaped_line,
3300                        invisibles: std::mem::take(&mut invisibles),
3301                    });
3302
3303                    line.clear();
3304                    styles.clear();
3305                    row += 1;
3306                    line_exceeded_max_len = false;
3307                    non_whitespace_added = false;
3308                    if row == max_line_count {
3309                        return layouts;
3310                    }
3311                }
3312
3313                if !line_chunk.is_empty() && !line_exceeded_max_len {
3314                    let text_style = if let Some(style) = highlighted_chunk.style {
3315                        Cow::Owned(text_style.clone().highlight(style))
3316                    } else {
3317                        Cow::Borrowed(text_style)
3318                    };
3319
3320                    if line.len() + line_chunk.len() > max_line_len {
3321                        let mut chunk_len = max_line_len - line.len();
3322                        while !line_chunk.is_char_boundary(chunk_len) {
3323                            chunk_len -= 1;
3324                        }
3325                        line_chunk = &line_chunk[..chunk_len];
3326                        line_exceeded_max_len = true;
3327                    }
3328
3329                    styles.push(TextRun {
3330                        len: line_chunk.len(),
3331                        font: text_style.font(),
3332                        color: text_style.color,
3333                        background_color: text_style.background_color,
3334                        underline: text_style.underline,
3335                        strikethrough: text_style.strikethrough,
3336                    });
3337
3338                    if editor_mode == EditorMode::Full {
3339                        // Line wrap pads its contents with fake whitespaces,
3340                        // avoid printing them
3341                        let inside_wrapped_string = line_number_layouts
3342                            .get(row)
3343                            .and_then(|layout| layout.as_ref())
3344                            .is_none();
3345                        if highlighted_chunk.is_tab {
3346                            if non_whitespace_added || !inside_wrapped_string {
3347                                invisibles.push(Invisible::Tab {
3348                                    line_start_offset: line.len(),
3349                                });
3350                            }
3351                        } else {
3352                            invisibles.extend(
3353                                line_chunk
3354                                    .chars()
3355                                    .enumerate()
3356                                    .filter(|(_, line_char)| {
3357                                        let is_whitespace = line_char.is_whitespace();
3358                                        non_whitespace_added |= !is_whitespace;
3359                                        is_whitespace
3360                                            && (non_whitespace_added || !inside_wrapped_string)
3361                                    })
3362                                    .map(|(whitespace_index, _)| Invisible::Whitespace {
3363                                        line_offset: line.len() + whitespace_index,
3364                                    }),
3365                            )
3366                        }
3367                    }
3368
3369                    line.push_str(line_chunk);
3370                }
3371            }
3372        }
3373
3374        layouts
3375    }
3376
3377    fn draw(
3378        &self,
3379        layout: &EditorLayout,
3380        row: u32,
3381        content_origin: gpui::Point<Pixels>,
3382        whitespace_setting: ShowWhitespaceSetting,
3383        selection_ranges: &[Range<DisplayPoint>],
3384        cx: &mut ElementContext,
3385    ) {
3386        let line_height = layout.position_map.line_height;
3387        let line_y =
3388            line_height * (row as f32 - layout.position_map.scroll_pixel_position.y / line_height);
3389
3390        let line_origin =
3391            content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
3392        self.line.paint(line_origin, line_height, cx).log_err();
3393
3394        self.draw_invisibles(
3395            &selection_ranges,
3396            layout,
3397            content_origin,
3398            line_y,
3399            row,
3400            line_height,
3401            whitespace_setting,
3402            cx,
3403        );
3404    }
3405
3406    #[allow(clippy::too_many_arguments)]
3407    fn draw_invisibles(
3408        &self,
3409        selection_ranges: &[Range<DisplayPoint>],
3410        layout: &EditorLayout,
3411        content_origin: gpui::Point<Pixels>,
3412        line_y: Pixels,
3413        row: u32,
3414        line_height: Pixels,
3415        whitespace_setting: ShowWhitespaceSetting,
3416        cx: &mut ElementContext,
3417    ) {
3418        let allowed_invisibles_regions = match whitespace_setting {
3419            ShowWhitespaceSetting::None => return,
3420            ShowWhitespaceSetting::Selection => Some(selection_ranges),
3421            ShowWhitespaceSetting::All => None,
3422        };
3423
3424        for invisible in &self.invisibles {
3425            let (&token_offset, invisible_symbol) = match invisible {
3426                Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
3427                Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
3428            };
3429
3430            let x_offset = self.line.x_for_index(token_offset);
3431            let invisible_offset =
3432                (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
3433            let origin = content_origin
3434                + gpui::point(
3435                    x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
3436                    line_y,
3437                );
3438
3439            if let Some(allowed_regions) = allowed_invisibles_regions {
3440                let invisible_point = DisplayPoint::new(row, token_offset as u32);
3441                if !allowed_regions
3442                    .iter()
3443                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
3444                {
3445                    continue;
3446                }
3447            }
3448            invisible_symbol.paint(origin, line_height, cx).log_err();
3449        }
3450    }
3451}
3452
3453#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3454enum Invisible {
3455    Tab { line_start_offset: usize },
3456    Whitespace { line_offset: usize },
3457}
3458
3459impl Element for EditorElement {
3460    type BeforeLayout = ();
3461    type AfterLayout = EditorLayout;
3462
3463    fn before_layout(&mut self, cx: &mut ElementContext) -> (gpui::LayoutId, ()) {
3464        self.editor.update(cx, |editor, cx| {
3465            editor.set_style(self.style.clone(), cx);
3466
3467            let layout_id = match editor.mode {
3468                EditorMode::SingleLine => {
3469                    let rem_size = cx.rem_size();
3470                    let mut style = Style::default();
3471                    style.size.width = relative(1.).into();
3472                    style.size.height = self.style.text.line_height_in_pixels(rem_size).into();
3473                    cx.with_element_context(|cx| cx.request_layout(&style, None))
3474                }
3475                EditorMode::AutoHeight { max_lines } => {
3476                    let editor_handle = cx.view().clone();
3477                    let max_line_number_width =
3478                        self.max_line_number_width(&editor.snapshot(cx), cx);
3479                    cx.with_element_context(|cx| {
3480                        cx.request_measured_layout(
3481                            Style::default(),
3482                            move |known_dimensions, _, cx| {
3483                                editor_handle
3484                                    .update(cx, |editor, cx| {
3485                                        compute_auto_height_layout(
3486                                            editor,
3487                                            max_lines,
3488                                            max_line_number_width,
3489                                            known_dimensions,
3490                                            cx,
3491                                        )
3492                                    })
3493                                    .unwrap_or_default()
3494                            },
3495                        )
3496                    })
3497                }
3498                EditorMode::Full => {
3499                    let mut style = Style::default();
3500                    style.size.width = relative(1.).into();
3501                    style.size.height = relative(1.).into();
3502                    cx.with_element_context(|cx| cx.request_layout(&style, None))
3503                }
3504            };
3505
3506            (layout_id, ())
3507        })
3508    }
3509
3510    fn after_layout(
3511        &mut self,
3512        bounds: Bounds<Pixels>,
3513        _: &mut Self::BeforeLayout,
3514        cx: &mut ElementContext,
3515    ) -> Self::AfterLayout {
3516        let text_style = TextStyleRefinement {
3517            font_size: Some(self.style.text.font_size),
3518            line_height: Some(self.style.text.line_height),
3519            ..Default::default()
3520        };
3521        cx.with_text_style(Some(text_style), |cx| {
3522            cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
3523                let mut snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
3524                let style = self.style.clone();
3525
3526                let font_id = cx.text_system().resolve_font(&style.text.font());
3527                let font_size = style.text.font_size.to_pixels(cx.rem_size());
3528                let line_height = style.text.line_height_in_pixels(cx.rem_size());
3529                let em_width = cx
3530                    .text_system()
3531                    .typographic_bounds(font_id, font_size, 'm')
3532                    .unwrap()
3533                    .size
3534                    .width;
3535                let em_advance = cx
3536                    .text_system()
3537                    .advance(font_id, font_size, 'm')
3538                    .unwrap()
3539                    .width;
3540
3541                let gutter_dimensions = snapshot.gutter_dimensions(
3542                    font_id,
3543                    font_size,
3544                    em_width,
3545                    self.max_line_number_width(&snapshot, cx),
3546                    cx,
3547                );
3548                let text_width = bounds.size.width - gutter_dimensions.width;
3549                let overscroll = size(em_width, px(0.));
3550
3551                snapshot = self.editor.update(cx, |editor, cx| {
3552                    editor.last_bounds = Some(bounds);
3553                    editor.gutter_width = gutter_dimensions.width;
3554                    editor.set_visible_line_count(bounds.size.height / line_height, cx);
3555
3556                    let editor_width =
3557                        text_width - gutter_dimensions.margin - overscroll.width - em_width;
3558                    let wrap_width = match editor.soft_wrap_mode(cx) {
3559                        SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
3560                        SoftWrap::EditorWidth => editor_width,
3561                        SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
3562                    };
3563
3564                    if editor.set_wrap_width(Some(wrap_width), cx) {
3565                        editor.snapshot(cx)
3566                    } else {
3567                        snapshot
3568                    }
3569                });
3570
3571                let wrap_guides = self
3572                    .editor
3573                    .read(cx)
3574                    .wrap_guides(cx)
3575                    .iter()
3576                    .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
3577                    .collect::<SmallVec<[_; 2]>>();
3578
3579                let hitbox = cx.insert_hitbox(bounds, false);
3580                let gutter_hitbox = cx.insert_hitbox(
3581                    Bounds {
3582                        origin: bounds.origin,
3583                        size: size(gutter_dimensions.width, bounds.size.height),
3584                    },
3585                    false,
3586                );
3587                let text_hitbox = cx.insert_hitbox(
3588                    Bounds {
3589                        origin: gutter_hitbox.upper_right(),
3590                        size: size(text_width, bounds.size.height),
3591                    },
3592                    false,
3593                );
3594                // Offset the content_bounds from the text_bounds by the gutter margin (which
3595                // is roughly half a character wide) to make hit testing work more like how we want.
3596                let content_origin =
3597                    text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
3598
3599                let autoscroll_horizontally = self.editor.update(cx, |editor, cx| {
3600                    let autoscroll_horizontally =
3601                        editor.autoscroll_vertically(bounds, line_height, cx);
3602                    snapshot = editor.snapshot(cx);
3603                    autoscroll_horizontally
3604                });
3605
3606                let mut scroll_position = snapshot.scroll_position();
3607                // The scroll position is a fractional point, the whole number of which represents
3608                // the top of the window in terms of display rows.
3609                let start_row = scroll_position.y as u32;
3610                let height_in_lines = bounds.size.height / line_height;
3611                let max_row = snapshot.max_point().row();
3612
3613                // Add 1 to ensure selections bleed off screen
3614                let end_row =
3615                    1 + cmp::min((scroll_position.y + height_in_lines).ceil() as u32, max_row);
3616
3617                let buffer_rows = snapshot
3618                    .buffer_rows(start_row)
3619                    .take((start_row..end_row).len());
3620
3621                let start_anchor = if start_row == 0 {
3622                    Anchor::min()
3623                } else {
3624                    snapshot.buffer_snapshot.anchor_before(
3625                        DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
3626                    )
3627                };
3628                let end_anchor = if end_row > max_row {
3629                    Anchor::max()
3630                } else {
3631                    snapshot.buffer_snapshot.anchor_before(
3632                        DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
3633                    )
3634                };
3635
3636                let highlighted_rows = self
3637                    .editor
3638                    .update(cx, |editor, cx| editor.highlighted_display_rows(cx));
3639                let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
3640                    start_anchor..end_anchor,
3641                    &snapshot.display_snapshot,
3642                    cx.theme().colors(),
3643                );
3644
3645                let redacted_ranges = self.editor.read(cx).redacted_ranges(
3646                    start_anchor..end_anchor,
3647                    &snapshot.display_snapshot,
3648                    cx,
3649                );
3650
3651                let (selections, active_rows, newest_selection_head) = self.layout_selections(
3652                    start_anchor,
3653                    end_anchor,
3654                    &snapshot,
3655                    start_row,
3656                    end_row,
3657                    cx,
3658                );
3659
3660                let (line_numbers, fold_statuses) = self.layout_line_numbers(
3661                    start_row..end_row,
3662                    buffer_rows.clone(),
3663                    &active_rows,
3664                    newest_selection_head,
3665                    &snapshot,
3666                    cx,
3667                );
3668
3669                let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
3670
3671                let mut max_visible_line_width = Pixels::ZERO;
3672                let line_layouts =
3673                    self.layout_lines(start_row..end_row, &line_numbers, &snapshot, cx);
3674                for line_with_invisibles in &line_layouts {
3675                    if line_with_invisibles.line.width > max_visible_line_width {
3676                        max_visible_line_width = line_with_invisibles.line.width;
3677                    }
3678                }
3679
3680                let longest_line_width = layout_line(snapshot.longest_row(), &snapshot, &style, cx)
3681                    .unwrap()
3682                    .width;
3683                let mut scroll_width =
3684                    longest_line_width.max(max_visible_line_width) + overscroll.width;
3685                let mut blocks = self.build_blocks(
3686                    start_row..end_row,
3687                    &snapshot,
3688                    &hitbox,
3689                    &text_hitbox,
3690                    &mut scroll_width,
3691                    &gutter_dimensions,
3692                    em_width,
3693                    gutter_dimensions.width + gutter_dimensions.margin,
3694                    line_height,
3695                    &line_layouts,
3696                    cx,
3697                );
3698
3699                let scroll_pixel_position = point(
3700                    scroll_position.x * em_width,
3701                    scroll_position.y * line_height,
3702                );
3703
3704                let mut inline_blame = None;
3705                if let Some(newest_selection_head) = newest_selection_head {
3706                    let display_row = newest_selection_head.row();
3707                    if (start_row..end_row).contains(&display_row) {
3708                        let line_layout = &line_layouts[(display_row - start_row) as usize];
3709                        inline_blame = self.layout_inline_blame(
3710                            display_row,
3711                            &snapshot.display_snapshot,
3712                            line_layout,
3713                            em_width,
3714                            content_origin,
3715                            scroll_pixel_position,
3716                            line_height,
3717                            cx,
3718                        );
3719                    }
3720                }
3721
3722                let blamed_display_rows = self.layout_blame_entries(
3723                    buffer_rows,
3724                    em_width,
3725                    scroll_position,
3726                    line_height,
3727                    &gutter_hitbox,
3728                    gutter_dimensions.git_blame_entries_width,
3729                    cx,
3730                );
3731
3732                let scroll_max = point(
3733                    ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
3734                    max_row as f32,
3735                );
3736
3737                self.editor.update(cx, |editor, cx| {
3738                    let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
3739
3740                    let autoscrolled = if autoscroll_horizontally {
3741                        editor.autoscroll_horizontally(
3742                            start_row,
3743                            text_hitbox.size.width,
3744                            scroll_width,
3745                            em_width,
3746                            &line_layouts,
3747                            cx,
3748                        )
3749                    } else {
3750                        false
3751                    };
3752
3753                    if clamped || autoscrolled {
3754                        snapshot = editor.snapshot(cx);
3755                        scroll_position = snapshot.scroll_position();
3756                    }
3757                });
3758
3759                cx.with_element_id(Some("blocks"), |cx| {
3760                    self.layout_blocks(
3761                        &mut blocks,
3762                        &hitbox,
3763                        line_height,
3764                        scroll_pixel_position,
3765                        cx,
3766                    );
3767                });
3768
3769                let cursors = self.layout_cursors(
3770                    &snapshot,
3771                    &selections,
3772                    start_row..end_row,
3773                    &line_layouts,
3774                    &text_hitbox,
3775                    content_origin,
3776                    scroll_pixel_position,
3777                    line_height,
3778                    em_width,
3779                    cx,
3780                );
3781
3782                let scrollbar_layout = self.layout_scrollbar(
3783                    &snapshot,
3784                    bounds,
3785                    scroll_position,
3786                    line_height,
3787                    height_in_lines,
3788                    cx,
3789                );
3790
3791                let folds = cx.with_element_id(Some("folds"), |cx| {
3792                    self.layout_folds(
3793                        &snapshot,
3794                        content_origin,
3795                        start_anchor..end_anchor,
3796                        start_row..end_row,
3797                        scroll_pixel_position,
3798                        line_height,
3799                        &line_layouts,
3800                        cx,
3801                    )
3802                });
3803
3804                let gutter_settings = EditorSettings::get_global(cx).gutter;
3805
3806                let mut context_menu_visible = false;
3807                let mut code_actions_indicator = None;
3808                if let Some(newest_selection_head) = newest_selection_head {
3809                    if (start_row..end_row).contains(&newest_selection_head.row()) {
3810                        context_menu_visible = self.layout_context_menu(
3811                            line_height,
3812                            &hitbox,
3813                            &text_hitbox,
3814                            content_origin,
3815                            start_row,
3816                            scroll_pixel_position,
3817                            &line_layouts,
3818                            newest_selection_head,
3819                            cx,
3820                        );
3821                        if gutter_settings.code_actions {
3822                            code_actions_indicator = self.layout_code_actions_indicator(
3823                                line_height,
3824                                newest_selection_head,
3825                                scroll_pixel_position,
3826                                &gutter_dimensions,
3827                                &gutter_hitbox,
3828                                cx,
3829                            );
3830                        }
3831                    }
3832                }
3833
3834                if !context_menu_visible && !cx.has_active_drag() {
3835                    self.layout_hover_popovers(
3836                        &snapshot,
3837                        &hitbox,
3838                        &text_hitbox,
3839                        start_row..end_row,
3840                        content_origin,
3841                        scroll_pixel_position,
3842                        &line_layouts,
3843                        line_height,
3844                        em_width,
3845                        cx,
3846                    );
3847                }
3848
3849                let mouse_context_menu = self.layout_mouse_context_menu(cx);
3850
3851                let fold_indicators = if gutter_settings.folds {
3852                    cx.with_element_id(Some("gutter_fold_indicators"), |cx| {
3853                        self.layout_gutter_fold_indicators(
3854                            fold_statuses,
3855                            line_height,
3856                            &gutter_dimensions,
3857                            gutter_settings,
3858                            scroll_pixel_position,
3859                            &gutter_hitbox,
3860                            cx,
3861                        )
3862                    })
3863                } else {
3864                    Vec::new()
3865                };
3866
3867                let invisible_symbol_font_size = font_size / 2.;
3868                let tab_invisible = cx
3869                    .text_system()
3870                    .shape_line(
3871                        "".into(),
3872                        invisible_symbol_font_size,
3873                        &[TextRun {
3874                            len: "".len(),
3875                            font: self.style.text.font(),
3876                            color: cx.theme().colors().editor_invisible,
3877                            background_color: None,
3878                            underline: None,
3879                            strikethrough: None,
3880                        }],
3881                    )
3882                    .unwrap();
3883                let space_invisible = cx
3884                    .text_system()
3885                    .shape_line(
3886                        "".into(),
3887                        invisible_symbol_font_size,
3888                        &[TextRun {
3889                            len: "".len(),
3890                            font: self.style.text.font(),
3891                            color: cx.theme().colors().editor_invisible,
3892                            background_color: None,
3893                            underline: None,
3894                            strikethrough: None,
3895                        }],
3896                    )
3897                    .unwrap();
3898
3899                EditorLayout {
3900                    mode: snapshot.mode,
3901                    position_map: Arc::new(PositionMap {
3902                        size: bounds.size,
3903                        scroll_pixel_position,
3904                        scroll_max,
3905                        line_layouts,
3906                        line_height,
3907                        em_width,
3908                        em_advance,
3909                        snapshot,
3910                    }),
3911                    visible_display_row_range: start_row..end_row,
3912                    wrap_guides,
3913                    hitbox,
3914                    text_hitbox,
3915                    gutter_hitbox,
3916                    gutter_dimensions,
3917                    content_origin,
3918                    scrollbar_layout,
3919                    max_row,
3920                    active_rows,
3921                    highlighted_rows,
3922                    highlighted_ranges,
3923                    redacted_ranges,
3924                    line_numbers,
3925                    display_hunks,
3926                    blamed_display_rows,
3927                    inline_blame,
3928                    folds,
3929                    blocks,
3930                    cursors,
3931                    selections,
3932                    mouse_context_menu,
3933                    code_actions_indicator,
3934                    fold_indicators,
3935                    tab_invisible,
3936                    space_invisible,
3937                }
3938            })
3939        })
3940    }
3941
3942    fn paint(
3943        &mut self,
3944        bounds: Bounds<gpui::Pixels>,
3945        _: &mut Self::BeforeLayout,
3946        layout: &mut Self::AfterLayout,
3947        cx: &mut ElementContext,
3948    ) {
3949        let focus_handle = self.editor.focus_handle(cx);
3950        let key_context = self.editor.read(cx).key_context(cx);
3951        cx.set_focus_handle(&focus_handle);
3952        cx.set_key_context(key_context);
3953        cx.set_view_id(self.editor.entity_id());
3954        cx.handle_input(
3955            &focus_handle,
3956            ElementInputHandler::new(bounds, self.editor.clone()),
3957        );
3958        self.register_actions(cx);
3959        self.register_key_listeners(cx, layout);
3960
3961        let text_style = TextStyleRefinement {
3962            font_size: Some(self.style.text.font_size),
3963            line_height: Some(self.style.text.line_height),
3964            ..Default::default()
3965        };
3966        cx.with_text_style(Some(text_style), |cx| {
3967            cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
3968                self.paint_mouse_listeners(layout, cx);
3969
3970                self.paint_background(layout, cx);
3971                if layout.gutter_hitbox.size.width > Pixels::ZERO {
3972                    self.paint_gutter(layout, cx);
3973                }
3974                self.paint_text(layout, cx);
3975
3976                if !layout.blocks.is_empty() {
3977                    cx.with_element_id(Some("blocks"), |cx| {
3978                        self.paint_blocks(layout, cx);
3979                    });
3980                }
3981
3982                self.paint_scrollbar(layout, cx);
3983                self.paint_mouse_context_menu(layout, cx);
3984            });
3985        })
3986    }
3987}
3988
3989impl IntoElement for EditorElement {
3990    type Element = Self;
3991
3992    fn into_element(self) -> Self::Element {
3993        self
3994    }
3995}
3996
3997type BufferRow = u32;
3998
3999pub struct EditorLayout {
4000    position_map: Arc<PositionMap>,
4001    hitbox: Hitbox,
4002    text_hitbox: Hitbox,
4003    gutter_hitbox: Hitbox,
4004    gutter_dimensions: GutterDimensions,
4005    content_origin: gpui::Point<Pixels>,
4006    scrollbar_layout: Option<ScrollbarLayout>,
4007    mode: EditorMode,
4008    wrap_guides: SmallVec<[(Pixels, bool); 2]>,
4009    visible_display_row_range: Range<u32>,
4010    active_rows: BTreeMap<u32, bool>,
4011    highlighted_rows: BTreeMap<u32, Hsla>,
4012    line_numbers: Vec<Option<ShapedLine>>,
4013    display_hunks: Vec<DisplayDiffHunk>,
4014    blamed_display_rows: Option<Vec<AnyElement>>,
4015    inline_blame: Option<AnyElement>,
4016    folds: Vec<FoldLayout>,
4017    blocks: Vec<BlockLayout>,
4018    highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
4019    redacted_ranges: Vec<Range<DisplayPoint>>,
4020    cursors: Vec<CursorLayout>,
4021    selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
4022    max_row: u32,
4023    code_actions_indicator: Option<AnyElement>,
4024    fold_indicators: Vec<Option<AnyElement>>,
4025    mouse_context_menu: Option<AnyElement>,
4026    tab_invisible: ShapedLine,
4027    space_invisible: ShapedLine,
4028}
4029
4030impl EditorLayout {
4031    fn line_end_overshoot(&self) -> Pixels {
4032        0.15 * self.position_map.line_height
4033    }
4034}
4035
4036struct ColoredRange<T> {
4037    start: T,
4038    end: T,
4039    color: Hsla,
4040}
4041
4042#[derive(Clone)]
4043struct ScrollbarLayout {
4044    hitbox: Hitbox,
4045    visible_row_range: Range<f32>,
4046    visible: bool,
4047    height: Pixels,
4048    scroll_height: f32,
4049    first_row_y_offset: Pixels,
4050    row_height: Pixels,
4051}
4052
4053impl ScrollbarLayout {
4054    const BORDER_WIDTH: Pixels = px(1.0);
4055    const MIN_MARKER_HEIGHT: Pixels = px(2.0);
4056
4057    fn thumb_bounds(&self) -> Bounds<Pixels> {
4058        let thumb_top = self.y_for_row(self.visible_row_range.start) - self.first_row_y_offset;
4059        let thumb_bottom = self.y_for_row(self.visible_row_range.end) + self.first_row_y_offset;
4060        Bounds::from_corners(
4061            point(self.hitbox.left(), thumb_top),
4062            point(self.hitbox.right(), thumb_bottom),
4063        )
4064    }
4065
4066    fn y_for_row(&self, row: f32) -> Pixels {
4067        self.hitbox.top() + self.first_row_y_offset + row * self.row_height
4068    }
4069
4070    fn marker_quads_for_ranges(
4071        &self,
4072        row_ranges: impl IntoIterator<Item = ColoredRange<u32>>,
4073        column: usize,
4074    ) -> Vec<PaintQuad> {
4075        let column_width =
4076            px(((self.hitbox.size.width - ScrollbarLayout::BORDER_WIDTH).0 / 3.0).floor());
4077
4078        let left_x = ScrollbarLayout::BORDER_WIDTH + (column as f32 * column_width);
4079        let right_x = left_x + column_width;
4080
4081        let mut background_pixel_ranges = row_ranges
4082            .into_iter()
4083            .map(|range| {
4084                let start_y = self.first_row_y_offset + range.start as f32 * self.row_height;
4085                let end_y = self.first_row_y_offset + (range.end + 1) as f32 * self.row_height;
4086                ColoredRange {
4087                    start: start_y,
4088                    end: end_y,
4089                    color: range.color,
4090                }
4091            })
4092            .peekable();
4093
4094        let mut quads = Vec::new();
4095        while let Some(mut pixel_range) = background_pixel_ranges.next() {
4096            pixel_range.end = pixel_range
4097                .end
4098                .max(pixel_range.start + Self::MIN_MARKER_HEIGHT);
4099            while let Some(next_pixel_range) = background_pixel_ranges.peek() {
4100                if pixel_range.end >= next_pixel_range.start
4101                    && pixel_range.color == next_pixel_range.color
4102                {
4103                    pixel_range.end = next_pixel_range.end.max(pixel_range.end);
4104                    background_pixel_ranges.next();
4105                } else {
4106                    break;
4107                }
4108            }
4109
4110            let bounds = Bounds::from_corners(
4111                point(left_x, pixel_range.start),
4112                point(right_x, pixel_range.end),
4113            );
4114            quads.push(quad(
4115                bounds,
4116                Corners::default(),
4117                pixel_range.color,
4118                Edges::default(),
4119                Hsla::transparent_black(),
4120            ));
4121        }
4122
4123        quads
4124    }
4125}
4126
4127struct FoldLayout {
4128    display_range: Range<DisplayPoint>,
4129    hover_element: AnyElement,
4130}
4131
4132struct PositionMap {
4133    size: Size<Pixels>,
4134    line_height: Pixels,
4135    scroll_pixel_position: gpui::Point<Pixels>,
4136    scroll_max: gpui::Point<f32>,
4137    em_width: Pixels,
4138    em_advance: Pixels,
4139    line_layouts: Vec<LineWithInvisibles>,
4140    snapshot: EditorSnapshot,
4141}
4142
4143#[derive(Debug, Copy, Clone)]
4144pub struct PointForPosition {
4145    pub previous_valid: DisplayPoint,
4146    pub next_valid: DisplayPoint,
4147    pub exact_unclipped: DisplayPoint,
4148    pub column_overshoot_after_line_end: u32,
4149}
4150
4151impl PointForPosition {
4152    pub fn as_valid(&self) -> Option<DisplayPoint> {
4153        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
4154            Some(self.previous_valid)
4155        } else {
4156            None
4157        }
4158    }
4159}
4160
4161impl PositionMap {
4162    fn point_for_position(
4163        &self,
4164        text_bounds: Bounds<Pixels>,
4165        position: gpui::Point<Pixels>,
4166    ) -> PointForPosition {
4167        let scroll_position = self.snapshot.scroll_position();
4168        let position = position - text_bounds.origin;
4169        let y = position.y.max(px(0.)).min(self.size.height);
4170        let x = position.x + (scroll_position.x * self.em_width);
4171        let row = ((y / self.line_height) + scroll_position.y) as u32;
4172
4173        let (column, x_overshoot_after_line_end) = if let Some(line) = self
4174            .line_layouts
4175            .get(row as usize - scroll_position.y as usize)
4176            .map(|LineWithInvisibles { line, .. }| line)
4177        {
4178            if let Some(ix) = line.index_for_x(x) {
4179                (ix as u32, px(0.))
4180            } else {
4181                (line.len as u32, px(0.).max(x - line.width))
4182            }
4183        } else {
4184            (0, x)
4185        };
4186
4187        let mut exact_unclipped = DisplayPoint::new(row, column);
4188        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
4189        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
4190
4191        let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
4192        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
4193        PointForPosition {
4194            previous_valid,
4195            next_valid,
4196            exact_unclipped,
4197            column_overshoot_after_line_end,
4198        }
4199    }
4200}
4201
4202struct BlockLayout {
4203    row: u32,
4204    element: AnyElement,
4205    available_space: Size<AvailableSpace>,
4206    style: BlockStyle,
4207}
4208
4209fn layout_line(
4210    row: u32,
4211    snapshot: &EditorSnapshot,
4212    style: &EditorStyle,
4213    cx: &WindowContext,
4214) -> Result<ShapedLine> {
4215    let mut line = snapshot.line(row);
4216
4217    if line.len() > MAX_LINE_LEN {
4218        let mut len = MAX_LINE_LEN;
4219        while !line.is_char_boundary(len) {
4220            len -= 1;
4221        }
4222
4223        line.truncate(len);
4224    }
4225
4226    cx.text_system().shape_line(
4227        line.into(),
4228        style.text.font_size.to_pixels(cx.rem_size()),
4229        &[TextRun {
4230            len: snapshot.line_len(row) as usize,
4231            font: style.text.font(),
4232            color: Hsla::default(),
4233            background_color: None,
4234            underline: None,
4235            strikethrough: None,
4236        }],
4237    )
4238}
4239
4240pub struct CursorLayout {
4241    origin: gpui::Point<Pixels>,
4242    block_width: Pixels,
4243    line_height: Pixels,
4244    color: Hsla,
4245    shape: CursorShape,
4246    block_text: Option<ShapedLine>,
4247    cursor_name: Option<AnyElement>,
4248}
4249
4250#[derive(Debug)]
4251pub struct CursorName {
4252    string: SharedString,
4253    color: Hsla,
4254    is_top_row: bool,
4255}
4256
4257impl CursorLayout {
4258    pub fn new(
4259        origin: gpui::Point<Pixels>,
4260        block_width: Pixels,
4261        line_height: Pixels,
4262        color: Hsla,
4263        shape: CursorShape,
4264        block_text: Option<ShapedLine>,
4265    ) -> CursorLayout {
4266        CursorLayout {
4267            origin,
4268            block_width,
4269            line_height,
4270            color,
4271            shape,
4272            block_text,
4273            cursor_name: None,
4274        }
4275    }
4276
4277    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
4278        Bounds {
4279            origin: self.origin + origin,
4280            size: size(self.block_width, self.line_height),
4281        }
4282    }
4283
4284    fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
4285        match self.shape {
4286            CursorShape::Bar => Bounds {
4287                origin: self.origin + origin,
4288                size: size(px(2.0), self.line_height),
4289            },
4290            CursorShape::Block | CursorShape::Hollow => Bounds {
4291                origin: self.origin + origin,
4292                size: size(self.block_width, self.line_height),
4293            },
4294            CursorShape::Underscore => Bounds {
4295                origin: self.origin
4296                    + origin
4297                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
4298                size: size(self.block_width, px(2.0)),
4299            },
4300        }
4301    }
4302
4303    pub fn layout(
4304        &mut self,
4305        origin: gpui::Point<Pixels>,
4306        cursor_name: Option<CursorName>,
4307        cx: &mut ElementContext,
4308    ) {
4309        if let Some(cursor_name) = cursor_name {
4310            let bounds = self.bounds(origin);
4311            let text_size = self.line_height / 1.5;
4312
4313            let name_origin = if cursor_name.is_top_row {
4314                point(bounds.right() - px(1.), bounds.top())
4315            } else {
4316                point(bounds.left(), bounds.top() - text_size / 2. - px(1.))
4317            };
4318            let mut name_element = div()
4319                .bg(self.color)
4320                .text_size(text_size)
4321                .px_0p5()
4322                .line_height(text_size + px(2.))
4323                .text_color(cursor_name.color)
4324                .child(cursor_name.string.clone())
4325                .into_any_element();
4326
4327            name_element.layout(
4328                name_origin,
4329                size(AvailableSpace::MinContent, AvailableSpace::MinContent),
4330                cx,
4331            );
4332
4333            self.cursor_name = Some(name_element);
4334        }
4335    }
4336
4337    pub fn paint(&mut self, origin: gpui::Point<Pixels>, cx: &mut ElementContext) {
4338        let bounds = self.bounds(origin);
4339
4340        //Draw background or border quad
4341        let cursor = if matches!(self.shape, CursorShape::Hollow) {
4342            outline(bounds, self.color)
4343        } else {
4344            fill(bounds, self.color)
4345        };
4346
4347        if let Some(name) = &mut self.cursor_name {
4348            name.paint(cx);
4349        }
4350
4351        cx.paint_quad(cursor);
4352
4353        if let Some(block_text) = &self.block_text {
4354            block_text
4355                .paint(self.origin + origin, self.line_height, cx)
4356                .log_err();
4357        }
4358    }
4359
4360    pub fn shape(&self) -> CursorShape {
4361        self.shape
4362    }
4363}
4364
4365#[derive(Debug)]
4366pub struct HighlightedRange {
4367    pub start_y: Pixels,
4368    pub line_height: Pixels,
4369    pub lines: Vec<HighlightedRangeLine>,
4370    pub color: Hsla,
4371    pub corner_radius: Pixels,
4372}
4373
4374#[derive(Debug)]
4375pub struct HighlightedRangeLine {
4376    pub start_x: Pixels,
4377    pub end_x: Pixels,
4378}
4379
4380impl HighlightedRange {
4381    pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut ElementContext) {
4382        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
4383            self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
4384            self.paint_lines(
4385                self.start_y + self.line_height,
4386                &self.lines[1..],
4387                bounds,
4388                cx,
4389            );
4390        } else {
4391            self.paint_lines(self.start_y, &self.lines, bounds, cx);
4392        }
4393    }
4394
4395    fn paint_lines(
4396        &self,
4397        start_y: Pixels,
4398        lines: &[HighlightedRangeLine],
4399        _bounds: Bounds<Pixels>,
4400        cx: &mut ElementContext,
4401    ) {
4402        if lines.is_empty() {
4403            return;
4404        }
4405
4406        let first_line = lines.first().unwrap();
4407        let last_line = lines.last().unwrap();
4408
4409        let first_top_left = point(first_line.start_x, start_y);
4410        let first_top_right = point(first_line.end_x, start_y);
4411
4412        let curve_height = point(Pixels::ZERO, self.corner_radius);
4413        let curve_width = |start_x: Pixels, end_x: Pixels| {
4414            let max = (end_x - start_x) / 2.;
4415            let width = if max < self.corner_radius {
4416                max
4417            } else {
4418                self.corner_radius
4419            };
4420
4421            point(width, Pixels::ZERO)
4422        };
4423
4424        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
4425        let mut path = gpui::Path::new(first_top_right - top_curve_width);
4426        path.curve_to(first_top_right + curve_height, first_top_right);
4427
4428        let mut iter = lines.iter().enumerate().peekable();
4429        while let Some((ix, line)) = iter.next() {
4430            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
4431
4432            if let Some((_, next_line)) = iter.peek() {
4433                let next_top_right = point(next_line.end_x, bottom_right.y);
4434
4435                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
4436                    Ordering::Equal => {
4437                        path.line_to(bottom_right);
4438                    }
4439                    Ordering::Less => {
4440                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
4441                        path.line_to(bottom_right - curve_height);
4442                        if self.corner_radius > Pixels::ZERO {
4443                            path.curve_to(bottom_right - curve_width, bottom_right);
4444                        }
4445                        path.line_to(next_top_right + curve_width);
4446                        if self.corner_radius > Pixels::ZERO {
4447                            path.curve_to(next_top_right + curve_height, next_top_right);
4448                        }
4449                    }
4450                    Ordering::Greater => {
4451                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
4452                        path.line_to(bottom_right - curve_height);
4453                        if self.corner_radius > Pixels::ZERO {
4454                            path.curve_to(bottom_right + curve_width, bottom_right);
4455                        }
4456                        path.line_to(next_top_right - curve_width);
4457                        if self.corner_radius > Pixels::ZERO {
4458                            path.curve_to(next_top_right + curve_height, next_top_right);
4459                        }
4460                    }
4461                }
4462            } else {
4463                let curve_width = curve_width(line.start_x, line.end_x);
4464                path.line_to(bottom_right - curve_height);
4465                if self.corner_radius > Pixels::ZERO {
4466                    path.curve_to(bottom_right - curve_width, bottom_right);
4467                }
4468
4469                let bottom_left = point(line.start_x, bottom_right.y);
4470                path.line_to(bottom_left + curve_width);
4471                if self.corner_radius > Pixels::ZERO {
4472                    path.curve_to(bottom_left - curve_height, bottom_left);
4473                }
4474            }
4475        }
4476
4477        if first_line.start_x > last_line.start_x {
4478            let curve_width = curve_width(last_line.start_x, first_line.start_x);
4479            let second_top_left = point(last_line.start_x, start_y + self.line_height);
4480            path.line_to(second_top_left + curve_height);
4481            if self.corner_radius > Pixels::ZERO {
4482                path.curve_to(second_top_left + curve_width, second_top_left);
4483            }
4484            let first_bottom_left = point(first_line.start_x, second_top_left.y);
4485            path.line_to(first_bottom_left - curve_width);
4486            if self.corner_radius > Pixels::ZERO {
4487                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
4488            }
4489        }
4490
4491        path.line_to(first_top_left + curve_height);
4492        if self.corner_radius > Pixels::ZERO {
4493            path.curve_to(first_top_left + top_curve_width, first_top_left);
4494        }
4495        path.line_to(first_top_right - top_curve_width);
4496
4497        cx.paint_path(path, self.color);
4498    }
4499}
4500
4501pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
4502    (delta.pow(1.5) / 100.0).into()
4503}
4504
4505fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
4506    (delta.pow(1.2) / 300.0).into()
4507}
4508
4509#[cfg(test)]
4510mod tests {
4511    use super::*;
4512    use crate::{
4513        display_map::{BlockDisposition, BlockProperties},
4514        editor_tests::{init_test, update_test_language_settings},
4515        Editor, MultiBuffer,
4516    };
4517    use gpui::TestAppContext;
4518    use language::language_settings;
4519    use log::info;
4520    use std::num::NonZeroU32;
4521    use util::test::sample_text;
4522
4523    #[gpui::test]
4524    fn test_shape_line_numbers(cx: &mut TestAppContext) {
4525        init_test(cx, |_| {});
4526        let window = cx.add_window(|cx| {
4527            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
4528            Editor::new(EditorMode::Full, buffer, None, cx)
4529        });
4530
4531        let editor = window.root(cx).unwrap();
4532        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4533        let element = EditorElement::new(&editor, style);
4534        let snapshot = window.update(cx, |editor, cx| editor.snapshot(cx)).unwrap();
4535
4536        let layouts = cx
4537            .update_window(*window, |_, cx| {
4538                cx.with_element_context(|cx| {
4539                    element
4540                        .layout_line_numbers(
4541                            0..6,
4542                            (0..6).map(Some),
4543                            &Default::default(),
4544                            Some(DisplayPoint::new(0, 0)),
4545                            &snapshot,
4546                            cx,
4547                        )
4548                        .0
4549                })
4550            })
4551            .unwrap();
4552        assert_eq!(layouts.len(), 6);
4553
4554        let relative_rows =
4555            element.calculate_relative_line_numbers((0..6).map(Some).collect(), &(0..6), Some(3));
4556        assert_eq!(relative_rows[&0], 3);
4557        assert_eq!(relative_rows[&1], 2);
4558        assert_eq!(relative_rows[&2], 1);
4559        // current line has no relative number
4560        assert_eq!(relative_rows[&4], 1);
4561        assert_eq!(relative_rows[&5], 2);
4562
4563        // works if cursor is before screen
4564        let relative_rows =
4565            element.calculate_relative_line_numbers((0..6).map(Some).collect(), &(3..6), Some(1));
4566        assert_eq!(relative_rows.len(), 3);
4567        assert_eq!(relative_rows[&3], 2);
4568        assert_eq!(relative_rows[&4], 3);
4569        assert_eq!(relative_rows[&5], 4);
4570
4571        // works if cursor is after screen
4572        let relative_rows =
4573            element.calculate_relative_line_numbers((0..6).map(Some).collect(), &(0..3), Some(6));
4574        assert_eq!(relative_rows.len(), 3);
4575        assert_eq!(relative_rows[&0], 5);
4576        assert_eq!(relative_rows[&1], 4);
4577        assert_eq!(relative_rows[&2], 3);
4578    }
4579
4580    #[gpui::test]
4581    async fn test_vim_visual_selections(cx: &mut TestAppContext) {
4582        init_test(cx, |_| {});
4583
4584        let window = cx.add_window(|cx| {
4585            let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
4586            Editor::new(EditorMode::Full, buffer, None, cx)
4587        });
4588        let editor = window.root(cx).unwrap();
4589        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4590        let mut element = EditorElement::new(&editor, style);
4591
4592        window
4593            .update(cx, |editor, cx| {
4594                editor.cursor_shape = CursorShape::Block;
4595                editor.change_selections(None, cx, |s| {
4596                    s.select_ranges([
4597                        Point::new(0, 0)..Point::new(1, 0),
4598                        Point::new(3, 2)..Point::new(3, 3),
4599                        Point::new(5, 6)..Point::new(6, 0),
4600                    ]);
4601                });
4602            })
4603            .unwrap();
4604        let state = cx
4605            .update_window(window.into(), |_view, cx| {
4606                cx.with_element_context(|cx| {
4607                    element.after_layout(
4608                        Bounds {
4609                            origin: point(px(500.), px(500.)),
4610                            size: size(px(500.), px(500.)),
4611                        },
4612                        &mut (),
4613                        cx,
4614                    )
4615                })
4616            })
4617            .unwrap();
4618
4619        assert_eq!(state.selections.len(), 1);
4620        let local_selections = &state.selections[0].1;
4621        assert_eq!(local_selections.len(), 3);
4622        // moves cursor back one line
4623        assert_eq!(local_selections[0].head, DisplayPoint::new(0, 6));
4624        assert_eq!(
4625            local_selections[0].range,
4626            DisplayPoint::new(0, 0)..DisplayPoint::new(1, 0)
4627        );
4628
4629        // moves cursor back one column
4630        assert_eq!(
4631            local_selections[1].range,
4632            DisplayPoint::new(3, 2)..DisplayPoint::new(3, 3)
4633        );
4634        assert_eq!(local_selections[1].head, DisplayPoint::new(3, 2));
4635
4636        // leaves cursor on the max point
4637        assert_eq!(
4638            local_selections[2].range,
4639            DisplayPoint::new(5, 6)..DisplayPoint::new(6, 0)
4640        );
4641        assert_eq!(local_selections[2].head, DisplayPoint::new(6, 0));
4642
4643        // active lines does not include 1 (even though the range of the selection does)
4644        assert_eq!(
4645            state.active_rows.keys().cloned().collect::<Vec<u32>>(),
4646            vec![0, 3, 5, 6]
4647        );
4648
4649        // multi-buffer support
4650        // in DisplayPoint coordinates, this is what we're dealing with:
4651        //  0: [[file
4652        //  1:   header]]
4653        //  2: aaaaaa
4654        //  3: bbbbbb
4655        //  4: cccccc
4656        //  5:
4657        //  6: ...
4658        //  7: ffffff
4659        //  8: gggggg
4660        //  9: hhhhhh
4661        // 10:
4662        // 11: [[file
4663        // 12:   header]]
4664        // 13: bbbbbb
4665        // 14: cccccc
4666        // 15: dddddd
4667        let window = cx.add_window(|cx| {
4668            let buffer = MultiBuffer::build_multi(
4669                [
4670                    (
4671                        &(sample_text(8, 6, 'a') + "\n"),
4672                        vec![
4673                            Point::new(0, 0)..Point::new(3, 0),
4674                            Point::new(4, 0)..Point::new(7, 0),
4675                        ],
4676                    ),
4677                    (
4678                        &(sample_text(8, 6, 'a') + "\n"),
4679                        vec![Point::new(1, 0)..Point::new(3, 0)],
4680                    ),
4681                ],
4682                cx,
4683            );
4684            Editor::new(EditorMode::Full, buffer, None, cx)
4685        });
4686        let editor = window.root(cx).unwrap();
4687        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4688        let mut element = EditorElement::new(&editor, style);
4689        let _state = window.update(cx, |editor, cx| {
4690            editor.cursor_shape = CursorShape::Block;
4691            editor.change_selections(None, cx, |s| {
4692                s.select_display_ranges([
4693                    DisplayPoint::new(4, 0)..DisplayPoint::new(7, 0),
4694                    DisplayPoint::new(10, 0)..DisplayPoint::new(13, 0),
4695                ]);
4696            });
4697        });
4698
4699        let state = cx
4700            .update_window(window.into(), |_view, cx| {
4701                cx.with_element_context(|cx| {
4702                    element.after_layout(
4703                        Bounds {
4704                            origin: point(px(500.), px(500.)),
4705                            size: size(px(500.), px(500.)),
4706                        },
4707                        &mut (),
4708                        cx,
4709                    )
4710                })
4711            })
4712            .unwrap();
4713        assert_eq!(state.selections.len(), 1);
4714        let local_selections = &state.selections[0].1;
4715        assert_eq!(local_selections.len(), 2);
4716
4717        // moves cursor on excerpt boundary back a line
4718        // and doesn't allow selection to bleed through
4719        assert_eq!(
4720            local_selections[0].range,
4721            DisplayPoint::new(4, 0)..DisplayPoint::new(6, 0)
4722        );
4723        assert_eq!(local_selections[0].head, DisplayPoint::new(5, 0));
4724        // moves cursor on buffer boundary back two lines
4725        // and doesn't allow selection to bleed through
4726        assert_eq!(
4727            local_selections[1].range,
4728            DisplayPoint::new(10, 0)..DisplayPoint::new(11, 0)
4729        );
4730        assert_eq!(local_selections[1].head, DisplayPoint::new(10, 0));
4731    }
4732
4733    #[gpui::test]
4734    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
4735        init_test(cx, |_| {});
4736
4737        let window = cx.add_window(|cx| {
4738            let buffer = MultiBuffer::build_simple("", cx);
4739            Editor::new(EditorMode::Full, buffer, None, cx)
4740        });
4741        let editor = window.root(cx).unwrap();
4742        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4743        window
4744            .update(cx, |editor, cx| {
4745                editor.set_placeholder_text("hello", cx);
4746                editor.insert_blocks(
4747                    [BlockProperties {
4748                        style: BlockStyle::Fixed,
4749                        disposition: BlockDisposition::Above,
4750                        height: 3,
4751                        position: Anchor::min(),
4752                        render: Box::new(|_| div().into_any()),
4753                    }],
4754                    None,
4755                    cx,
4756                );
4757
4758                // Blur the editor so that it displays placeholder text.
4759                cx.blur();
4760            })
4761            .unwrap();
4762
4763        let mut element = EditorElement::new(&editor, style);
4764        let state = cx
4765            .update_window(window.into(), |_view, cx| {
4766                cx.with_element_context(|cx| {
4767                    element.after_layout(
4768                        Bounds {
4769                            origin: point(px(500.), px(500.)),
4770                            size: size(px(500.), px(500.)),
4771                        },
4772                        &mut (),
4773                        cx,
4774                    )
4775                })
4776            })
4777            .unwrap();
4778
4779        assert_eq!(state.position_map.line_layouts.len(), 4);
4780        assert_eq!(
4781            state
4782                .line_numbers
4783                .iter()
4784                .map(Option::is_some)
4785                .collect::<Vec<_>>(),
4786            &[false, false, false, true]
4787        );
4788    }
4789
4790    #[gpui::test]
4791    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
4792        const TAB_SIZE: u32 = 4;
4793
4794        let input_text = "\t \t|\t| a b";
4795        let expected_invisibles = vec![
4796            Invisible::Tab {
4797                line_start_offset: 0,
4798            },
4799            Invisible::Whitespace {
4800                line_offset: TAB_SIZE as usize,
4801            },
4802            Invisible::Tab {
4803                line_start_offset: TAB_SIZE as usize + 1,
4804            },
4805            Invisible::Tab {
4806                line_start_offset: TAB_SIZE as usize * 2 + 1,
4807            },
4808            Invisible::Whitespace {
4809                line_offset: TAB_SIZE as usize * 3 + 1,
4810            },
4811            Invisible::Whitespace {
4812                line_offset: TAB_SIZE as usize * 3 + 3,
4813            },
4814        ];
4815        assert_eq!(
4816            expected_invisibles.len(),
4817            input_text
4818                .chars()
4819                .filter(|initial_char| initial_char.is_whitespace())
4820                .count(),
4821            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
4822        );
4823
4824        init_test(cx, |s| {
4825            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4826            s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
4827        });
4828
4829        let actual_invisibles =
4830            collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, px(500.0));
4831
4832        assert_eq!(expected_invisibles, actual_invisibles);
4833    }
4834
4835    #[gpui::test]
4836    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
4837        init_test(cx, |s| {
4838            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4839            s.defaults.tab_size = NonZeroU32::new(4);
4840        });
4841
4842        for editor_mode_without_invisibles in [
4843            EditorMode::SingleLine,
4844            EditorMode::AutoHeight { max_lines: 100 },
4845        ] {
4846            let invisibles = collect_invisibles_from_new_editor(
4847                cx,
4848                editor_mode_without_invisibles,
4849                "\t\t\t| | a b",
4850                px(500.0),
4851            );
4852            assert!(invisibles.is_empty(),
4853                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
4854        }
4855    }
4856
4857    #[gpui::test]
4858    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
4859        let tab_size = 4;
4860        let input_text = "a\tbcd   ".repeat(9);
4861        let repeated_invisibles = [
4862            Invisible::Tab {
4863                line_start_offset: 1,
4864            },
4865            Invisible::Whitespace {
4866                line_offset: tab_size as usize + 3,
4867            },
4868            Invisible::Whitespace {
4869                line_offset: tab_size as usize + 4,
4870            },
4871            Invisible::Whitespace {
4872                line_offset: tab_size as usize + 5,
4873            },
4874        ];
4875        let expected_invisibles = std::iter::once(repeated_invisibles)
4876            .cycle()
4877            .take(9)
4878            .flatten()
4879            .collect::<Vec<_>>();
4880        assert_eq!(
4881            expected_invisibles.len(),
4882            input_text
4883                .chars()
4884                .filter(|initial_char| initial_char.is_whitespace())
4885                .count(),
4886            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
4887        );
4888        info!("Expected invisibles: {expected_invisibles:?}");
4889
4890        init_test(cx, |_| {});
4891
4892        // Put the same string with repeating whitespace pattern into editors of various size,
4893        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
4894        let resize_step = 10.0;
4895        let mut editor_width = 200.0;
4896        while editor_width <= 1000.0 {
4897            update_test_language_settings(cx, |s| {
4898                s.defaults.tab_size = NonZeroU32::new(tab_size);
4899                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4900                s.defaults.preferred_line_length = Some(editor_width as u32);
4901                s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
4902            });
4903
4904            let actual_invisibles = collect_invisibles_from_new_editor(
4905                cx,
4906                EditorMode::Full,
4907                &input_text,
4908                px(editor_width),
4909            );
4910
4911            // Whatever the editor size is, ensure it has the same invisible kinds in the same order
4912            // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
4913            let mut i = 0;
4914            for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
4915                i = actual_index;
4916                match expected_invisibles.get(i) {
4917                    Some(expected_invisible) => match (expected_invisible, actual_invisible) {
4918                        (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
4919                        | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
4920                        _ => {
4921                            panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
4922                        }
4923                    },
4924                    None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
4925                }
4926            }
4927            let missing_expected_invisibles = &expected_invisibles[i + 1..];
4928            assert!(
4929                missing_expected_invisibles.is_empty(),
4930                "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
4931            );
4932
4933            editor_width += resize_step;
4934        }
4935    }
4936
4937    fn collect_invisibles_from_new_editor(
4938        cx: &mut TestAppContext,
4939        editor_mode: EditorMode,
4940        input_text: &str,
4941        editor_width: Pixels,
4942    ) -> Vec<Invisible> {
4943        info!(
4944            "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
4945            editor_width.0
4946        );
4947        let window = cx.add_window(|cx| {
4948            let buffer = MultiBuffer::build_simple(&input_text, cx);
4949            Editor::new(editor_mode, buffer, None, cx)
4950        });
4951        let editor = window.root(cx).unwrap();
4952        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4953        let mut element = EditorElement::new(&editor, style);
4954        window
4955            .update(cx, |editor, cx| {
4956                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
4957                editor.set_wrap_width(Some(editor_width), cx);
4958            })
4959            .unwrap();
4960        let layout_state = cx
4961            .update_window(window.into(), |_, cx| {
4962                cx.with_element_context(|cx| {
4963                    element.after_layout(
4964                        Bounds {
4965                            origin: point(px(500.), px(500.)),
4966                            size: size(px(500.), px(500.)),
4967                        },
4968                        &mut (),
4969                        cx,
4970                    )
4971                })
4972            })
4973            .unwrap();
4974
4975        layout_state
4976            .position_map
4977            .line_layouts
4978            .iter()
4979            .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
4980            .cloned()
4981            .collect()
4982    }
4983}
4984
4985pub fn register_action<T: Action>(
4986    view: &View<Editor>,
4987    cx: &mut WindowContext,
4988    listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
4989) {
4990    let view = view.clone();
4991    cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
4992        let action = action.downcast_ref().unwrap();
4993        if phase == DispatchPhase::Bubble {
4994            view.update(cx, |editor, cx| {
4995                listener(editor, action, cx);
4996            })
4997        }
4998    })
4999}
5000
5001fn compute_auto_height_layout(
5002    editor: &mut Editor,
5003    max_lines: usize,
5004    max_line_number_width: Pixels,
5005    known_dimensions: Size<Option<Pixels>>,
5006    cx: &mut ViewContext<Editor>,
5007) -> Option<Size<Pixels>> {
5008    let width = known_dimensions.width?;
5009    if let Some(height) = known_dimensions.height {
5010        return Some(size(width, height));
5011    }
5012
5013    let style = editor.style.as_ref().unwrap();
5014    let font_id = cx.text_system().resolve_font(&style.text.font());
5015    let font_size = style.text.font_size.to_pixels(cx.rem_size());
5016    let line_height = style.text.line_height_in_pixels(cx.rem_size());
5017    let em_width = cx
5018        .text_system()
5019        .typographic_bounds(font_id, font_size, 'm')
5020        .unwrap()
5021        .size
5022        .width;
5023
5024    let mut snapshot = editor.snapshot(cx);
5025    let gutter_dimensions =
5026        snapshot.gutter_dimensions(font_id, font_size, em_width, max_line_number_width, cx);
5027
5028    editor.gutter_width = gutter_dimensions.width;
5029    let text_width = width - gutter_dimensions.width;
5030    let overscroll = size(em_width, px(0.));
5031
5032    let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
5033    if editor.set_wrap_width(Some(editor_width), cx) {
5034        snapshot = editor.snapshot(cx);
5035    }
5036
5037    let scroll_height = Pixels::from(snapshot.max_point().row() + 1) * line_height;
5038    let height = scroll_height
5039        .max(line_height)
5040        .min(line_height * max_lines as f32);
5041
5042    Some(size(width, height))
5043}