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