element.rs

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