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