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