element.rs

   1use crate::editor_settings::ScrollBeyondLastLine;
   2use crate::{
   3    blame_entry_tooltip::{blame_entry_relative_timestamp, BlameEntryTooltip},
   4    display_map::{
   5        BlockContext, BlockStyle, DisplaySnapshot, HighlightedChunk, ToDisplayPoint, TransformBlock,
   6    },
   7    editor_settings::{
   8        CurrentLineHighlight, DoubleClickInMultibuffer, MultiCursorModifier, ShowScrollbar,
   9    },
  10    git::{
  11        blame::{CommitDetails, GitBlame},
  12        diff_hunk_to_display, DisplayDiffHunk,
  13    },
  14    hover_popover::{
  15        self, hover_at, HOVER_POPOVER_GAP, MIN_POPOVER_CHARACTER_WIDTH, MIN_POPOVER_LINE_HEIGHT,
  16    },
  17    hunk_status,
  18    items::BufferSearchHighlights,
  19    mouse_context_menu::{self, MouseContextMenu},
  20    scroll::scroll_amount::ScrollAmount,
  21    CodeActionsMenu, CursorShape, DisplayPoint, DisplayRow, DocumentHighlightRead,
  22    DocumentHighlightWrite, Editor, EditorMode, EditorSettings, EditorSnapshot, EditorStyle,
  23    ExpandExcerpts, GutterDimensions, HalfPageDown, HalfPageUp, HoveredCursor, HunkToExpand,
  24    LineDown, LineUp, OpenExcerpts, PageDown, PageUp, Point, RowExt, RowRangeExt, SelectPhase,
  25    Selection, SoftWrap, ToPoint, CURSORS_VISIBLE_FOR, MAX_LINE_LEN,
  26};
  27use client::ParticipantIndex;
  28use collections::{BTreeMap, HashMap};
  29use git::{blame::BlameEntry, diff::DiffHunkStatus, Oid};
  30use gpui::{
  31    anchored, deferred, div, fill, outline, point, px, quad, relative, size, svg,
  32    transparent_black, Action, AnchorCorner, AnyElement, AvailableSpace, Bounds, ClipboardItem,
  33    ContentMask, Corners, CursorStyle, DispatchPhase, Edges, Element, ElementInputHandler, Entity,
  34    FontId, GlobalElementId, Hitbox, Hsla, InteractiveElement, IntoElement, Length,
  35    ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PaintQuad,
  36    ParentElement, Pixels, ScrollDelta, ScrollWheelEvent, ShapedLine, SharedString, Size,
  37    StatefulInteractiveElement, Style, Styled, TextRun, TextStyle, TextStyleRefinement, View,
  38    ViewContext, WeakView, WindowContext,
  39};
  40use itertools::Itertools;
  41use language::language_settings::{
  42    IndentGuideBackgroundColoring, IndentGuideColoring, IndentGuideSettings, ShowWhitespaceSetting,
  43};
  44use lsp::DiagnosticSeverity;
  45use multi_buffer::{Anchor, MultiBufferPoint, MultiBufferRow};
  46use project::{
  47    project_settings::{GitGutterSetting, ProjectSettings},
  48    ProjectPath,
  49};
  50use settings::Settings;
  51use smallvec::{smallvec, SmallVec};
  52use std::{
  53    any::TypeId,
  54    borrow::Cow,
  55    cmp::{self, Ordering},
  56    fmt::{self, Write},
  57    iter, mem,
  58    ops::{Deref, Range},
  59    sync::Arc,
  60};
  61use sum_tree::Bias;
  62use theme::{ActiveTheme, PlayerColor};
  63use ui::prelude::*;
  64use ui::{h_flex, ButtonLike, ButtonStyle, ContextMenu, Tooltip};
  65use util::ResultExt;
  66use workspace::{item::Item, Workspace};
  67
  68struct SelectionLayout {
  69    head: DisplayPoint,
  70    cursor_shape: CursorShape,
  71    is_newest: bool,
  72    is_local: bool,
  73    range: Range<DisplayPoint>,
  74    active_rows: Range<DisplayRow>,
  75    user_name: Option<SharedString>,
  76}
  77
  78impl SelectionLayout {
  79    fn new<T: ToPoint + ToDisplayPoint + Clone>(
  80        selection: Selection<T>,
  81        line_mode: bool,
  82        cursor_shape: CursorShape,
  83        map: &DisplaySnapshot,
  84        is_newest: bool,
  85        is_local: bool,
  86        user_name: Option<SharedString>,
  87    ) -> Self {
  88        let point_selection = selection.map(|p| p.to_point(&map.buffer_snapshot));
  89        let display_selection = point_selection.map(|p| p.to_display_point(map));
  90        let mut range = display_selection.range();
  91        let mut head = display_selection.head();
  92        let mut active_rows = map.prev_line_boundary(point_selection.start).1.row()
  93            ..map.next_line_boundary(point_selection.end).1.row();
  94
  95        // vim visual line mode
  96        if line_mode {
  97            let point_range = map.expand_to_line(point_selection.range());
  98            range = point_range.start.to_display_point(map)..point_range.end.to_display_point(map);
  99        }
 100
 101        // any vim visual mode (including line mode)
 102        if (cursor_shape == CursorShape::Block || cursor_shape == CursorShape::Hollow)
 103            && !range.is_empty()
 104            && !selection.reversed
 105        {
 106            if head.column() > 0 {
 107                head = map.clip_point(DisplayPoint::new(head.row(), head.column() - 1), Bias::Left)
 108            } else if head.row().0 > 0 && head != map.max_point() {
 109                head = map.clip_point(
 110                    DisplayPoint::new(
 111                        head.row().previous_row(),
 112                        map.line_len(head.row().previous_row()),
 113                    ),
 114                    Bias::Left,
 115                );
 116                // updating range.end is a no-op unless you're cursor is
 117                // on the newline containing a multi-buffer divider
 118                // in which case the clip_point may have moved the head up
 119                // an additional row.
 120                range.end = DisplayPoint::new(head.row().next_row(), 0);
 121                active_rows.end = head.row();
 122            }
 123        }
 124
 125        Self {
 126            head,
 127            cursor_shape,
 128            is_newest,
 129            is_local,
 130            range,
 131            active_rows,
 132            user_name,
 133        }
 134    }
 135}
 136
 137pub struct EditorElement {
 138    editor: View<Editor>,
 139    style: EditorStyle,
 140}
 141
 142type DisplayRowDelta = u32;
 143
 144impl EditorElement {
 145    pub(crate) const SCROLLBAR_WIDTH: Pixels = px(13.);
 146
 147    pub fn new(editor: &View<Editor>, style: EditorStyle) -> Self {
 148        Self {
 149            editor: editor.clone(),
 150            style,
 151        }
 152    }
 153
 154    fn register_actions(&self, cx: &mut WindowContext) {
 155        let view = &self.editor;
 156        view.update(cx, |editor, cx| {
 157            for action in editor.editor_actions.borrow().values() {
 158                (action)(cx)
 159            }
 160        });
 161
 162        crate::rust_analyzer_ext::apply_related_actions(view, cx);
 163        register_action(view, cx, Editor::move_left);
 164        register_action(view, cx, Editor::move_right);
 165        register_action(view, cx, Editor::move_down);
 166        register_action(view, cx, Editor::move_down_by_lines);
 167        register_action(view, cx, Editor::select_down_by_lines);
 168        register_action(view, cx, Editor::move_up);
 169        register_action(view, cx, Editor::move_up_by_lines);
 170        register_action(view, cx, Editor::select_up_by_lines);
 171        register_action(view, cx, Editor::select_page_down);
 172        register_action(view, cx, Editor::select_page_up);
 173        register_action(view, cx, Editor::cancel);
 174        register_action(view, cx, Editor::newline);
 175        register_action(view, cx, Editor::newline_above);
 176        register_action(view, cx, Editor::newline_below);
 177        register_action(view, cx, Editor::backspace);
 178        register_action(view, cx, Editor::delete);
 179        register_action(view, cx, Editor::tab);
 180        register_action(view, cx, Editor::tab_prev);
 181        register_action(view, cx, Editor::indent);
 182        register_action(view, cx, Editor::outdent);
 183        register_action(view, cx, Editor::delete_line);
 184        register_action(view, cx, Editor::join_lines);
 185        register_action(view, cx, Editor::sort_lines_case_sensitive);
 186        register_action(view, cx, Editor::sort_lines_case_insensitive);
 187        register_action(view, cx, Editor::reverse_lines);
 188        register_action(view, cx, Editor::shuffle_lines);
 189        register_action(view, cx, Editor::convert_to_upper_case);
 190        register_action(view, cx, Editor::convert_to_lower_case);
 191        register_action(view, cx, Editor::convert_to_title_case);
 192        register_action(view, cx, Editor::convert_to_snake_case);
 193        register_action(view, cx, Editor::convert_to_kebab_case);
 194        register_action(view, cx, Editor::convert_to_upper_camel_case);
 195        register_action(view, cx, Editor::convert_to_lower_camel_case);
 196        register_action(view, cx, Editor::convert_to_opposite_case);
 197        register_action(view, cx, Editor::delete_to_previous_word_start);
 198        register_action(view, cx, Editor::delete_to_previous_subword_start);
 199        register_action(view, cx, Editor::delete_to_next_word_end);
 200        register_action(view, cx, Editor::delete_to_next_subword_end);
 201        register_action(view, cx, Editor::delete_to_beginning_of_line);
 202        register_action(view, cx, Editor::delete_to_end_of_line);
 203        register_action(view, cx, Editor::cut_to_end_of_line);
 204        register_action(view, cx, Editor::duplicate_line_up);
 205        register_action(view, cx, Editor::duplicate_line_down);
 206        register_action(view, cx, Editor::move_line_up);
 207        register_action(view, cx, Editor::move_line_down);
 208        register_action(view, cx, Editor::transpose);
 209        register_action(view, cx, Editor::cut);
 210        register_action(view, cx, Editor::copy);
 211        register_action(view, cx, Editor::paste);
 212        register_action(view, cx, Editor::undo);
 213        register_action(view, cx, Editor::redo);
 214        register_action(view, cx, Editor::move_page_up);
 215        register_action(view, cx, Editor::move_page_down);
 216        register_action(view, cx, Editor::next_screen);
 217        register_action(view, cx, Editor::scroll_cursor_top);
 218        register_action(view, cx, Editor::scroll_cursor_center);
 219        register_action(view, cx, Editor::scroll_cursor_bottom);
 220        register_action(view, cx, |editor, _: &LineDown, cx| {
 221            editor.scroll_screen(&ScrollAmount::Line(1.), cx)
 222        });
 223        register_action(view, cx, |editor, _: &LineUp, cx| {
 224            editor.scroll_screen(&ScrollAmount::Line(-1.), cx)
 225        });
 226        register_action(view, cx, |editor, _: &HalfPageDown, cx| {
 227            editor.scroll_screen(&ScrollAmount::Page(0.5), cx)
 228        });
 229        register_action(view, cx, |editor, _: &HalfPageUp, cx| {
 230            editor.scroll_screen(&ScrollAmount::Page(-0.5), cx)
 231        });
 232        register_action(view, cx, |editor, _: &PageDown, cx| {
 233            editor.scroll_screen(&ScrollAmount::Page(1.), cx)
 234        });
 235        register_action(view, cx, |editor, _: &PageUp, cx| {
 236            editor.scroll_screen(&ScrollAmount::Page(-1.), cx)
 237        });
 238        register_action(view, cx, Editor::move_to_previous_word_start);
 239        register_action(view, cx, Editor::move_to_previous_subword_start);
 240        register_action(view, cx, Editor::move_to_next_word_end);
 241        register_action(view, cx, Editor::move_to_next_subword_end);
 242        register_action(view, cx, Editor::move_to_beginning_of_line);
 243        register_action(view, cx, Editor::move_to_end_of_line);
 244        register_action(view, cx, Editor::move_to_start_of_paragraph);
 245        register_action(view, cx, Editor::move_to_end_of_paragraph);
 246        register_action(view, cx, Editor::move_to_beginning);
 247        register_action(view, cx, Editor::move_to_end);
 248        register_action(view, cx, Editor::select_up);
 249        register_action(view, cx, Editor::select_down);
 250        register_action(view, cx, Editor::select_left);
 251        register_action(view, cx, Editor::select_right);
 252        register_action(view, cx, Editor::select_to_previous_word_start);
 253        register_action(view, cx, Editor::select_to_previous_subword_start);
 254        register_action(view, cx, Editor::select_to_next_word_end);
 255        register_action(view, cx, Editor::select_to_next_subword_end);
 256        register_action(view, cx, Editor::select_to_beginning_of_line);
 257        register_action(view, cx, Editor::select_to_end_of_line);
 258        register_action(view, cx, Editor::select_to_start_of_paragraph);
 259        register_action(view, cx, Editor::select_to_end_of_paragraph);
 260        register_action(view, cx, Editor::select_to_beginning);
 261        register_action(view, cx, Editor::select_to_end);
 262        register_action(view, cx, Editor::select_all);
 263        register_action(view, cx, |editor, action, cx| {
 264            editor.select_all_matches(action, cx).log_err();
 265        });
 266        register_action(view, cx, Editor::select_line);
 267        register_action(view, cx, Editor::split_selection_into_lines);
 268        register_action(view, cx, Editor::add_selection_above);
 269        register_action(view, cx, Editor::add_selection_below);
 270        register_action(view, cx, |editor, action, cx| {
 271            editor.select_next(action, cx).log_err();
 272        });
 273        register_action(view, cx, |editor, action, cx| {
 274            editor.select_previous(action, cx).log_err();
 275        });
 276        register_action(view, cx, Editor::toggle_comments);
 277        register_action(view, cx, Editor::select_larger_syntax_node);
 278        register_action(view, cx, Editor::select_smaller_syntax_node);
 279        register_action(view, cx, Editor::select_enclosing_symbol);
 280        register_action(view, cx, Editor::move_to_enclosing_bracket);
 281        register_action(view, cx, Editor::undo_selection);
 282        register_action(view, cx, Editor::redo_selection);
 283        if !view.read(cx).is_singleton(cx) {
 284            register_action(view, cx, Editor::expand_excerpts);
 285            register_action(view, cx, Editor::expand_excerpts_up);
 286            register_action(view, cx, Editor::expand_excerpts_down);
 287        }
 288        register_action(view, cx, Editor::go_to_diagnostic);
 289        register_action(view, cx, Editor::go_to_prev_diagnostic);
 290        register_action(view, cx, Editor::go_to_hunk);
 291        register_action(view, cx, Editor::go_to_prev_hunk);
 292        register_action(view, cx, |editor, a, cx| {
 293            editor.go_to_definition(a, cx).detach_and_log_err(cx);
 294        });
 295        register_action(view, cx, |editor, a, cx| {
 296            editor.go_to_definition_split(a, cx).detach_and_log_err(cx);
 297        });
 298        register_action(view, cx, |editor, a, cx| {
 299            editor.go_to_implementation(a, cx).detach_and_log_err(cx);
 300        });
 301        register_action(view, cx, |editor, a, cx| {
 302            editor
 303                .go_to_implementation_split(a, cx)
 304                .detach_and_log_err(cx);
 305        });
 306        register_action(view, cx, |editor, a, cx| {
 307            editor.go_to_type_definition(a, cx).detach_and_log_err(cx);
 308        });
 309        register_action(view, cx, |editor, a, cx| {
 310            editor
 311                .go_to_type_definition_split(a, cx)
 312                .detach_and_log_err(cx);
 313        });
 314        register_action(view, cx, Editor::open_url);
 315        register_action(view, cx, Editor::fold);
 316        register_action(view, cx, Editor::fold_at);
 317        register_action(view, cx, Editor::unfold_lines);
 318        register_action(view, cx, Editor::unfold_at);
 319        register_action(view, cx, Editor::fold_selected_ranges);
 320        register_action(view, cx, Editor::show_completions);
 321        register_action(view, cx, Editor::toggle_code_actions);
 322        register_action(view, cx, Editor::open_excerpts);
 323        register_action(view, cx, Editor::open_excerpts_in_split);
 324        register_action(view, cx, Editor::toggle_soft_wrap);
 325        register_action(view, cx, Editor::toggle_tab_bar);
 326        register_action(view, cx, Editor::toggle_line_numbers);
 327        register_action(view, cx, Editor::toggle_indent_guides);
 328        register_action(view, cx, Editor::toggle_inlay_hints);
 329        register_action(view, cx, hover_popover::hover);
 330        register_action(view, cx, Editor::reveal_in_finder);
 331        register_action(view, cx, Editor::copy_path);
 332        register_action(view, cx, Editor::copy_relative_path);
 333        register_action(view, cx, Editor::copy_highlight_json);
 334        register_action(view, cx, Editor::copy_permalink_to_line);
 335        register_action(view, cx, Editor::open_permalink_to_line);
 336        register_action(view, cx, Editor::toggle_git_blame);
 337        register_action(view, cx, Editor::toggle_git_blame_inline);
 338        register_action(view, cx, Editor::toggle_hunk_diff);
 339        register_action(view, cx, Editor::expand_all_hunk_diffs);
 340        register_action(view, cx, |editor, action, cx| {
 341            if let Some(task) = editor.format(action, cx) {
 342                task.detach_and_log_err(cx);
 343            } else {
 344                cx.propagate();
 345            }
 346        });
 347        register_action(view, cx, Editor::restart_language_server);
 348        register_action(view, cx, Editor::cancel_language_server_work);
 349        register_action(view, cx, Editor::show_character_palette);
 350        register_action(view, cx, |editor, action, cx| {
 351            if let Some(task) = editor.confirm_completion(action, cx) {
 352                task.detach_and_log_err(cx);
 353            } else {
 354                cx.propagate();
 355            }
 356        });
 357        register_action(view, cx, |editor, action, cx| {
 358            if let Some(task) = editor.confirm_code_action(action, cx) {
 359                task.detach_and_log_err(cx);
 360            } else {
 361                cx.propagate();
 362            }
 363        });
 364        register_action(view, cx, |editor, action, cx| {
 365            if let Some(task) = editor.rename(action, cx) {
 366                task.detach_and_log_err(cx);
 367            } else {
 368                cx.propagate();
 369            }
 370        });
 371        register_action(view, cx, |editor, action, cx| {
 372            if let Some(task) = editor.confirm_rename(action, cx) {
 373                task.detach_and_log_err(cx);
 374            } else {
 375                cx.propagate();
 376            }
 377        });
 378        register_action(view, cx, |editor, action, cx| {
 379            if let Some(task) = editor.find_all_references(action, cx) {
 380                task.detach_and_log_err(cx);
 381            } else {
 382                cx.propagate();
 383            }
 384        });
 385        register_action(view, cx, Editor::next_inline_completion);
 386        register_action(view, cx, Editor::previous_inline_completion);
 387        register_action(view, cx, Editor::show_inline_completion);
 388        register_action(view, cx, Editor::context_menu_first);
 389        register_action(view, cx, Editor::context_menu_prev);
 390        register_action(view, cx, Editor::context_menu_next);
 391        register_action(view, cx, Editor::context_menu_last);
 392        register_action(view, cx, Editor::display_cursor_names);
 393        register_action(view, cx, Editor::unique_lines_case_insensitive);
 394        register_action(view, cx, Editor::unique_lines_case_sensitive);
 395        register_action(view, cx, Editor::accept_partial_inline_completion);
 396        register_action(view, cx, Editor::accept_inline_completion);
 397        register_action(view, cx, Editor::revert_selected_hunks);
 398        register_action(view, cx, Editor::open_active_item_in_terminal)
 399    }
 400
 401    fn register_key_listeners(&self, cx: &mut WindowContext, layout: &EditorLayout) {
 402        let position_map = layout.position_map.clone();
 403        cx.on_key_event({
 404            let editor = self.editor.clone();
 405            let text_hitbox = layout.text_hitbox.clone();
 406            move |event: &ModifiersChangedEvent, phase, cx| {
 407                if phase != DispatchPhase::Bubble {
 408                    return;
 409                }
 410
 411                editor.update(cx, |editor, cx| {
 412                    Self::modifiers_changed(editor, event, &position_map, &text_hitbox, cx)
 413                })
 414            }
 415        });
 416    }
 417
 418    fn modifiers_changed(
 419        editor: &mut Editor,
 420        event: &ModifiersChangedEvent,
 421        position_map: &PositionMap,
 422        text_hitbox: &Hitbox,
 423        cx: &mut ViewContext<Editor>,
 424    ) {
 425        let mouse_position = cx.mouse_position();
 426        if !text_hitbox.is_hovered(cx) {
 427            return;
 428        }
 429
 430        editor.update_hovered_link(
 431            position_map.point_for_position(text_hitbox.bounds, mouse_position),
 432            &position_map.snapshot,
 433            event.modifiers,
 434            cx,
 435        )
 436    }
 437
 438    fn mouse_left_down(
 439        editor: &mut Editor,
 440        event: &MouseDownEvent,
 441        hovered_hunk: Option<&HunkToExpand>,
 442        position_map: &PositionMap,
 443        text_hitbox: &Hitbox,
 444        gutter_hitbox: &Hitbox,
 445        cx: &mut ViewContext<Editor>,
 446    ) {
 447        if cx.default_prevented() {
 448            return;
 449        }
 450
 451        let mut click_count = event.click_count;
 452        let mut modifiers = event.modifiers;
 453
 454        if let Some(hovered_hunk) = hovered_hunk {
 455            editor.expand_diff_hunk(None, hovered_hunk, cx);
 456            cx.notify();
 457            return;
 458        } else if gutter_hitbox.is_hovered(cx) {
 459            click_count = 3; // Simulate triple-click when clicking the gutter to select lines
 460        } else if !text_hitbox.is_hovered(cx) {
 461            return;
 462        }
 463
 464        if click_count == 2 && !editor.buffer().read(cx).is_singleton() {
 465            match EditorSettings::get_global(cx).double_click_in_multibuffer {
 466                DoubleClickInMultibuffer::Select => {
 467                    // do nothing special on double click, all selection logic is below
 468                }
 469                DoubleClickInMultibuffer::Open => {
 470                    if modifiers.alt {
 471                        // if double click is made with alt, pretend it's a regular double click without opening and alt,
 472                        // and run the selection logic.
 473                        modifiers.alt = false;
 474                    } else {
 475                        // if double click is made without alt, open the corresponding excerp
 476                        editor.open_excerpts(&OpenExcerpts, cx);
 477                        return;
 478                    }
 479                }
 480            }
 481        }
 482
 483        let point_for_position =
 484            position_map.point_for_position(text_hitbox.bounds, event.position);
 485        let position = point_for_position.previous_valid;
 486        if modifiers.shift && modifiers.alt {
 487            editor.select(
 488                SelectPhase::BeginColumnar {
 489                    position,
 490                    reset: false,
 491                    goal_column: point_for_position.exact_unclipped.column(),
 492                },
 493                cx,
 494            );
 495        } else if modifiers.shift && !modifiers.control && !modifiers.alt && !modifiers.secondary()
 496        {
 497            editor.select(
 498                SelectPhase::Extend {
 499                    position,
 500                    click_count,
 501                },
 502                cx,
 503            );
 504        } else {
 505            let multi_cursor_setting = EditorSettings::get_global(cx).multi_cursor_modifier;
 506            let multi_cursor_modifier = match multi_cursor_setting {
 507                MultiCursorModifier::Alt => modifiers.alt,
 508                MultiCursorModifier::CmdOrCtrl => modifiers.secondary(),
 509            };
 510            editor.select(
 511                SelectPhase::Begin {
 512                    position,
 513                    add: multi_cursor_modifier,
 514                    click_count,
 515                },
 516                cx,
 517            );
 518        }
 519
 520        cx.stop_propagation();
 521    }
 522
 523    fn mouse_right_down(
 524        editor: &mut Editor,
 525        event: &MouseDownEvent,
 526        position_map: &PositionMap,
 527        text_hitbox: &Hitbox,
 528        cx: &mut ViewContext<Editor>,
 529    ) {
 530        if !text_hitbox.is_hovered(cx) {
 531            return;
 532        }
 533        let point_for_position =
 534            position_map.point_for_position(text_hitbox.bounds, event.position);
 535        mouse_context_menu::deploy_context_menu(
 536            editor,
 537            event.position,
 538            point_for_position.previous_valid,
 539            cx,
 540        );
 541        cx.stop_propagation();
 542    }
 543
 544    fn mouse_middle_down(
 545        editor: &mut Editor,
 546        event: &MouseDownEvent,
 547        position_map: &PositionMap,
 548        text_hitbox: &Hitbox,
 549        cx: &mut ViewContext<Editor>,
 550    ) {
 551        if !text_hitbox.is_hovered(cx) || cx.default_prevented() {
 552            return;
 553        }
 554
 555        let point_for_position =
 556            position_map.point_for_position(text_hitbox.bounds, event.position);
 557        let position = point_for_position.previous_valid;
 558
 559        editor.select(
 560            SelectPhase::BeginColumnar {
 561                position,
 562                reset: true,
 563                goal_column: point_for_position.exact_unclipped.column(),
 564            },
 565            cx,
 566        );
 567    }
 568
 569    fn mouse_up(
 570        editor: &mut Editor,
 571        event: &MouseUpEvent,
 572        position_map: &PositionMap,
 573        text_hitbox: &Hitbox,
 574        cx: &mut ViewContext<Editor>,
 575    ) {
 576        let end_selection = editor.has_pending_selection();
 577        let pending_nonempty_selections = editor.has_pending_nonempty_selection();
 578
 579        if end_selection {
 580            editor.select(SelectPhase::End, cx);
 581        }
 582
 583        let multi_cursor_setting = EditorSettings::get_global(cx).multi_cursor_modifier;
 584        let multi_cursor_modifier = match multi_cursor_setting {
 585            MultiCursorModifier::Alt => event.modifiers.secondary(),
 586            MultiCursorModifier::CmdOrCtrl => event.modifiers.alt,
 587        };
 588
 589        if !pending_nonempty_selections && multi_cursor_modifier && text_hitbox.is_hovered(cx) {
 590            let point = position_map.point_for_position(text_hitbox.bounds, event.position);
 591            editor.handle_click_hovered_link(point, event.modifiers, cx);
 592
 593            cx.stop_propagation();
 594        } else if end_selection && pending_nonempty_selections {
 595            cx.stop_propagation();
 596        } else if cfg!(target_os = "linux") && event.button == MouseButton::Middle {
 597            if !text_hitbox.is_hovered(cx) || editor.read_only(cx) {
 598                return;
 599            }
 600
 601            #[cfg(target_os = "linux")]
 602            if let Some(item) = cx.read_from_primary() {
 603                let point_for_position =
 604                    position_map.point_for_position(text_hitbox.bounds, event.position);
 605                let position = point_for_position.previous_valid;
 606
 607                editor.select(
 608                    SelectPhase::Begin {
 609                        position,
 610                        add: false,
 611                        click_count: 1,
 612                    },
 613                    cx,
 614                );
 615                editor.insert(item.text(), cx);
 616            }
 617            cx.stop_propagation()
 618        }
 619    }
 620
 621    fn mouse_dragged(
 622        editor: &mut Editor,
 623        event: &MouseMoveEvent,
 624        position_map: &PositionMap,
 625        text_bounds: Bounds<Pixels>,
 626        cx: &mut ViewContext<Editor>,
 627    ) {
 628        if !editor.has_pending_selection() {
 629            return;
 630        }
 631
 632        let point_for_position = position_map.point_for_position(text_bounds, event.position);
 633        let mut scroll_delta = gpui::Point::<f32>::default();
 634        let vertical_margin = position_map.line_height.min(text_bounds.size.height / 3.0);
 635        let top = text_bounds.origin.y + vertical_margin;
 636        let bottom = text_bounds.lower_left().y - vertical_margin;
 637        if event.position.y < top {
 638            scroll_delta.y = -scale_vertical_mouse_autoscroll_delta(top - event.position.y);
 639        }
 640        if event.position.y > bottom {
 641            scroll_delta.y = scale_vertical_mouse_autoscroll_delta(event.position.y - bottom);
 642        }
 643
 644        let horizontal_margin = position_map.line_height.min(text_bounds.size.width / 3.0);
 645        let left = text_bounds.origin.x + horizontal_margin;
 646        let right = text_bounds.upper_right().x - horizontal_margin;
 647        if event.position.x < left {
 648            scroll_delta.x = -scale_horizontal_mouse_autoscroll_delta(left - event.position.x);
 649        }
 650        if event.position.x > right {
 651            scroll_delta.x = scale_horizontal_mouse_autoscroll_delta(event.position.x - right);
 652        }
 653
 654        editor.select(
 655            SelectPhase::Update {
 656                position: point_for_position.previous_valid,
 657                goal_column: point_for_position.exact_unclipped.column(),
 658                scroll_delta,
 659            },
 660            cx,
 661        );
 662    }
 663
 664    fn mouse_moved(
 665        editor: &mut Editor,
 666        event: &MouseMoveEvent,
 667        position_map: &PositionMap,
 668        text_hitbox: &Hitbox,
 669        gutter_hitbox: &Hitbox,
 670        cx: &mut ViewContext<Editor>,
 671    ) {
 672        let modifiers = event.modifiers;
 673        let gutter_hovered = gutter_hitbox.is_hovered(cx);
 674        editor.set_gutter_hovered(gutter_hovered, cx);
 675
 676        // Don't trigger hover popover if mouse is hovering over context menu
 677        if text_hitbox.is_hovered(cx) {
 678            let point_for_position =
 679                position_map.point_for_position(text_hitbox.bounds, event.position);
 680
 681            editor.update_hovered_link(point_for_position, &position_map.snapshot, modifiers, cx);
 682
 683            if let Some(point) = point_for_position.as_valid() {
 684                let anchor = position_map
 685                    .snapshot
 686                    .buffer_snapshot
 687                    .anchor_before(point.to_offset(&position_map.snapshot, Bias::Left));
 688                hover_at(editor, Some(anchor), cx);
 689                Self::update_visible_cursor(editor, point, position_map, cx);
 690            } else {
 691                hover_at(editor, None, cx);
 692            }
 693        } else {
 694            editor.hide_hovered_link(cx);
 695            hover_at(editor, None, cx);
 696            if gutter_hovered {
 697                cx.stop_propagation();
 698            }
 699        }
 700    }
 701
 702    fn update_visible_cursor(
 703        editor: &mut Editor,
 704        point: DisplayPoint,
 705        position_map: &PositionMap,
 706        cx: &mut ViewContext<Editor>,
 707    ) {
 708        let snapshot = &position_map.snapshot;
 709        let Some(hub) = editor.collaboration_hub() else {
 710            return;
 711        };
 712        let range = DisplayPoint::new(point.row(), point.column().saturating_sub(1))
 713            ..DisplayPoint::new(
 714                point.row(),
 715                (point.column() + 1).min(snapshot.line_len(point.row())),
 716            );
 717
 718        let range = snapshot
 719            .buffer_snapshot
 720            .anchor_at(range.start.to_point(&snapshot.display_snapshot), Bias::Left)
 721            ..snapshot
 722                .buffer_snapshot
 723                .anchor_at(range.end.to_point(&snapshot.display_snapshot), Bias::Right);
 724
 725        let Some(selection) = snapshot.remote_selections_in_range(&range, hub, cx).next() else {
 726            return;
 727        };
 728        let key = crate::HoveredCursor {
 729            replica_id: selection.replica_id,
 730            selection_id: selection.selection.id,
 731        };
 732        editor.hovered_cursors.insert(
 733            key.clone(),
 734            cx.spawn(|editor, mut cx| async move {
 735                cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 736                editor
 737                    .update(&mut cx, |editor, cx| {
 738                        editor.hovered_cursors.remove(&key);
 739                        cx.notify();
 740                    })
 741                    .ok();
 742            }),
 743        );
 744        cx.notify()
 745    }
 746
 747    fn layout_selections(
 748        &self,
 749        start_anchor: Anchor,
 750        end_anchor: Anchor,
 751        snapshot: &EditorSnapshot,
 752        start_row: DisplayRow,
 753        end_row: DisplayRow,
 754        cx: &mut WindowContext,
 755    ) -> (
 756        Vec<(PlayerColor, Vec<SelectionLayout>)>,
 757        BTreeMap<DisplayRow, bool>,
 758        Option<DisplayPoint>,
 759    ) {
 760        let mut selections: Vec<(PlayerColor, Vec<SelectionLayout>)> = Vec::new();
 761        let mut active_rows = BTreeMap::new();
 762        let mut newest_selection_head = None;
 763        let editor = self.editor.read(cx);
 764
 765        if editor.show_local_selections {
 766            let mut local_selections: Vec<Selection<Point>> = editor
 767                .selections
 768                .disjoint_in_range(start_anchor..end_anchor, cx);
 769            local_selections.extend(editor.selections.pending(cx));
 770            let mut layouts = Vec::new();
 771            let newest = editor.selections.newest(cx);
 772            for selection in local_selections.drain(..) {
 773                let is_empty = selection.start == selection.end;
 774                let is_newest = selection == newest;
 775
 776                let layout = SelectionLayout::new(
 777                    selection,
 778                    editor.selections.line_mode,
 779                    editor.cursor_shape,
 780                    &snapshot.display_snapshot,
 781                    is_newest,
 782                    editor.leader_peer_id.is_none(),
 783                    None,
 784                );
 785                if is_newest {
 786                    newest_selection_head = Some(layout.head);
 787                }
 788
 789                for row in cmp::max(layout.active_rows.start.0, start_row.0)
 790                    ..=cmp::min(layout.active_rows.end.0, end_row.0)
 791                {
 792                    let contains_non_empty_selection =
 793                        active_rows.entry(DisplayRow(row)).or_insert(!is_empty);
 794                    *contains_non_empty_selection |= !is_empty;
 795                }
 796                layouts.push(layout);
 797            }
 798
 799            let player = if editor.read_only(cx) {
 800                cx.theme().players().read_only()
 801            } else {
 802                self.style.local_player
 803            };
 804
 805            selections.push((player, layouts));
 806        }
 807
 808        if let Some(collaboration_hub) = &editor.collaboration_hub {
 809            // When following someone, render the local selections in their color.
 810            if let Some(leader_id) = editor.leader_peer_id {
 811                if let Some(collaborator) = collaboration_hub.collaborators(cx).get(&leader_id) {
 812                    if let Some(participant_index) = collaboration_hub
 813                        .user_participant_indices(cx)
 814                        .get(&collaborator.user_id)
 815                    {
 816                        if let Some((local_selection_style, _)) = selections.first_mut() {
 817                            *local_selection_style = cx
 818                                .theme()
 819                                .players()
 820                                .color_for_participant(participant_index.0);
 821                        }
 822                    }
 823                }
 824            }
 825
 826            let mut remote_selections = HashMap::default();
 827            for selection in snapshot.remote_selections_in_range(
 828                &(start_anchor..end_anchor),
 829                collaboration_hub.as_ref(),
 830                cx,
 831            ) {
 832                let selection_style = Self::get_participant_color(selection.participant_index, cx);
 833
 834                // Don't re-render the leader's selections, since the local selections
 835                // match theirs.
 836                if Some(selection.peer_id) == editor.leader_peer_id {
 837                    continue;
 838                }
 839                let key = HoveredCursor {
 840                    replica_id: selection.replica_id,
 841                    selection_id: selection.selection.id,
 842                };
 843
 844                let is_shown =
 845                    editor.show_cursor_names || editor.hovered_cursors.contains_key(&key);
 846
 847                remote_selections
 848                    .entry(selection.replica_id)
 849                    .or_insert((selection_style, Vec::new()))
 850                    .1
 851                    .push(SelectionLayout::new(
 852                        selection.selection,
 853                        selection.line_mode,
 854                        selection.cursor_shape,
 855                        &snapshot.display_snapshot,
 856                        false,
 857                        false,
 858                        if is_shown { selection.user_name } else { None },
 859                    ));
 860            }
 861
 862            selections.extend(remote_selections.into_values());
 863        } else if !editor.is_focused(cx) && editor.show_cursor_when_unfocused {
 864            let player = if editor.read_only(cx) {
 865                cx.theme().players().read_only()
 866            } else {
 867                self.style.local_player
 868            };
 869            let layouts = snapshot
 870                .buffer_snapshot
 871                .selections_in_range(&(start_anchor..end_anchor), true)
 872                .map(move |(_, line_mode, cursor_shape, selection)| {
 873                    SelectionLayout::new(
 874                        selection,
 875                        line_mode,
 876                        cursor_shape,
 877                        &snapshot.display_snapshot,
 878                        false,
 879                        false,
 880                        None,
 881                    )
 882                })
 883                .collect::<Vec<_>>();
 884            selections.push((player, layouts));
 885        }
 886        (selections, active_rows, newest_selection_head)
 887    }
 888
 889    fn collect_cursors(
 890        &self,
 891        snapshot: &EditorSnapshot,
 892        cx: &mut WindowContext,
 893    ) -> Vec<(DisplayPoint, Hsla)> {
 894        let editor = self.editor.read(cx);
 895        let mut cursors = Vec::new();
 896        let mut skip_local = false;
 897        let mut add_cursor = |anchor: Anchor, color| {
 898            cursors.push((anchor.to_display_point(&snapshot.display_snapshot), color));
 899        };
 900        // Remote cursors
 901        if let Some(collaboration_hub) = &editor.collaboration_hub {
 902            for remote_selection in snapshot.remote_selections_in_range(
 903                &(Anchor::min()..Anchor::max()),
 904                collaboration_hub.deref(),
 905                cx,
 906            ) {
 907                let color = Self::get_participant_color(remote_selection.participant_index, cx);
 908                add_cursor(remote_selection.selection.head(), color.cursor);
 909                if Some(remote_selection.peer_id) == editor.leader_peer_id {
 910                    skip_local = true;
 911                }
 912            }
 913        }
 914        // Local cursors
 915        if !skip_local {
 916            let color = cx.theme().players().local().cursor;
 917            editor.selections.disjoint.iter().for_each(|selection| {
 918                add_cursor(selection.head(), color);
 919            });
 920            if let Some(ref selection) = editor.selections.pending_anchor() {
 921                add_cursor(selection.head(), color);
 922            }
 923        }
 924        cursors
 925    }
 926
 927    #[allow(clippy::too_many_arguments)]
 928    fn layout_visible_cursors(
 929        &self,
 930        snapshot: &EditorSnapshot,
 931        selections: &[(PlayerColor, Vec<SelectionLayout>)],
 932        visible_display_row_range: Range<DisplayRow>,
 933        line_layouts: &[LineWithInvisibles],
 934        text_hitbox: &Hitbox,
 935        content_origin: gpui::Point<Pixels>,
 936        scroll_position: gpui::Point<f32>,
 937        scroll_pixel_position: gpui::Point<Pixels>,
 938        line_height: Pixels,
 939        em_width: Pixels,
 940        autoscroll_containing_element: bool,
 941        cx: &mut WindowContext,
 942    ) -> Vec<CursorLayout> {
 943        let mut autoscroll_bounds = None;
 944        let cursor_layouts = self.editor.update(cx, |editor, cx| {
 945            let mut cursors = Vec::new();
 946            for (player_color, selections) in selections {
 947                for selection in selections {
 948                    let cursor_position = selection.head;
 949
 950                    let in_range = visible_display_row_range.contains(&cursor_position.row());
 951                    if (selection.is_local && !editor.show_local_cursors(cx)) || !in_range {
 952                        continue;
 953                    }
 954
 955                    let cursor_row_layout = &line_layouts
 956                        [cursor_position.row().minus(visible_display_row_range.start) as usize];
 957                    let cursor_column = cursor_position.column() as usize;
 958
 959                    let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 960                    let mut block_width =
 961                        cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
 962                    if block_width == Pixels::ZERO {
 963                        block_width = em_width;
 964                    }
 965                    let block_text = if let CursorShape::Block = selection.cursor_shape {
 966                        snapshot.display_chars_at(cursor_position).next().and_then(
 967                            |(character, _)| {
 968                                let text = if character == '\n' {
 969                                    SharedString::from(" ")
 970                                } else {
 971                                    SharedString::from(character.to_string())
 972                                };
 973                                let len = text.len();
 974
 975                                let font = cursor_row_layout
 976                                    .font_id_for_index(cursor_column)
 977                                    .and_then(|cursor_font_id| {
 978                                        cx.text_system().get_font_for_id(cursor_font_id)
 979                                    })
 980                                    .unwrap_or(self.style.text.font());
 981
 982                                cx.text_system()
 983                                    .shape_line(
 984                                        text,
 985                                        cursor_row_layout.font_size,
 986                                        &[TextRun {
 987                                            len,
 988                                            font,
 989                                            color: self.style.background,
 990                                            background_color: None,
 991                                            strikethrough: None,
 992                                            underline: None,
 993                                        }],
 994                                    )
 995                                    .log_err()
 996                            },
 997                        )
 998                    } else {
 999                        None
1000                    };
1001
1002                    let x = cursor_character_x - scroll_pixel_position.x;
1003                    let y = (cursor_position.row().as_f32()
1004                        - scroll_pixel_position.y / line_height)
1005                        * line_height;
1006                    if selection.is_newest {
1007                        editor.pixel_position_of_newest_cursor = Some(point(
1008                            text_hitbox.origin.x + x + block_width / 2.,
1009                            text_hitbox.origin.y + y + line_height / 2.,
1010                        ));
1011
1012                        if autoscroll_containing_element {
1013                            let top = text_hitbox.origin.y
1014                                + (cursor_position.row().as_f32() - scroll_position.y - 3.).max(0.)
1015                                    * line_height;
1016                            let left = text_hitbox.origin.x
1017                                + (cursor_position.column() as f32 - scroll_position.x - 3.)
1018                                    .max(0.)
1019                                    * em_width;
1020
1021                            let bottom = text_hitbox.origin.y
1022                                + (cursor_position.row().as_f32() - scroll_position.y + 4.)
1023                                    * line_height;
1024                            let right = text_hitbox.origin.x
1025                                + (cursor_position.column() as f32 - scroll_position.x + 4.)
1026                                    * em_width;
1027
1028                            autoscroll_bounds =
1029                                Some(Bounds::from_corners(point(left, top), point(right, bottom)))
1030                        }
1031                    }
1032
1033                    let mut cursor = CursorLayout {
1034                        color: player_color.cursor,
1035                        block_width,
1036                        origin: point(x, y),
1037                        line_height,
1038                        shape: selection.cursor_shape,
1039                        block_text,
1040                        cursor_name: None,
1041                    };
1042                    let cursor_name = selection.user_name.clone().map(|name| CursorName {
1043                        string: name,
1044                        color: self.style.background,
1045                        is_top_row: cursor_position.row().0 == 0,
1046                    });
1047                    cursor.layout(content_origin, cursor_name, cx);
1048                    cursors.push(cursor);
1049                }
1050            }
1051            cursors
1052        });
1053
1054        if let Some(bounds) = autoscroll_bounds {
1055            cx.request_autoscroll(bounds);
1056        }
1057
1058        cursor_layouts
1059    }
1060
1061    fn layout_scrollbar(
1062        &self,
1063        snapshot: &EditorSnapshot,
1064        bounds: Bounds<Pixels>,
1065        scroll_position: gpui::Point<f32>,
1066        rows_per_page: f32,
1067        non_visible_cursors: bool,
1068        cx: &mut WindowContext,
1069    ) -> Option<ScrollbarLayout> {
1070        let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
1071        let show_scrollbars = match scrollbar_settings.show {
1072            ShowScrollbar::Auto => {
1073                let editor = self.editor.read(cx);
1074                let is_singleton = editor.is_singleton(cx);
1075                // Git
1076                (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_git_diffs())
1077                    ||
1078                    // Buffer Search Results
1079                    (is_singleton && scrollbar_settings.search_results && editor.has_background_highlights::<BufferSearchHighlights>())
1080                    ||
1081                    // Selected Symbol Occurrences
1082                    (is_singleton && scrollbar_settings.selected_symbol && (editor.has_background_highlights::<DocumentHighlightRead>() || editor.has_background_highlights::<DocumentHighlightWrite>()))
1083                    ||
1084                    // Diagnostics
1085                    (is_singleton && scrollbar_settings.diagnostics && snapshot.buffer_snapshot.has_diagnostics())
1086                    ||
1087                    // Cursors out of sight
1088                    non_visible_cursors
1089                    ||
1090                    // Scrollmanager
1091                    editor.scroll_manager.scrollbars_visible()
1092            }
1093            ShowScrollbar::System => self.editor.read(cx).scroll_manager.scrollbars_visible(),
1094            ShowScrollbar::Always => true,
1095            ShowScrollbar::Never => false,
1096        };
1097        if snapshot.mode != EditorMode::Full {
1098            return None;
1099        }
1100
1101        let visible_row_range = scroll_position.y..scroll_position.y + rows_per_page;
1102
1103        // If a drag took place after we started dragging the scrollbar,
1104        // cancel the scrollbar drag.
1105        if cx.has_active_drag() {
1106            self.editor.update(cx, |editor, cx| {
1107                editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
1108            });
1109        }
1110
1111        let track_bounds = Bounds::from_corners(
1112            point(self.scrollbar_left(&bounds), bounds.origin.y),
1113            point(bounds.lower_right().x, bounds.lower_left().y),
1114        );
1115
1116        let settings = EditorSettings::get_global(cx);
1117        let scroll_beyond_last_line: f32 = match settings.scroll_beyond_last_line {
1118            ScrollBeyondLastLine::OnePage => rows_per_page,
1119            ScrollBeyondLastLine::Off => 1.0,
1120            ScrollBeyondLastLine::VerticalScrollMargin => 1.0 + settings.vertical_scroll_margin,
1121        };
1122        let total_rows = snapshot.max_point().row().as_f32() + scroll_beyond_last_line;
1123        let height = bounds.size.height;
1124        let px_per_row = height / total_rows;
1125        let thumb_height = (rows_per_page * px_per_row).max(ScrollbarLayout::MIN_THUMB_HEIGHT);
1126        let row_height = (height - thumb_height) / (total_rows - rows_per_page).max(0.0);
1127
1128        Some(ScrollbarLayout {
1129            hitbox: cx.insert_hitbox(track_bounds, false),
1130            visible_row_range,
1131            row_height,
1132            visible: show_scrollbars,
1133            thumb_height,
1134        })
1135    }
1136
1137    #[allow(clippy::too_many_arguments)]
1138    fn prepaint_gutter_fold_toggles(
1139        &self,
1140        toggles: &mut [Option<AnyElement>],
1141        line_height: Pixels,
1142        gutter_dimensions: &GutterDimensions,
1143        gutter_settings: crate::editor_settings::Gutter,
1144        scroll_pixel_position: gpui::Point<Pixels>,
1145        gutter_hitbox: &Hitbox,
1146        cx: &mut WindowContext,
1147    ) {
1148        for (ix, fold_indicator) in toggles.iter_mut().enumerate() {
1149            if let Some(fold_indicator) = fold_indicator {
1150                debug_assert!(gutter_settings.folds);
1151                let available_space = size(
1152                    AvailableSpace::MinContent,
1153                    AvailableSpace::Definite(line_height * 0.55),
1154                );
1155                let fold_indicator_size = fold_indicator.layout_as_root(available_space, cx);
1156
1157                let position = point(
1158                    gutter_dimensions.width - gutter_dimensions.right_padding,
1159                    ix as f32 * line_height - (scroll_pixel_position.y % line_height),
1160                );
1161                let centering_offset = point(
1162                    (gutter_dimensions.fold_area_width() - fold_indicator_size.width) / 2.,
1163                    (line_height - fold_indicator_size.height) / 2.,
1164                );
1165                let origin = gutter_hitbox.origin + position + centering_offset;
1166                fold_indicator.prepaint_as_root(origin, available_space, cx);
1167            }
1168        }
1169    }
1170
1171    #[allow(clippy::too_many_arguments)]
1172    fn prepaint_crease_trailers(
1173        &self,
1174        trailers: Vec<Option<AnyElement>>,
1175        lines: &[LineWithInvisibles],
1176        line_height: Pixels,
1177        content_origin: gpui::Point<Pixels>,
1178        scroll_pixel_position: gpui::Point<Pixels>,
1179        em_width: Pixels,
1180        cx: &mut WindowContext,
1181    ) -> Vec<Option<CreaseTrailerLayout>> {
1182        trailers
1183            .into_iter()
1184            .enumerate()
1185            .map(|(ix, element)| {
1186                let mut element = element?;
1187                let available_space = size(
1188                    AvailableSpace::MinContent,
1189                    AvailableSpace::Definite(line_height),
1190                );
1191                let size = element.layout_as_root(available_space, cx);
1192
1193                let line = &lines[ix];
1194                let padding = if line.width == Pixels::ZERO {
1195                    Pixels::ZERO
1196                } else {
1197                    4. * em_width
1198                };
1199                let position = point(
1200                    scroll_pixel_position.x + line.width + padding,
1201                    ix as f32 * line_height - (scroll_pixel_position.y % line_height),
1202                );
1203                let centering_offset = point(px(0.), (line_height - size.height) / 2.);
1204                let origin = content_origin + position + centering_offset;
1205                element.prepaint_as_root(origin, available_space, cx);
1206                Some(CreaseTrailerLayout {
1207                    element,
1208                    bounds: Bounds::new(origin, size),
1209                })
1210            })
1211            .collect()
1212    }
1213
1214    // Folds contained in a hunk are ignored apart from shrinking visual size
1215    // If a fold contains any hunks then that fold line is marked as modified
1216    fn layout_git_gutters(
1217        &self,
1218        line_height: Pixels,
1219        gutter_hitbox: &Hitbox,
1220        display_rows: Range<DisplayRow>,
1221        snapshot: &EditorSnapshot,
1222        cx: &mut WindowContext,
1223    ) -> Vec<(DisplayDiffHunk, Option<Hitbox>)> {
1224        let buffer_snapshot = &snapshot.buffer_snapshot;
1225
1226        let buffer_start_row = MultiBufferRow(
1227            DisplayPoint::new(display_rows.start, 0)
1228                .to_point(snapshot)
1229                .row,
1230        );
1231        let buffer_end_row = MultiBufferRow(
1232            DisplayPoint::new(display_rows.end, 0)
1233                .to_point(snapshot)
1234                .row,
1235        );
1236
1237        let expanded_hunk_display_rows = self.editor.update(cx, |editor, _| {
1238            editor
1239                .expanded_hunks
1240                .hunks(false)
1241                .map(|expanded_hunk| {
1242                    let start_row = expanded_hunk
1243                        .hunk_range
1244                        .start
1245                        .to_display_point(snapshot)
1246                        .row();
1247                    let end_row = expanded_hunk
1248                        .hunk_range
1249                        .end
1250                        .to_display_point(snapshot)
1251                        .row();
1252                    (start_row, end_row)
1253                })
1254                .collect::<HashMap<_, _>>()
1255        });
1256
1257        let git_gutter_setting = ProjectSettings::get_global(cx)
1258            .git
1259            .git_gutter
1260            .unwrap_or_default();
1261        buffer_snapshot
1262            .git_diff_hunks_in_range(buffer_start_row..buffer_end_row)
1263            .map(|hunk| diff_hunk_to_display(&hunk, snapshot))
1264            .dedup()
1265            .map(|hunk| match git_gutter_setting {
1266                GitGutterSetting::TrackedFiles => {
1267                    let hitbox = if let DisplayDiffHunk::Unfolded {
1268                        display_row_range, ..
1269                    } = &hunk
1270                    {
1271                        let was_expanded = expanded_hunk_display_rows
1272                            .get(&display_row_range.start)
1273                            .map(|expanded_end_row| expanded_end_row == &display_row_range.end)
1274                            .unwrap_or(false);
1275                        if was_expanded {
1276                            None
1277                        } else {
1278                            let hunk_bounds = Self::diff_hunk_bounds(
1279                                &snapshot,
1280                                line_height,
1281                                gutter_hitbox.bounds,
1282                                &hunk,
1283                            );
1284                            Some(cx.insert_hitbox(hunk_bounds, true))
1285                        }
1286                    } else {
1287                        None
1288                    };
1289                    (hunk, hitbox)
1290                }
1291                GitGutterSetting::Hide => (hunk, None),
1292            })
1293            .collect()
1294    }
1295
1296    #[allow(clippy::too_many_arguments)]
1297    fn layout_inline_blame(
1298        &self,
1299        display_row: DisplayRow,
1300        display_snapshot: &DisplaySnapshot,
1301        line_layout: &LineWithInvisibles,
1302        crease_trailer: Option<&CreaseTrailerLayout>,
1303        em_width: Pixels,
1304        content_origin: gpui::Point<Pixels>,
1305        scroll_pixel_position: gpui::Point<Pixels>,
1306        line_height: Pixels,
1307        cx: &mut WindowContext,
1308    ) -> Option<AnyElement> {
1309        if !self
1310            .editor
1311            .update(cx, |editor, cx| editor.render_git_blame_inline(cx))
1312        {
1313            return None;
1314        }
1315
1316        let workspace = self
1317            .editor
1318            .read(cx)
1319            .workspace
1320            .as_ref()
1321            .map(|(w, _)| w.clone());
1322
1323        let display_point = DisplayPoint::new(display_row, 0);
1324        let buffer_row = MultiBufferRow(display_point.to_point(display_snapshot).row);
1325
1326        let blame = self.editor.read(cx).blame.clone()?;
1327        let blame_entry = blame
1328            .update(cx, |blame, cx| {
1329                blame.blame_for_rows([Some(buffer_row)], cx).next()
1330            })
1331            .flatten()?;
1332
1333        let mut element =
1334            render_inline_blame_entry(&blame, blame_entry, &self.style, workspace, cx);
1335
1336        let start_y = content_origin.y
1337            + line_height * (display_row.as_f32() - scroll_pixel_position.y / line_height);
1338
1339        let start_x = {
1340            const INLINE_BLAME_PADDING_EM_WIDTHS: f32 = 6.;
1341
1342            let line_end = if let Some(crease_trailer) = crease_trailer {
1343                crease_trailer.bounds.right()
1344            } else {
1345                content_origin.x - scroll_pixel_position.x + line_layout.width
1346            };
1347            let padded_line_end = line_end + em_width * INLINE_BLAME_PADDING_EM_WIDTHS;
1348
1349            let min_column_in_pixels = ProjectSettings::get_global(cx)
1350                .git
1351                .inline_blame
1352                .and_then(|settings| settings.min_column)
1353                .map(|col| self.column_pixels(col as usize, cx))
1354                .unwrap_or(px(0.));
1355            let min_start = content_origin.x - scroll_pixel_position.x + min_column_in_pixels;
1356
1357            cmp::max(padded_line_end, min_start)
1358        };
1359
1360        let absolute_offset = point(start_x, start_y);
1361        let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1362
1363        element.prepaint_as_root(absolute_offset, available_space, cx);
1364
1365        Some(element)
1366    }
1367
1368    #[allow(clippy::too_many_arguments)]
1369    fn layout_blame_entries(
1370        &self,
1371        buffer_rows: impl Iterator<Item = Option<MultiBufferRow>>,
1372        em_width: Pixels,
1373        scroll_position: gpui::Point<f32>,
1374        line_height: Pixels,
1375        gutter_hitbox: &Hitbox,
1376        max_width: Option<Pixels>,
1377        cx: &mut WindowContext,
1378    ) -> Option<Vec<AnyElement>> {
1379        if !self
1380            .editor
1381            .update(cx, |editor, cx| editor.render_git_blame_gutter(cx))
1382        {
1383            return None;
1384        }
1385
1386        let blame = self.editor.read(cx).blame.clone()?;
1387        let blamed_rows: Vec<_> = blame.update(cx, |blame, cx| {
1388            blame.blame_for_rows(buffer_rows, cx).collect()
1389        });
1390
1391        let width = if let Some(max_width) = max_width {
1392            AvailableSpace::Definite(max_width)
1393        } else {
1394            AvailableSpace::MaxContent
1395        };
1396        let scroll_top = scroll_position.y * line_height;
1397        let start_x = em_width * 1;
1398
1399        let mut last_used_color: Option<(PlayerColor, Oid)> = None;
1400
1401        let shaped_lines = blamed_rows
1402            .into_iter()
1403            .enumerate()
1404            .flat_map(|(ix, blame_entry)| {
1405                if let Some(blame_entry) = blame_entry {
1406                    let mut element = render_blame_entry(
1407                        ix,
1408                        &blame,
1409                        blame_entry,
1410                        &self.style,
1411                        &mut last_used_color,
1412                        self.editor.clone(),
1413                        cx,
1414                    );
1415
1416                    let start_y = ix as f32 * line_height - (scroll_top % line_height);
1417                    let absolute_offset = gutter_hitbox.origin + point(start_x, start_y);
1418
1419                    element.prepaint_as_root(
1420                        absolute_offset,
1421                        size(width, AvailableSpace::MinContent),
1422                        cx,
1423                    );
1424
1425                    Some(element)
1426                } else {
1427                    None
1428                }
1429            })
1430            .collect();
1431
1432        Some(shaped_lines)
1433    }
1434
1435    #[allow(clippy::too_many_arguments)]
1436    fn layout_indent_guides(
1437        &self,
1438        content_origin: gpui::Point<Pixels>,
1439        text_origin: gpui::Point<Pixels>,
1440        visible_buffer_range: Range<MultiBufferRow>,
1441        scroll_pixel_position: gpui::Point<Pixels>,
1442        line_height: Pixels,
1443        snapshot: &DisplaySnapshot,
1444        cx: &mut WindowContext,
1445    ) -> Option<Vec<IndentGuideLayout>> {
1446        let indent_guides = self.editor.update(cx, |editor, cx| {
1447            editor.indent_guides(visible_buffer_range, snapshot, cx)
1448        })?;
1449
1450        let active_indent_guide_indices = self.editor.update(cx, |editor, cx| {
1451            editor
1452                .find_active_indent_guide_indices(&indent_guides, snapshot, cx)
1453                .unwrap_or_default()
1454        });
1455
1456        Some(
1457            indent_guides
1458                .into_iter()
1459                .enumerate()
1460                .filter_map(|(i, indent_guide)| {
1461                    let single_indent_width =
1462                        self.column_pixels(indent_guide.tab_size as usize, cx);
1463                    let total_width = single_indent_width * indent_guide.depth as f32;
1464                    let start_x = content_origin.x + total_width - scroll_pixel_position.x;
1465                    if start_x >= text_origin.x {
1466                        let (offset_y, length) = Self::calculate_indent_guide_bounds(
1467                            indent_guide.multibuffer_row_range.clone(),
1468                            line_height,
1469                            snapshot,
1470                        );
1471
1472                        let start_y = content_origin.y + offset_y - scroll_pixel_position.y;
1473
1474                        Some(IndentGuideLayout {
1475                            origin: point(start_x, start_y),
1476                            length,
1477                            single_indent_width,
1478                            depth: indent_guide.depth,
1479                            active: active_indent_guide_indices.contains(&i),
1480                            settings: indent_guide.settings,
1481                        })
1482                    } else {
1483                        None
1484                    }
1485                })
1486                .collect(),
1487        )
1488    }
1489
1490    fn calculate_indent_guide_bounds(
1491        row_range: Range<MultiBufferRow>,
1492        line_height: Pixels,
1493        snapshot: &DisplaySnapshot,
1494    ) -> (gpui::Pixels, gpui::Pixels) {
1495        let start_point = Point::new(row_range.start.0, 0);
1496        let end_point = Point::new(row_range.end.0, 0);
1497
1498        let row_range = start_point.to_display_point(snapshot).row()
1499            ..end_point.to_display_point(snapshot).row();
1500
1501        let mut prev_line = start_point;
1502        prev_line.row = prev_line.row.saturating_sub(1);
1503        let prev_line = prev_line.to_display_point(snapshot).row();
1504
1505        let mut cons_line = end_point;
1506        cons_line.row += 1;
1507        let cons_line = cons_line.to_display_point(snapshot).row();
1508
1509        let mut offset_y = row_range.start.0 as f32 * line_height;
1510        let mut length = (cons_line.0.saturating_sub(row_range.start.0)) as f32 * line_height;
1511
1512        // If we are at the end of the buffer, ensure that the indent guide extends to the end of the line.
1513        if row_range.end == cons_line {
1514            length += line_height;
1515        }
1516
1517        // If there is a block (e.g. diagnostic) in between the start of the indent guide and the line above,
1518        // we want to extend the indent guide to the start of the block.
1519        let mut block_height = 0;
1520        let mut block_offset = 0;
1521        let mut found_excerpt_header = false;
1522        for (_, block) in snapshot.blocks_in_range(prev_line..row_range.start) {
1523            if matches!(block, TransformBlock::ExcerptHeader { .. }) {
1524                found_excerpt_header = true;
1525                break;
1526            }
1527            block_offset += block.height();
1528            block_height += block.height();
1529        }
1530        if !found_excerpt_header {
1531            offset_y -= block_offset as f32 * line_height;
1532            length += block_height as f32 * line_height;
1533        }
1534
1535        // If there is a block (e.g. diagnostic) at the end of an multibuffer excerpt,
1536        // we want to ensure that the indent guide stops before the excerpt header.
1537        let mut block_height = 0;
1538        let mut found_excerpt_header = false;
1539        for (_, block) in snapshot.blocks_in_range(row_range.end..cons_line) {
1540            if matches!(block, TransformBlock::ExcerptHeader { .. }) {
1541                found_excerpt_header = true;
1542            }
1543            block_height += block.height();
1544        }
1545        if found_excerpt_header {
1546            length -= block_height as f32 * line_height;
1547        }
1548
1549        (offset_y, length)
1550    }
1551
1552    fn layout_run_indicators(
1553        &self,
1554        line_height: Pixels,
1555        scroll_pixel_position: gpui::Point<Pixels>,
1556        gutter_dimensions: &GutterDimensions,
1557        gutter_hitbox: &Hitbox,
1558        snapshot: &EditorSnapshot,
1559        cx: &mut WindowContext,
1560    ) -> Vec<AnyElement> {
1561        self.editor.update(cx, |editor, cx| {
1562            let active_task_indicator_row =
1563                if let Some(crate::ContextMenu::CodeActions(CodeActionsMenu {
1564                    deployed_from_indicator,
1565                    actions,
1566                    ..
1567                })) = editor.context_menu.read().as_ref()
1568                {
1569                    actions
1570                        .tasks
1571                        .as_ref()
1572                        .map(|tasks| tasks.position.to_display_point(snapshot).row())
1573                        .or_else(|| *deployed_from_indicator)
1574                } else {
1575                    None
1576                };
1577            editor
1578                .tasks
1579                .iter()
1580                .filter_map(|(_, tasks)| {
1581                    let multibuffer_point = tasks.offset.0.to_point(&snapshot.buffer_snapshot);
1582                    let multibuffer_row = MultiBufferRow(multibuffer_point.row);
1583                    if snapshot.is_line_folded(multibuffer_row) {
1584                        return None;
1585                    }
1586                    let display_row = multibuffer_point.to_display_point(snapshot).row();
1587                    let button = editor.render_run_indicator(
1588                        &self.style,
1589                        Some(display_row) == active_task_indicator_row,
1590                        display_row,
1591                        cx,
1592                    );
1593
1594                    let button = prepaint_gutter_button(
1595                        button,
1596                        display_row,
1597                        line_height,
1598                        gutter_dimensions,
1599                        scroll_pixel_position,
1600                        gutter_hitbox,
1601                        cx,
1602                    );
1603                    Some(button)
1604                })
1605                .collect_vec()
1606        })
1607    }
1608
1609    fn layout_code_actions_indicator(
1610        &self,
1611        line_height: Pixels,
1612        newest_selection_head: DisplayPoint,
1613        scroll_pixel_position: gpui::Point<Pixels>,
1614        gutter_dimensions: &GutterDimensions,
1615        gutter_hitbox: &Hitbox,
1616        cx: &mut WindowContext,
1617    ) -> Option<AnyElement> {
1618        let mut active = false;
1619        let mut button = None;
1620        let row = newest_selection_head.row();
1621        self.editor.update(cx, |editor, cx| {
1622            if let Some(crate::ContextMenu::CodeActions(CodeActionsMenu {
1623                deployed_from_indicator,
1624                ..
1625            })) = editor.context_menu.read().as_ref()
1626            {
1627                active = deployed_from_indicator.map_or(true, |indicator_row| indicator_row == row);
1628            };
1629            button = editor.render_code_actions_indicator(&self.style, row, active, cx);
1630        });
1631
1632        let button = prepaint_gutter_button(
1633            button?,
1634            row,
1635            line_height,
1636            gutter_dimensions,
1637            scroll_pixel_position,
1638            gutter_hitbox,
1639            cx,
1640        );
1641
1642        Some(button)
1643    }
1644
1645    fn get_participant_color(
1646        participant_index: Option<ParticipantIndex>,
1647        cx: &WindowContext,
1648    ) -> PlayerColor {
1649        if let Some(index) = participant_index {
1650            cx.theme().players().color_for_participant(index.0)
1651        } else {
1652            cx.theme().players().absent()
1653        }
1654    }
1655
1656    fn calculate_relative_line_numbers(
1657        &self,
1658        snapshot: &EditorSnapshot,
1659        rows: &Range<DisplayRow>,
1660        relative_to: Option<DisplayRow>,
1661    ) -> HashMap<DisplayRow, DisplayRowDelta> {
1662        let mut relative_rows: HashMap<DisplayRow, DisplayRowDelta> = Default::default();
1663        let Some(relative_to) = relative_to else {
1664            return relative_rows;
1665        };
1666
1667        let start = rows.start.min(relative_to);
1668        let end = rows.end.max(relative_to);
1669
1670        let buffer_rows = snapshot
1671            .buffer_rows(start)
1672            .take(1 + end.minus(start) as usize)
1673            .collect::<Vec<_>>();
1674
1675        let head_idx = relative_to.minus(start);
1676        let mut delta = 1;
1677        let mut i = head_idx + 1;
1678        while i < buffer_rows.len() as u32 {
1679            if buffer_rows[i as usize].is_some() {
1680                if rows.contains(&DisplayRow(i + start.0)) {
1681                    relative_rows.insert(DisplayRow(i + start.0), delta);
1682                }
1683                delta += 1;
1684            }
1685            i += 1;
1686        }
1687        delta = 1;
1688        i = head_idx.min(buffer_rows.len() as u32 - 1);
1689        while i > 0 && buffer_rows[i as usize].is_none() {
1690            i -= 1;
1691        }
1692
1693        while i > 0 {
1694            i -= 1;
1695            if buffer_rows[i as usize].is_some() {
1696                if rows.contains(&DisplayRow(i + start.0)) {
1697                    relative_rows.insert(DisplayRow(i + start.0), delta);
1698                }
1699                delta += 1;
1700            }
1701        }
1702
1703        relative_rows
1704    }
1705
1706    fn layout_line_numbers(
1707        &self,
1708        rows: Range<DisplayRow>,
1709        buffer_rows: impl Iterator<Item = Option<MultiBufferRow>>,
1710        active_rows: &BTreeMap<DisplayRow, bool>,
1711        newest_selection_head: Option<DisplayPoint>,
1712        snapshot: &EditorSnapshot,
1713        cx: &mut WindowContext,
1714    ) -> Vec<Option<ShapedLine>> {
1715        let include_line_numbers = snapshot.show_line_numbers.unwrap_or_else(|| {
1716            EditorSettings::get_global(cx).gutter.line_numbers && snapshot.mode == EditorMode::Full
1717        });
1718        if !include_line_numbers {
1719            return Vec::new();
1720        }
1721
1722        let editor = self.editor.read(cx);
1723        let newest_selection_head = newest_selection_head.unwrap_or_else(|| {
1724            let newest = editor.selections.newest::<Point>(cx);
1725            SelectionLayout::new(
1726                newest,
1727                editor.selections.line_mode,
1728                editor.cursor_shape,
1729                &snapshot.display_snapshot,
1730                true,
1731                true,
1732                None,
1733            )
1734            .head
1735        });
1736        let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1737
1738        let is_relative = EditorSettings::get_global(cx).relative_line_numbers;
1739        let relative_to = if is_relative {
1740            Some(newest_selection_head.row())
1741        } else {
1742            None
1743        };
1744        let relative_rows = self.calculate_relative_line_numbers(snapshot, &rows, relative_to);
1745        let mut line_number = String::new();
1746        buffer_rows
1747            .into_iter()
1748            .enumerate()
1749            .map(|(ix, multibuffer_row)| {
1750                let multibuffer_row = multibuffer_row?;
1751                let display_row = DisplayRow(rows.start.0 + ix as u32);
1752                let color = if active_rows.contains_key(&display_row) {
1753                    cx.theme().colors().editor_active_line_number
1754                } else {
1755                    cx.theme().colors().editor_line_number
1756                };
1757                line_number.clear();
1758                let default_number = multibuffer_row.0 + 1;
1759                let number = relative_rows
1760                    .get(&DisplayRow(ix as u32 + rows.start.0))
1761                    .unwrap_or(&default_number);
1762                write!(&mut line_number, "{number}").unwrap();
1763                let run = TextRun {
1764                    len: line_number.len(),
1765                    font: self.style.text.font(),
1766                    color,
1767                    background_color: None,
1768                    underline: None,
1769                    strikethrough: None,
1770                };
1771                let shaped_line = cx
1772                    .text_system()
1773                    .shape_line(line_number.clone().into(), font_size, &[run])
1774                    .unwrap();
1775                Some(shaped_line)
1776            })
1777            .collect()
1778    }
1779
1780    fn layout_gutter_fold_toggles(
1781        &self,
1782        rows: Range<DisplayRow>,
1783        buffer_rows: impl IntoIterator<Item = Option<MultiBufferRow>>,
1784        active_rows: &BTreeMap<DisplayRow, bool>,
1785        snapshot: &EditorSnapshot,
1786        cx: &mut WindowContext,
1787    ) -> Vec<Option<AnyElement>> {
1788        let include_fold_statuses = EditorSettings::get_global(cx).gutter.folds
1789            && snapshot.mode == EditorMode::Full
1790            && self.editor.read(cx).is_singleton(cx);
1791        if include_fold_statuses {
1792            buffer_rows
1793                .into_iter()
1794                .enumerate()
1795                .map(|(ix, row)| {
1796                    if let Some(multibuffer_row) = row {
1797                        let display_row = DisplayRow(rows.start.0 + ix as u32);
1798                        let active = active_rows.contains_key(&display_row);
1799                        snapshot.render_fold_toggle(
1800                            multibuffer_row,
1801                            active,
1802                            self.editor.clone(),
1803                            cx,
1804                        )
1805                    } else {
1806                        None
1807                    }
1808                })
1809                .collect()
1810        } else {
1811            Vec::new()
1812        }
1813    }
1814
1815    fn layout_crease_trailers(
1816        &self,
1817        buffer_rows: impl IntoIterator<Item = Option<MultiBufferRow>>,
1818        snapshot: &EditorSnapshot,
1819        cx: &mut WindowContext,
1820    ) -> Vec<Option<AnyElement>> {
1821        buffer_rows
1822            .into_iter()
1823            .map(|row| {
1824                if let Some(multibuffer_row) = row {
1825                    snapshot.render_crease_trailer(multibuffer_row, cx)
1826                } else {
1827                    None
1828                }
1829            })
1830            .collect()
1831    }
1832
1833    fn layout_lines(
1834        &self,
1835        rows: Range<DisplayRow>,
1836        line_number_layouts: &[Option<ShapedLine>],
1837        snapshot: &EditorSnapshot,
1838        cx: &mut WindowContext,
1839    ) -> Vec<LineWithInvisibles> {
1840        if rows.start >= rows.end {
1841            return Vec::new();
1842        }
1843
1844        // Show the placeholder when the editor is empty
1845        if snapshot.is_empty() {
1846            let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1847            let placeholder_color = cx.theme().colors().text_placeholder;
1848            let placeholder_text = snapshot.placeholder_text();
1849
1850            let placeholder_lines = placeholder_text
1851                .as_ref()
1852                .map_or("", AsRef::as_ref)
1853                .split('\n')
1854                .skip(rows.start.0 as usize)
1855                .chain(iter::repeat(""))
1856                .take(rows.len());
1857            placeholder_lines
1858                .filter_map(move |line| {
1859                    let run = TextRun {
1860                        len: line.len(),
1861                        font: self.style.text.font(),
1862                        color: placeholder_color,
1863                        background_color: None,
1864                        underline: Default::default(),
1865                        strikethrough: None,
1866                    };
1867                    cx.text_system()
1868                        .shape_line(line.to_string().into(), font_size, &[run])
1869                        .log_err()
1870                })
1871                .map(|line| LineWithInvisibles {
1872                    width: line.width,
1873                    len: line.len,
1874                    fragments: smallvec![LineFragment::Text(line)],
1875                    invisibles: Vec::new(),
1876                    font_size,
1877                })
1878                .collect()
1879        } else {
1880            let chunks = snapshot.highlighted_chunks(rows.clone(), true, &self.style);
1881            LineWithInvisibles::from_chunks(
1882                chunks,
1883                &self.style.text,
1884                MAX_LINE_LEN,
1885                rows.len(),
1886                line_number_layouts,
1887                snapshot.mode,
1888                cx,
1889            )
1890        }
1891    }
1892
1893    fn prepaint_lines(
1894        &self,
1895        start_row: DisplayRow,
1896        line_layouts: &mut [LineWithInvisibles],
1897        line_height: Pixels,
1898        scroll_pixel_position: gpui::Point<Pixels>,
1899        content_origin: gpui::Point<Pixels>,
1900        cx: &mut WindowContext,
1901    ) -> SmallVec<[AnyElement; 1]> {
1902        let mut line_elements = SmallVec::new();
1903        for (ix, line) in line_layouts.iter_mut().enumerate() {
1904            let row = start_row + DisplayRow(ix as u32);
1905            line.prepaint(
1906                line_height,
1907                scroll_pixel_position,
1908                row,
1909                content_origin,
1910                &mut line_elements,
1911                cx,
1912            );
1913        }
1914        line_elements
1915    }
1916
1917    #[allow(clippy::too_many_arguments)]
1918    fn build_blocks(
1919        &self,
1920        rows: Range<DisplayRow>,
1921        snapshot: &EditorSnapshot,
1922        hitbox: &Hitbox,
1923        text_hitbox: &Hitbox,
1924        scroll_width: &mut Pixels,
1925        gutter_dimensions: &GutterDimensions,
1926        em_width: Pixels,
1927        text_x: Pixels,
1928        line_height: Pixels,
1929        line_layouts: &[LineWithInvisibles],
1930        cx: &mut WindowContext,
1931    ) -> Vec<BlockLayout> {
1932        let mut block_id = 0;
1933        let (fixed_blocks, non_fixed_blocks) = snapshot
1934            .blocks_in_range(rows.clone())
1935            .partition::<Vec<_>, _>(|(_, block)| match block {
1936                TransformBlock::ExcerptHeader { .. } => false,
1937                TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
1938                TransformBlock::ExcerptFooter { .. } => false,
1939            });
1940
1941        let render_block = |block: &TransformBlock,
1942                            available_space: Size<AvailableSpace>,
1943                            block_id: usize,
1944                            block_row_start: DisplayRow,
1945                            cx: &mut WindowContext| {
1946            let mut element = match block {
1947                TransformBlock::Custom(block) => {
1948                    let align_to = block
1949                        .position()
1950                        .to_point(&snapshot.buffer_snapshot)
1951                        .to_display_point(snapshot);
1952                    let anchor_x = text_x
1953                        + if rows.contains(&align_to.row()) {
1954                            line_layouts[align_to.row().minus(rows.start) as usize]
1955                                .x_for_index(align_to.column() as usize)
1956                        } else {
1957                            layout_line(align_to.row(), snapshot, &self.style, cx)
1958                                .x_for_index(align_to.column() as usize)
1959                        };
1960
1961                    block.render(&mut BlockContext {
1962                        context: cx,
1963                        anchor_x,
1964                        gutter_dimensions,
1965                        line_height,
1966                        em_width,
1967                        block_id,
1968                        max_width: text_hitbox.size.width.max(*scroll_width),
1969                        editor_style: &self.style,
1970                    })
1971                }
1972
1973                TransformBlock::ExcerptHeader {
1974                    buffer,
1975                    range,
1976                    starts_new_buffer,
1977                    height,
1978                    id,
1979                    show_excerpt_controls,
1980                    ..
1981                } => {
1982                    let include_root = self
1983                        .editor
1984                        .read(cx)
1985                        .project
1986                        .as_ref()
1987                        .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
1988                        .unwrap_or_default();
1989
1990                    #[derive(Clone)]
1991                    struct JumpData {
1992                        position: Point,
1993                        anchor: text::Anchor,
1994                        path: ProjectPath,
1995                        line_offset_from_top: u32,
1996                    }
1997
1998                    let jump_data = project::File::from_dyn(buffer.file()).map(|file| {
1999                        let jump_path = ProjectPath {
2000                            worktree_id: file.worktree_id(cx),
2001                            path: file.path.clone(),
2002                        };
2003                        let jump_anchor = range
2004                            .primary
2005                            .as_ref()
2006                            .map_or(range.context.start, |primary| primary.start);
2007
2008                        let excerpt_start = range.context.start;
2009                        let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
2010                        let offset_from_excerpt_start = if jump_anchor == excerpt_start {
2011                            0
2012                        } else {
2013                            let excerpt_start_row =
2014                                language::ToPoint::to_point(&jump_anchor, buffer).row;
2015                            jump_position.row - excerpt_start_row
2016                        };
2017
2018                        let line_offset_from_top =
2019                            block_row_start.0 + *height as u32 + offset_from_excerpt_start
2020                                - snapshot
2021                                    .scroll_anchor
2022                                    .scroll_position(&snapshot.display_snapshot)
2023                                    .y as u32;
2024
2025                        JumpData {
2026                            position: jump_position,
2027                            anchor: jump_anchor,
2028                            path: jump_path,
2029                            line_offset_from_top,
2030                        }
2031                    });
2032
2033                    let icon_offset = gutter_dimensions.width
2034                        - (gutter_dimensions.left_padding + gutter_dimensions.margin);
2035
2036                    let element = if *starts_new_buffer {
2037                        let path = buffer.resolve_file_path(cx, include_root);
2038                        let mut filename = None;
2039                        let mut parent_path = None;
2040                        // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
2041                        if let Some(path) = path {
2042                            filename = path.file_name().map(|f| f.to_string_lossy().to_string());
2043                            parent_path = path
2044                                .parent()
2045                                .map(|p| SharedString::from(p.to_string_lossy().to_string() + "/"));
2046                        }
2047
2048                        let header_padding = px(6.0);
2049
2050                        v_flex()
2051                            .id(("path excerpt header", block_id))
2052                            .size_full()
2053                            .p(header_padding)
2054                            .child(
2055                                h_flex()
2056                                    .flex_basis(Length::Definite(DefiniteLength::Fraction(0.667)))
2057                                    .id("path header block")
2058                                    .pl(gpui::px(12.))
2059                                    .pr(gpui::px(8.))
2060                                    .rounded_md()
2061                                    .shadow_md()
2062                                    .border_1()
2063                                    .border_color(cx.theme().colors().border)
2064                                    .bg(cx.theme().colors().editor_subheader_background)
2065                                    .justify_between()
2066                                    .hover(|style| style.bg(cx.theme().colors().element_hover))
2067                                    .child(
2068                                        h_flex().gap_3().child(
2069                                            h_flex()
2070                                                .gap_2()
2071                                                .child(
2072                                                    filename
2073                                                        .map(SharedString::from)
2074                                                        .unwrap_or_else(|| "untitled".into()),
2075                                                )
2076                                                .when_some(parent_path, |then, path| {
2077                                                    then.child(
2078                                                        div().child(path).text_color(
2079                                                            cx.theme().colors().text_muted,
2080                                                        ),
2081                                                    )
2082                                                }),
2083                                        ),
2084                                    )
2085                                    .when_some(jump_data.clone(), |this, jump_data| {
2086                                        this.cursor_pointer()
2087                                            .tooltip(|cx| {
2088                                                Tooltip::for_action(
2089                                                    "Jump to File",
2090                                                    &OpenExcerpts,
2091                                                    cx,
2092                                                )
2093                                            })
2094                                            .on_mouse_down(MouseButton::Left, |_, cx| {
2095                                                cx.stop_propagation()
2096                                            })
2097                                            .on_click(cx.listener_for(&self.editor, {
2098                                                move |editor, _, cx| {
2099                                                    editor.jump(
2100                                                        jump_data.path.clone(),
2101                                                        jump_data.position,
2102                                                        jump_data.anchor,
2103                                                        jump_data.line_offset_from_top,
2104                                                        cx,
2105                                                    );
2106                                                }
2107                                            }))
2108                                    }),
2109                            )
2110                            .children(show_excerpt_controls.then(|| {
2111                                h_flex()
2112                                    .flex_basis(Length::Definite(DefiniteLength::Fraction(0.333)))
2113                                    .pt_1()
2114                                    .justify_end()
2115                                    .flex_none()
2116                                    .w(icon_offset - header_padding)
2117                                    .child(
2118                                        ButtonLike::new("expand-icon")
2119                                            .style(ButtonStyle::Transparent)
2120                                            .child(
2121                                                svg()
2122                                                    .path(IconName::ArrowUpFromLine.path())
2123                                                    .size(IconSize::XSmall.rems())
2124                                                    .text_color(
2125                                                        cx.theme().colors().editor_line_number,
2126                                                    )
2127                                                    .group("")
2128                                                    .hover(|style| {
2129                                                        style.text_color(
2130                                                            cx.theme()
2131                                                                .colors()
2132                                                                .editor_active_line_number,
2133                                                        )
2134                                                    }),
2135                                            )
2136                                            .on_click(cx.listener_for(&self.editor, {
2137                                                let id = *id;
2138                                                move |editor, _, cx| {
2139                                                    editor.expand_excerpt(
2140                                                        id,
2141                                                        multi_buffer::ExpandExcerptDirection::Up,
2142                                                        cx,
2143                                                    );
2144                                                }
2145                                            }))
2146                                            .tooltip({
2147                                                move |cx| {
2148                                                    Tooltip::for_action(
2149                                                        "Expand Excerpt",
2150                                                        &ExpandExcerpts { lines: 0 },
2151                                                        cx,
2152                                                    )
2153                                                }
2154                                            }),
2155                                    )
2156                            }))
2157                    } else {
2158                        v_flex()
2159                            .id(("excerpt header", block_id))
2160                            .size_full()
2161                            .child(
2162                                div()
2163                                    .flex()
2164                                    .v_flex()
2165                                    .justify_start()
2166                                    .id("jump to collapsed context")
2167                                    .w(relative(1.0))
2168                                    .h_full()
2169                                    .child(
2170                                        div()
2171                                            .h_px()
2172                                            .w_full()
2173                                            .bg(cx.theme().colors().border_variant)
2174                                            .group_hover("excerpt-jump-action", |style| {
2175                                                style.bg(cx.theme().colors().border)
2176                                            }),
2177                                    ),
2178                            )
2179                            .child(
2180                                h_flex()
2181                                    .justify_end()
2182                                    .flex_none()
2183                                    .w(icon_offset)
2184                                    .h_full()
2185                                    .child(
2186                                        show_excerpt_controls.then(|| {
2187                                            ButtonLike::new("expand-icon")
2188                                                .style(ButtonStyle::Transparent)
2189                                                .child(
2190                                                    svg()
2191                                                        .path(IconName::ArrowUpFromLine.path())
2192                                                        .size(IconSize::XSmall.rems())
2193                                                        .text_color(
2194                                                            cx.theme().colors().editor_line_number,
2195                                                        )
2196                                                        .group("")
2197                                                        .hover(|style| {
2198                                                            style.text_color(
2199                                                                cx.theme()
2200                                                                    .colors()
2201                                                                    .editor_active_line_number,
2202                                                            )
2203                                                        }),
2204                                                )
2205                                                .on_click(cx.listener_for(&self.editor, {
2206                                                    let id = *id;
2207                                                    move |editor, _, cx| {
2208                                                        editor.expand_excerpt(
2209                                                            id,
2210                                                            multi_buffer::ExpandExcerptDirection::Up,
2211                                                            cx,
2212                                                        );
2213                                                    }
2214                                                }))
2215                                                .tooltip({
2216                                                    move |cx| {
2217                                                        Tooltip::for_action(
2218                                                            "Expand Excerpt",
2219                                                            &ExpandExcerpts { lines: 0 },
2220                                                            cx,
2221                                                        )
2222                                                    }
2223                                                })
2224                                        }).unwrap_or_else(|| {
2225                                            ButtonLike::new("jump-icon")
2226                                                .style(ButtonStyle::Transparent)
2227                                                .child(
2228                                                    svg()
2229                                                        .path(IconName::ArrowUpRight.path())
2230                                                        .size(IconSize::XSmall.rems())
2231                                                        .text_color(
2232                                                            cx.theme().colors().border_variant,
2233                                                        )
2234                                                        .group("excerpt-jump-action")
2235                                                        .group_hover("excerpt-jump-action", |style| {
2236                                                            style.text_color(
2237                                                                cx.theme().colors().border
2238
2239                                                            )
2240                                                        })
2241                                                )
2242                                                .when_some(jump_data.clone(), |this, jump_data| {
2243                                                    this.on_click(cx.listener_for(&self.editor, {
2244                                                        let path = jump_data.path.clone();
2245                                                        move |editor, _, cx| {
2246                                                            cx.stop_propagation();
2247
2248                                                            editor.jump(
2249                                                                path.clone(),
2250                                                                jump_data.position,
2251                                                                jump_data.anchor,
2252                                                                jump_data.line_offset_from_top,
2253                                                                cx,
2254                                                            );
2255                                                        }
2256                                                    }))
2257                                                    .tooltip(move |cx| {
2258                                                        Tooltip::for_action(
2259                                                            format!(
2260                                                                "Jump to {}:L{}",
2261                                                                jump_data.path.path.display(),
2262                                                                jump_data.position.row + 1
2263                                                            ),
2264                                                            &OpenExcerpts,
2265                                                            cx,
2266                                                        )
2267                                                    })
2268                                                })
2269                                        })
2270
2271                                    ),
2272                            )
2273                            .group("excerpt-jump-action")
2274                            .cursor_pointer()
2275                            .when_some(jump_data.clone(), |this, jump_data| {
2276                                this.on_click(cx.listener_for(&self.editor, {
2277                                    let path = jump_data.path.clone();
2278                                    move |editor, _, cx| {
2279                                        cx.stop_propagation();
2280
2281                                        editor.jump(
2282                                            path.clone(),
2283                                            jump_data.position,
2284                                            jump_data.anchor,
2285                                            jump_data.line_offset_from_top,
2286                                            cx,
2287                                        );
2288                                    }
2289                                }))
2290                                .tooltip(move |cx| {
2291                                    Tooltip::for_action(
2292                                        format!(
2293                                            "Jump to {}:L{}",
2294                                            jump_data.path.path.display(),
2295                                            jump_data.position.row + 1
2296                                        ),
2297                                        &OpenExcerpts,
2298                                        cx,
2299                                    )
2300                                })
2301                            })
2302                    };
2303                    element.into_any()
2304                }
2305
2306                TransformBlock::ExcerptFooter { id, .. } => {
2307                    let element = v_flex().id(("excerpt footer", block_id)).size_full().child(
2308                        h_flex()
2309                            .justify_end()
2310                            .flex_none()
2311                            .w(gutter_dimensions.width
2312                                - (gutter_dimensions.left_padding + gutter_dimensions.margin))
2313                            .h_full()
2314                            .child(
2315                                ButtonLike::new("expand-icon")
2316                                    .style(ButtonStyle::Transparent)
2317                                    .child(
2318                                        svg()
2319                                            .path(IconName::ArrowDownFromLine.path())
2320                                            .size(IconSize::XSmall.rems())
2321                                            .text_color(cx.theme().colors().editor_line_number)
2322                                            .group("")
2323                                            .hover(|style| {
2324                                                style.text_color(
2325                                                    cx.theme().colors().editor_active_line_number,
2326                                                )
2327                                            }),
2328                                    )
2329                                    .on_click(cx.listener_for(&self.editor, {
2330                                        let id = *id;
2331                                        move |editor, _, cx| {
2332                                            editor.expand_excerpt(
2333                                                id,
2334                                                multi_buffer::ExpandExcerptDirection::Down,
2335                                                cx,
2336                                            );
2337                                        }
2338                                    }))
2339                                    .tooltip({
2340                                        move |cx| {
2341                                            Tooltip::for_action(
2342                                                "Expand Excerpt",
2343                                                &ExpandExcerpts { lines: 0 },
2344                                                cx,
2345                                            )
2346                                        }
2347                                    }),
2348                            ),
2349                    );
2350                    element.into_any()
2351                }
2352            };
2353
2354            let size = element.layout_as_root(available_space, cx);
2355            (element, size)
2356        };
2357
2358        let mut fixed_block_max_width = Pixels::ZERO;
2359        let mut blocks = Vec::new();
2360        for (row, block) in fixed_blocks {
2361            let available_space = size(
2362                AvailableSpace::MinContent,
2363                AvailableSpace::Definite(block.height() as f32 * line_height),
2364            );
2365            let (element, element_size) = render_block(block, available_space, block_id, row, cx);
2366            block_id += 1;
2367            fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
2368            blocks.push(BlockLayout {
2369                row,
2370                element,
2371                available_space,
2372                style: BlockStyle::Fixed,
2373            });
2374        }
2375        for (row, block) in non_fixed_blocks {
2376            let style = match block {
2377                TransformBlock::Custom(block) => block.style(),
2378                TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
2379                TransformBlock::ExcerptFooter { .. } => BlockStyle::Sticky,
2380            };
2381            let width = match style {
2382                BlockStyle::Sticky => hitbox.size.width,
2383                BlockStyle::Flex => hitbox
2384                    .size
2385                    .width
2386                    .max(fixed_block_max_width)
2387                    .max(gutter_dimensions.width + *scroll_width),
2388                BlockStyle::Fixed => unreachable!(),
2389            };
2390            let available_space = size(
2391                AvailableSpace::Definite(width),
2392                AvailableSpace::Definite(block.height() as f32 * line_height),
2393            );
2394            let (element, _) = render_block(block, available_space, block_id, row, cx);
2395            block_id += 1;
2396            blocks.push(BlockLayout {
2397                row,
2398                element,
2399                available_space,
2400                style,
2401            });
2402        }
2403
2404        *scroll_width = (*scroll_width).max(fixed_block_max_width - gutter_dimensions.width);
2405        blocks
2406    }
2407
2408    fn layout_blocks(
2409        &self,
2410        blocks: &mut Vec<BlockLayout>,
2411        hitbox: &Hitbox,
2412        line_height: Pixels,
2413        scroll_pixel_position: gpui::Point<Pixels>,
2414        cx: &mut WindowContext,
2415    ) {
2416        for block in blocks {
2417            let mut origin = hitbox.origin
2418                + point(
2419                    Pixels::ZERO,
2420                    block.row.as_f32() * line_height - scroll_pixel_position.y,
2421                );
2422            if !matches!(block.style, BlockStyle::Sticky) {
2423                origin += point(-scroll_pixel_position.x, Pixels::ZERO);
2424            }
2425            block
2426                .element
2427                .prepaint_as_root(origin, block.available_space, cx);
2428        }
2429    }
2430
2431    #[allow(clippy::too_many_arguments)]
2432    fn layout_context_menu(
2433        &self,
2434        line_height: Pixels,
2435        hitbox: &Hitbox,
2436        text_hitbox: &Hitbox,
2437        content_origin: gpui::Point<Pixels>,
2438        start_row: DisplayRow,
2439        scroll_pixel_position: gpui::Point<Pixels>,
2440        line_layouts: &[LineWithInvisibles],
2441        newest_selection_head: DisplayPoint,
2442        gutter_overshoot: Pixels,
2443        cx: &mut WindowContext,
2444    ) -> bool {
2445        let max_height = cmp::min(
2446            12. * line_height,
2447            cmp::max(3. * line_height, (hitbox.size.height - line_height) / 2.),
2448        );
2449        let Some((position, mut context_menu)) = self.editor.update(cx, |editor, cx| {
2450            if editor.context_menu_visible() {
2451                editor.render_context_menu(newest_selection_head, &self.style, max_height, cx)
2452            } else {
2453                None
2454            }
2455        }) else {
2456            return false;
2457        };
2458
2459        let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
2460        let context_menu_size = context_menu.layout_as_root(available_space, cx);
2461
2462        let (x, y) = match position {
2463            crate::ContextMenuOrigin::EditorPoint(point) => {
2464                let cursor_row_layout = &line_layouts[point.row().minus(start_row) as usize];
2465                let x = cursor_row_layout.x_for_index(point.column() as usize)
2466                    - scroll_pixel_position.x;
2467                let y = point.row().next_row().as_f32() * line_height - scroll_pixel_position.y;
2468                (x, y)
2469            }
2470            crate::ContextMenuOrigin::GutterIndicator(row) => {
2471                // Context menu was spawned via a click on a gutter. Ensure it's a bit closer to the indicator than just a plain first column of the
2472                // text field.
2473                let x = -gutter_overshoot;
2474                let y = row.next_row().as_f32() * line_height - scroll_pixel_position.y;
2475                (x, y)
2476            }
2477        };
2478
2479        let mut list_origin = content_origin + point(x, y);
2480        let list_width = context_menu_size.width;
2481        let list_height = context_menu_size.height;
2482
2483        // Snap the right edge of the list to the right edge of the window if
2484        // its horizontal bounds overflow.
2485        if list_origin.x + list_width > cx.viewport_size().width {
2486            list_origin.x = (cx.viewport_size().width - list_width).max(Pixels::ZERO);
2487        }
2488
2489        if list_origin.y + list_height > text_hitbox.lower_right().y {
2490            list_origin.y -= line_height + list_height;
2491        }
2492
2493        cx.defer_draw(context_menu, list_origin, 1);
2494        true
2495    }
2496
2497    fn layout_mouse_context_menu(&self, cx: &mut WindowContext) -> Option<AnyElement> {
2498        let mouse_context_menu = self.editor.read(cx).mouse_context_menu.as_ref()?;
2499        let mut element = deferred(
2500            anchored()
2501                .position(mouse_context_menu.position)
2502                .child(mouse_context_menu.context_menu.clone())
2503                .anchor(AnchorCorner::TopLeft)
2504                .snap_to_window(),
2505        )
2506        .with_priority(1)
2507        .into_any();
2508
2509        element.prepaint_as_root(gpui::Point::default(), AvailableSpace::min_size(), cx);
2510        Some(element)
2511    }
2512
2513    #[allow(clippy::too_many_arguments)]
2514    fn layout_hover_popovers(
2515        &self,
2516        snapshot: &EditorSnapshot,
2517        hitbox: &Hitbox,
2518        text_hitbox: &Hitbox,
2519        visible_display_row_range: Range<DisplayRow>,
2520        content_origin: gpui::Point<Pixels>,
2521        scroll_pixel_position: gpui::Point<Pixels>,
2522        line_layouts: &[LineWithInvisibles],
2523        line_height: Pixels,
2524        em_width: Pixels,
2525        cx: &mut WindowContext,
2526    ) {
2527        struct MeasuredHoverPopover {
2528            element: AnyElement,
2529            size: Size<Pixels>,
2530            horizontal_offset: Pixels,
2531        }
2532
2533        let max_size = size(
2534            (120. * em_width) // Default size
2535                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
2536                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2537            (16. * line_height) // Default size
2538                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
2539                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2540        );
2541
2542        let hover_popovers = self.editor.update(cx, |editor, cx| {
2543            editor.hover_state.render(
2544                &snapshot,
2545                &self.style,
2546                visible_display_row_range.clone(),
2547                max_size,
2548                editor.workspace.as_ref().map(|(w, _)| w.clone()),
2549                cx,
2550            )
2551        });
2552        let Some((position, hover_popovers)) = hover_popovers else {
2553            return;
2554        };
2555
2556        let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
2557
2558        // This is safe because we check on layout whether the required row is available
2559        let hovered_row_layout =
2560            &line_layouts[position.row().minus(visible_display_row_range.start) as usize];
2561
2562        // Compute Hovered Point
2563        let x =
2564            hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
2565        let y = position.row().as_f32() * line_height - scroll_pixel_position.y;
2566        let hovered_point = content_origin + point(x, y);
2567
2568        let mut overall_height = Pixels::ZERO;
2569        let mut measured_hover_popovers = Vec::new();
2570        for mut hover_popover in hover_popovers {
2571            let size = hover_popover.layout_as_root(available_space, cx);
2572            let horizontal_offset =
2573                (text_hitbox.upper_right().x - (hovered_point.x + size.width)).min(Pixels::ZERO);
2574
2575            overall_height += HOVER_POPOVER_GAP + size.height;
2576
2577            measured_hover_popovers.push(MeasuredHoverPopover {
2578                element: hover_popover,
2579                size,
2580                horizontal_offset,
2581            });
2582        }
2583        overall_height += HOVER_POPOVER_GAP;
2584
2585        fn draw_occluder(width: Pixels, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
2586            let mut occlusion = div()
2587                .size_full()
2588                .occlude()
2589                .on_mouse_move(|_, cx| cx.stop_propagation())
2590                .into_any_element();
2591            occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), cx);
2592            cx.defer_draw(occlusion, origin, 2);
2593        }
2594
2595        if hovered_point.y > overall_height {
2596            // There is enough space above. Render popovers above the hovered point
2597            let mut current_y = hovered_point.y;
2598            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
2599                let size = popover.size;
2600                let popover_origin = point(
2601                    hovered_point.x + popover.horizontal_offset,
2602                    current_y - size.height,
2603                );
2604
2605                cx.defer_draw(popover.element, popover_origin, 2);
2606                if position != itertools::Position::Last {
2607                    let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
2608                    draw_occluder(size.width, origin, cx);
2609                }
2610
2611                current_y = popover_origin.y - HOVER_POPOVER_GAP;
2612            }
2613        } else {
2614            // There is not enough space above. Render popovers below the hovered point
2615            let mut current_y = hovered_point.y + line_height;
2616            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
2617                let size = popover.size;
2618                let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
2619
2620                cx.defer_draw(popover.element, popover_origin, 2);
2621                if position != itertools::Position::Last {
2622                    let origin = point(popover_origin.x, popover_origin.y + size.height);
2623                    draw_occluder(size.width, origin, cx);
2624                }
2625
2626                current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
2627            }
2628        }
2629    }
2630
2631    fn paint_background(&self, layout: &EditorLayout, cx: &mut WindowContext) {
2632        cx.paint_layer(layout.hitbox.bounds, |cx| {
2633            let scroll_top = layout.position_map.snapshot.scroll_position().y;
2634            let gutter_bg = cx.theme().colors().editor_gutter_background;
2635            cx.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
2636            cx.paint_quad(fill(layout.text_hitbox.bounds, self.style.background));
2637
2638            if let EditorMode::Full = layout.mode {
2639                let mut active_rows = layout.active_rows.iter().peekable();
2640                while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
2641                    let mut end_row = start_row.0;
2642                    while active_rows
2643                        .peek()
2644                        .map_or(false, |(active_row, has_selection)| {
2645                            active_row.0 == end_row + 1
2646                                && *has_selection == contains_non_empty_selection
2647                        })
2648                    {
2649                        active_rows.next().unwrap();
2650                        end_row += 1;
2651                    }
2652
2653                    if !contains_non_empty_selection {
2654                        let highlight_h_range =
2655                            match layout.position_map.snapshot.current_line_highlight {
2656                                CurrentLineHighlight::Gutter => Some(Range {
2657                                    start: layout.hitbox.left(),
2658                                    end: layout.gutter_hitbox.right(),
2659                                }),
2660                                CurrentLineHighlight::Line => Some(Range {
2661                                    start: layout.text_hitbox.bounds.left(),
2662                                    end: layout.text_hitbox.bounds.right(),
2663                                }),
2664                                CurrentLineHighlight::All => Some(Range {
2665                                    start: layout.hitbox.left(),
2666                                    end: layout.hitbox.right(),
2667                                }),
2668                                CurrentLineHighlight::None => None,
2669                            };
2670                        if let Some(range) = highlight_h_range {
2671                            let active_line_bg = cx.theme().colors().editor_active_line_background;
2672                            let bounds = Bounds {
2673                                origin: point(
2674                                    range.start,
2675                                    layout.hitbox.origin.y
2676                                        + (start_row.as_f32() - scroll_top)
2677                                            * layout.position_map.line_height,
2678                                ),
2679                                size: size(
2680                                    range.end - range.start,
2681                                    layout.position_map.line_height
2682                                        * (end_row - start_row.0 + 1) as f32,
2683                                ),
2684                            };
2685                            cx.paint_quad(fill(bounds, active_line_bg));
2686                        }
2687                    }
2688                }
2689
2690                let mut paint_highlight =
2691                    |highlight_row_start: DisplayRow, highlight_row_end: DisplayRow, color| {
2692                        let origin = point(
2693                            layout.hitbox.origin.x,
2694                            layout.hitbox.origin.y
2695                                + (highlight_row_start.as_f32() - scroll_top)
2696                                    * layout.position_map.line_height,
2697                        );
2698                        let size = size(
2699                            layout.hitbox.size.width,
2700                            layout.position_map.line_height
2701                                * highlight_row_end.next_row().minus(highlight_row_start) as f32,
2702                        );
2703                        cx.paint_quad(fill(Bounds { origin, size }, color));
2704                    };
2705
2706                let mut current_paint: Option<(Hsla, Range<DisplayRow>)> = None;
2707                for (&new_row, &new_color) in &layout.highlighted_rows {
2708                    match &mut current_paint {
2709                        Some((current_color, current_range)) => {
2710                            let current_color = *current_color;
2711                            let new_range_started = current_color != new_color
2712                                || current_range.end.next_row() != new_row;
2713                            if new_range_started {
2714                                paint_highlight(
2715                                    current_range.start,
2716                                    current_range.end,
2717                                    current_color,
2718                                );
2719                                current_paint = Some((new_color, new_row..new_row));
2720                                continue;
2721                            } else {
2722                                current_range.end = current_range.end.next_row();
2723                            }
2724                        }
2725                        None => current_paint = Some((new_color, new_row..new_row)),
2726                    };
2727                }
2728                if let Some((color, range)) = current_paint {
2729                    paint_highlight(range.start, range.end, color);
2730                }
2731
2732                let scroll_left =
2733                    layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
2734
2735                for (wrap_position, active) in layout.wrap_guides.iter() {
2736                    let x = (layout.text_hitbox.origin.x
2737                        + *wrap_position
2738                        + layout.position_map.em_width / 2.)
2739                        - scroll_left;
2740
2741                    let show_scrollbars = layout
2742                        .scrollbar_layout
2743                        .as_ref()
2744                        .map_or(false, |scrollbar| scrollbar.visible);
2745                    if x < layout.text_hitbox.origin.x
2746                        || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
2747                    {
2748                        continue;
2749                    }
2750
2751                    let color = if *active {
2752                        cx.theme().colors().editor_active_wrap_guide
2753                    } else {
2754                        cx.theme().colors().editor_wrap_guide
2755                    };
2756                    cx.paint_quad(fill(
2757                        Bounds {
2758                            origin: point(x, layout.text_hitbox.origin.y),
2759                            size: size(px(1.), layout.text_hitbox.size.height),
2760                        },
2761                        color,
2762                    ));
2763                }
2764            }
2765        })
2766    }
2767
2768    fn paint_indent_guides(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2769        let Some(indent_guides) = &layout.indent_guides else {
2770            return;
2771        };
2772
2773        let faded_color = |color: Hsla, alpha: f32| {
2774            let mut faded = color;
2775            faded.a = alpha;
2776            faded
2777        };
2778
2779        for indent_guide in indent_guides {
2780            let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
2781            let settings = indent_guide.settings;
2782
2783            // TODO fixed for now, expose them through themes later
2784            const INDENT_AWARE_ALPHA: f32 = 0.2;
2785            const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
2786            const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
2787            const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
2788
2789            let line_color = match (settings.coloring, indent_guide.active) {
2790                (IndentGuideColoring::Disabled, _) => None,
2791                (IndentGuideColoring::Fixed, false) => {
2792                    Some(cx.theme().colors().editor_indent_guide)
2793                }
2794                (IndentGuideColoring::Fixed, true) => {
2795                    Some(cx.theme().colors().editor_indent_guide_active)
2796                }
2797                (IndentGuideColoring::IndentAware, false) => {
2798                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
2799                }
2800                (IndentGuideColoring::IndentAware, true) => {
2801                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
2802                }
2803            };
2804
2805            let background_color = match (settings.background_coloring, indent_guide.active) {
2806                (IndentGuideBackgroundColoring::Disabled, _) => None,
2807                (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
2808                    indent_accent_colors,
2809                    INDENT_AWARE_BACKGROUND_ALPHA,
2810                )),
2811                (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
2812                    indent_accent_colors,
2813                    INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
2814                )),
2815            };
2816
2817            let requested_line_width = if indent_guide.active {
2818                settings.active_line_width
2819            } else {
2820                settings.line_width
2821            }
2822            .clamp(1, 10);
2823            let mut line_indicator_width = 0.;
2824            if let Some(color) = line_color {
2825                cx.paint_quad(fill(
2826                    Bounds {
2827                        origin: indent_guide.origin,
2828                        size: size(px(requested_line_width as f32), indent_guide.length),
2829                    },
2830                    color,
2831                ));
2832                line_indicator_width = requested_line_width as f32;
2833            }
2834
2835            if let Some(color) = background_color {
2836                let width = indent_guide.single_indent_width - px(line_indicator_width);
2837                cx.paint_quad(fill(
2838                    Bounds {
2839                        origin: point(
2840                            indent_guide.origin.x + px(line_indicator_width),
2841                            indent_guide.origin.y,
2842                        ),
2843                        size: size(width, indent_guide.length),
2844                    },
2845                    color,
2846                ));
2847            }
2848        }
2849    }
2850
2851    fn paint_line_numbers(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2852        let line_height = layout.position_map.line_height;
2853        let scroll_position = layout.position_map.snapshot.scroll_position();
2854        let scroll_top = scroll_position.y * line_height;
2855
2856        cx.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
2857
2858        for (ix, line) in layout.line_numbers.iter().enumerate() {
2859            if let Some(line) = line {
2860                let line_origin = layout.gutter_hitbox.origin
2861                    + point(
2862                        layout.gutter_hitbox.size.width
2863                            - line.width
2864                            - layout.gutter_dimensions.right_padding,
2865                        ix as f32 * line_height - (scroll_top % line_height),
2866                    );
2867
2868                line.paint(line_origin, line_height, cx).log_err();
2869            }
2870        }
2871    }
2872
2873    fn paint_diff_hunks(layout: &EditorLayout, cx: &mut WindowContext) {
2874        if layout.display_hunks.is_empty() {
2875            return;
2876        }
2877
2878        let line_height = layout.position_map.line_height;
2879        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2880            for (hunk, hitbox) in &layout.display_hunks {
2881                let hunk_to_paint = match hunk {
2882                    DisplayDiffHunk::Folded { .. } => {
2883                        let hunk_bounds = Self::diff_hunk_bounds(
2884                            &layout.position_map.snapshot,
2885                            line_height,
2886                            layout.gutter_hitbox.bounds,
2887                            &hunk,
2888                        );
2889                        Some((
2890                            hunk_bounds,
2891                            cx.theme().status().modified,
2892                            Corners::all(1. * line_height),
2893                        ))
2894                    }
2895                    DisplayDiffHunk::Unfolded { status, .. } => {
2896                        hitbox.as_ref().map(|hunk_hitbox| match status {
2897                            DiffHunkStatus::Added => (
2898                                hunk_hitbox.bounds,
2899                                cx.theme().status().created,
2900                                Corners::all(0.05 * line_height),
2901                            ),
2902                            DiffHunkStatus::Modified => (
2903                                hunk_hitbox.bounds,
2904                                cx.theme().status().modified,
2905                                Corners::all(0.05 * line_height),
2906                            ),
2907                            DiffHunkStatus::Removed => (
2908                                Bounds::new(
2909                                    point(
2910                                        hunk_hitbox.origin.x - hunk_hitbox.size.width,
2911                                        hunk_hitbox.origin.y,
2912                                    ),
2913                                    size(hunk_hitbox.size.width * px(2.), hunk_hitbox.size.height),
2914                                ),
2915                                cx.theme().status().deleted,
2916                                Corners::all(1. * line_height),
2917                            ),
2918                        })
2919                    }
2920                };
2921
2922                if let Some((hunk_bounds, background_color, corner_radii)) = hunk_to_paint {
2923                    cx.paint_quad(quad(
2924                        hunk_bounds,
2925                        corner_radii,
2926                        background_color,
2927                        Edges::default(),
2928                        transparent_black(),
2929                    ));
2930                }
2931            }
2932        });
2933    }
2934
2935    fn diff_hunk_bounds(
2936        snapshot: &EditorSnapshot,
2937        line_height: Pixels,
2938        bounds: Bounds<Pixels>,
2939        hunk: &DisplayDiffHunk,
2940    ) -> Bounds<Pixels> {
2941        let scroll_position = snapshot.scroll_position();
2942        let scroll_top = scroll_position.y * line_height;
2943
2944        match hunk {
2945            DisplayDiffHunk::Folded { display_row, .. } => {
2946                let start_y = display_row.as_f32() * line_height - scroll_top;
2947                let end_y = start_y + line_height;
2948
2949                let width = 0.275 * line_height;
2950                let highlight_origin = bounds.origin + point(px(0.), start_y);
2951                let highlight_size = size(width, end_y - start_y);
2952                Bounds::new(highlight_origin, highlight_size)
2953            }
2954            DisplayDiffHunk::Unfolded {
2955                display_row_range,
2956                status,
2957                ..
2958            } => match status {
2959                DiffHunkStatus::Added | DiffHunkStatus::Modified => {
2960                    let start_row = display_row_range.start;
2961                    let end_row = display_row_range.end;
2962                    // If we're in a multibuffer, row range span might include an
2963                    // excerpt header, so if we were to draw the marker straight away,
2964                    // the hunk might include the rows of that header.
2965                    // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
2966                    // Instead, we simply check whether the range we're dealing with includes
2967                    // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
2968                    let end_row_in_current_excerpt = snapshot
2969                        .blocks_in_range(start_row..end_row)
2970                        .find_map(|(start_row, block)| {
2971                            if matches!(block, TransformBlock::ExcerptHeader { .. }) {
2972                                Some(start_row)
2973                            } else {
2974                                None
2975                            }
2976                        })
2977                        .unwrap_or(end_row);
2978
2979                    let start_y = start_row.as_f32() * line_height - scroll_top;
2980                    let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
2981
2982                    let width = 0.275 * line_height;
2983                    let highlight_origin = bounds.origin + point(px(0.), start_y);
2984                    let highlight_size = size(width, end_y - start_y);
2985                    Bounds::new(highlight_origin, highlight_size)
2986                }
2987                DiffHunkStatus::Removed => {
2988                    let row = display_row_range.start;
2989
2990                    let offset = line_height / 2.;
2991                    let start_y = row.as_f32() * line_height - offset - scroll_top;
2992                    let end_y = start_y + line_height;
2993
2994                    let width = 0.35 * line_height;
2995                    let highlight_origin = bounds.origin + point(px(0.), start_y);
2996                    let highlight_size = size(width, end_y - start_y);
2997                    Bounds::new(highlight_origin, highlight_size)
2998                }
2999            },
3000        }
3001    }
3002
3003    fn paint_gutter_indicators(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3004        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3005            cx.with_element_namespace("gutter_fold_toggles", |cx| {
3006                for fold_indicator in layout.gutter_fold_toggles.iter_mut().flatten() {
3007                    fold_indicator.paint(cx);
3008                }
3009            });
3010
3011            for test_indicators in layout.test_indicators.iter_mut() {
3012                test_indicators.paint(cx);
3013            }
3014
3015            if let Some(indicator) = layout.code_actions_indicator.as_mut() {
3016                indicator.paint(cx);
3017            }
3018        });
3019    }
3020
3021    fn paint_gutter_highlights(&self, layout: &EditorLayout, cx: &mut WindowContext) {
3022        for (_, hunk_hitbox) in &layout.display_hunks {
3023            if let Some(hunk_hitbox) = hunk_hitbox {
3024                cx.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
3025            }
3026        }
3027
3028        let show_git_gutter = layout
3029            .position_map
3030            .snapshot
3031            .show_git_diff_gutter
3032            .unwrap_or_else(|| {
3033                matches!(
3034                    ProjectSettings::get_global(cx).git.git_gutter,
3035                    Some(GitGutterSetting::TrackedFiles)
3036                )
3037            });
3038        if show_git_gutter {
3039            Self::paint_diff_hunks(layout, cx)
3040        }
3041
3042        let highlight_width = 0.275 * layout.position_map.line_height;
3043        let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
3044        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3045            for (range, color) in &layout.highlighted_gutter_ranges {
3046                let start_row = if range.start.row() < layout.visible_display_row_range.start {
3047                    layout.visible_display_row_range.start - DisplayRow(1)
3048                } else {
3049                    range.start.row()
3050                };
3051                let end_row = if range.end.row() > layout.visible_display_row_range.end {
3052                    layout.visible_display_row_range.end + DisplayRow(1)
3053                } else {
3054                    range.end.row()
3055                };
3056
3057                let start_y = layout.gutter_hitbox.top()
3058                    + start_row.0 as f32 * layout.position_map.line_height
3059                    - layout.position_map.scroll_pixel_position.y;
3060                let end_y = layout.gutter_hitbox.top()
3061                    + (end_row.0 + 1) as f32 * layout.position_map.line_height
3062                    - layout.position_map.scroll_pixel_position.y;
3063                let bounds = Bounds::from_corners(
3064                    point(layout.gutter_hitbox.left(), start_y),
3065                    point(layout.gutter_hitbox.left() + highlight_width, end_y),
3066                );
3067                cx.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
3068            }
3069        });
3070    }
3071
3072    fn paint_blamed_display_rows(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3073        let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
3074            return;
3075        };
3076
3077        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3078            for mut blame_element in blamed_display_rows.into_iter() {
3079                blame_element.paint(cx);
3080            }
3081        })
3082    }
3083
3084    fn paint_text(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3085        cx.with_content_mask(
3086            Some(ContentMask {
3087                bounds: layout.text_hitbox.bounds,
3088            }),
3089            |cx| {
3090                let cursor_style = if self
3091                    .editor
3092                    .read(cx)
3093                    .hovered_link_state
3094                    .as_ref()
3095                    .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
3096                {
3097                    CursorStyle::PointingHand
3098                } else {
3099                    CursorStyle::IBeam
3100                };
3101                cx.set_cursor_style(cursor_style, &layout.text_hitbox);
3102
3103                let invisible_display_ranges = self.paint_highlights(layout, cx);
3104                self.paint_lines(&invisible_display_ranges, layout, cx);
3105                self.paint_redactions(layout, cx);
3106                self.paint_cursors(layout, cx);
3107                self.paint_inline_blame(layout, cx);
3108                cx.with_element_namespace("crease_trailers", |cx| {
3109                    for trailer in layout.crease_trailers.iter_mut().flatten() {
3110                        trailer.element.paint(cx);
3111                    }
3112                });
3113            },
3114        )
3115    }
3116
3117    fn paint_highlights(
3118        &mut self,
3119        layout: &mut EditorLayout,
3120        cx: &mut WindowContext,
3121    ) -> SmallVec<[Range<DisplayPoint>; 32]> {
3122        cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3123            let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
3124            let line_end_overshoot = 0.15 * layout.position_map.line_height;
3125            for (range, color) in &layout.highlighted_ranges {
3126                self.paint_highlighted_range(
3127                    range.clone(),
3128                    *color,
3129                    Pixels::ZERO,
3130                    line_end_overshoot,
3131                    layout,
3132                    cx,
3133                );
3134            }
3135
3136            let corner_radius = 0.15 * layout.position_map.line_height;
3137
3138            for (player_color, selections) in &layout.selections {
3139                for selection in selections.into_iter() {
3140                    self.paint_highlighted_range(
3141                        selection.range.clone(),
3142                        player_color.selection,
3143                        corner_radius,
3144                        corner_radius * 2.,
3145                        layout,
3146                        cx,
3147                    );
3148
3149                    if selection.is_local && !selection.range.is_empty() {
3150                        invisible_display_ranges.push(selection.range.clone());
3151                    }
3152                }
3153            }
3154            invisible_display_ranges
3155        })
3156    }
3157
3158    fn paint_lines(
3159        &mut self,
3160        invisible_display_ranges: &[Range<DisplayPoint>],
3161        layout: &mut EditorLayout,
3162        cx: &mut WindowContext,
3163    ) {
3164        let whitespace_setting = self
3165            .editor
3166            .read(cx)
3167            .buffer
3168            .read(cx)
3169            .settings_at(0, cx)
3170            .show_whitespaces;
3171
3172        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
3173            let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
3174            line_with_invisibles.draw(
3175                layout,
3176                row,
3177                layout.content_origin,
3178                whitespace_setting,
3179                invisible_display_ranges,
3180                cx,
3181            )
3182        }
3183
3184        for line_element in &mut layout.line_elements {
3185            line_element.paint(cx);
3186        }
3187    }
3188
3189    fn paint_redactions(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
3190        if layout.redacted_ranges.is_empty() {
3191            return;
3192        }
3193
3194        let line_end_overshoot = layout.line_end_overshoot();
3195
3196        // A softer than perfect black
3197        let redaction_color = gpui::rgb(0x0e1111);
3198
3199        cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3200            for range in layout.redacted_ranges.iter() {
3201                self.paint_highlighted_range(
3202                    range.clone(),
3203                    redaction_color.into(),
3204                    Pixels::ZERO,
3205                    line_end_overshoot,
3206                    layout,
3207                    cx,
3208                );
3209            }
3210        });
3211    }
3212
3213    fn paint_cursors(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3214        for cursor in &mut layout.visible_cursors {
3215            cursor.paint(layout.content_origin, cx);
3216        }
3217    }
3218
3219    fn paint_scrollbar(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3220        let Some(scrollbar_layout) = layout.scrollbar_layout.as_ref() else {
3221            return;
3222        };
3223
3224        let thumb_bounds = scrollbar_layout.thumb_bounds();
3225        if scrollbar_layout.visible {
3226            cx.paint_layer(scrollbar_layout.hitbox.bounds, |cx| {
3227                cx.paint_quad(quad(
3228                    scrollbar_layout.hitbox.bounds,
3229                    Corners::default(),
3230                    cx.theme().colors().scrollbar_track_background,
3231                    Edges {
3232                        top: Pixels::ZERO,
3233                        right: Pixels::ZERO,
3234                        bottom: Pixels::ZERO,
3235                        left: ScrollbarLayout::BORDER_WIDTH,
3236                    },
3237                    cx.theme().colors().scrollbar_track_border,
3238                ));
3239
3240                let fast_markers =
3241                    self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
3242                // Refresh slow scrollbar markers in the background. Below, we paint whatever markers have already been computed.
3243                self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, cx);
3244
3245                let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
3246                for marker in markers.iter().chain(&fast_markers) {
3247                    let mut marker = marker.clone();
3248                    marker.bounds.origin += scrollbar_layout.hitbox.origin;
3249                    cx.paint_quad(marker);
3250                }
3251
3252                cx.paint_quad(quad(
3253                    thumb_bounds,
3254                    Corners::default(),
3255                    cx.theme().colors().scrollbar_thumb_background,
3256                    Edges {
3257                        top: Pixels::ZERO,
3258                        right: Pixels::ZERO,
3259                        bottom: Pixels::ZERO,
3260                        left: ScrollbarLayout::BORDER_WIDTH,
3261                    },
3262                    cx.theme().colors().scrollbar_thumb_border,
3263                ));
3264            });
3265        }
3266
3267        cx.set_cursor_style(CursorStyle::Arrow, &scrollbar_layout.hitbox);
3268
3269        let row_height = scrollbar_layout.row_height;
3270        let row_range = scrollbar_layout.visible_row_range.clone();
3271
3272        cx.on_mouse_event({
3273            let editor = self.editor.clone();
3274            let hitbox = scrollbar_layout.hitbox.clone();
3275            let mut mouse_position = cx.mouse_position();
3276            move |event: &MouseMoveEvent, phase, cx| {
3277                if phase == DispatchPhase::Capture {
3278                    return;
3279                }
3280
3281                editor.update(cx, |editor, cx| {
3282                    if event.pressed_button == Some(MouseButton::Left)
3283                        && editor.scroll_manager.is_dragging_scrollbar()
3284                    {
3285                        let y = mouse_position.y;
3286                        let new_y = event.position.y;
3287                        if (hitbox.top()..hitbox.bottom()).contains(&y) {
3288                            let mut position = editor.scroll_position(cx);
3289                            position.y += (new_y - y) / row_height;
3290                            if position.y < 0.0 {
3291                                position.y = 0.0;
3292                            }
3293                            editor.set_scroll_position(position, cx);
3294                        }
3295
3296                        cx.stop_propagation();
3297                    } else {
3298                        editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
3299                        if hitbox.is_hovered(cx) {
3300                            editor.scroll_manager.show_scrollbar(cx);
3301                        }
3302                    }
3303                    mouse_position = event.position;
3304                })
3305            }
3306        });
3307
3308        if self.editor.read(cx).scroll_manager.is_dragging_scrollbar() {
3309            cx.on_mouse_event({
3310                let editor = self.editor.clone();
3311                move |_: &MouseUpEvent, phase, cx| {
3312                    if phase == DispatchPhase::Capture {
3313                        return;
3314                    }
3315
3316                    editor.update(cx, |editor, cx| {
3317                        editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
3318                        cx.stop_propagation();
3319                    });
3320                }
3321            });
3322        } else {
3323            cx.on_mouse_event({
3324                let editor = self.editor.clone();
3325                let hitbox = scrollbar_layout.hitbox.clone();
3326                move |event: &MouseDownEvent, phase, cx| {
3327                    if phase == DispatchPhase::Capture || !hitbox.is_hovered(cx) {
3328                        return;
3329                    }
3330
3331                    editor.update(cx, |editor, cx| {
3332                        editor.scroll_manager.set_is_dragging_scrollbar(true, cx);
3333
3334                        let y = event.position.y;
3335                        if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
3336                            let center_row = ((y - hitbox.top()) / row_height).round() as u32;
3337                            let top_row = center_row
3338                                .saturating_sub((row_range.end - row_range.start) as u32 / 2);
3339                            let mut position = editor.scroll_position(cx);
3340                            position.y = top_row as f32;
3341                            editor.set_scroll_position(position, cx);
3342                        } else {
3343                            editor.scroll_manager.show_scrollbar(cx);
3344                        }
3345
3346                        cx.stop_propagation();
3347                    });
3348                }
3349            });
3350        }
3351    }
3352
3353    fn collect_fast_scrollbar_markers(
3354        &self,
3355        layout: &EditorLayout,
3356        scrollbar_layout: &ScrollbarLayout,
3357        cx: &mut WindowContext,
3358    ) -> Vec<PaintQuad> {
3359        const LIMIT: usize = 100;
3360        if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
3361            return vec![];
3362        }
3363        let cursor_ranges = layout
3364            .cursors
3365            .iter()
3366            .map(|(point, color)| ColoredRange {
3367                start: point.row(),
3368                end: point.row(),
3369                color: *color,
3370            })
3371            .collect_vec();
3372        scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
3373    }
3374
3375    fn refresh_slow_scrollbar_markers(
3376        &self,
3377        layout: &EditorLayout,
3378        scrollbar_layout: &ScrollbarLayout,
3379        cx: &mut WindowContext,
3380    ) {
3381        self.editor.update(cx, |editor, cx| {
3382            if !editor.is_singleton(cx)
3383                || !editor
3384                    .scrollbar_marker_state
3385                    .should_refresh(scrollbar_layout.hitbox.size)
3386            {
3387                return;
3388            }
3389
3390            let scrollbar_layout = scrollbar_layout.clone();
3391            let background_highlights = editor.background_highlights.clone();
3392            let snapshot = layout.position_map.snapshot.clone();
3393            let theme = cx.theme().clone();
3394            let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
3395
3396            editor.scrollbar_marker_state.dirty = false;
3397            editor.scrollbar_marker_state.pending_refresh =
3398                Some(cx.spawn(|editor, mut cx| async move {
3399                    let scrollbar_size = scrollbar_layout.hitbox.size;
3400                    let scrollbar_markers = cx
3401                        .background_executor()
3402                        .spawn(async move {
3403                            let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
3404                            let mut marker_quads = Vec::new();
3405                            if scrollbar_settings.git_diff {
3406                                let marker_row_ranges = snapshot
3407                                    .buffer_snapshot
3408                                    .git_diff_hunks_in_range(
3409                                        MultiBufferRow::MIN..MultiBufferRow::MAX,
3410                                    )
3411                                    .map(|hunk| {
3412                                        let start_display_row =
3413                                            MultiBufferPoint::new(hunk.associated_range.start.0, 0)
3414                                                .to_display_point(&snapshot.display_snapshot)
3415                                                .row();
3416                                        let mut end_display_row =
3417                                            MultiBufferPoint::new(hunk.associated_range.end.0, 0)
3418                                                .to_display_point(&snapshot.display_snapshot)
3419                                                .row();
3420                                        if end_display_row != start_display_row {
3421                                            end_display_row.0 -= 1;
3422                                        }
3423                                        let color = match hunk_status(&hunk) {
3424                                            DiffHunkStatus::Added => theme.status().created,
3425                                            DiffHunkStatus::Modified => theme.status().modified,
3426                                            DiffHunkStatus::Removed => theme.status().deleted,
3427                                        };
3428                                        ColoredRange {
3429                                            start: start_display_row,
3430                                            end: end_display_row,
3431                                            color,
3432                                        }
3433                                    });
3434
3435                                marker_quads.extend(
3436                                    scrollbar_layout
3437                                        .marker_quads_for_ranges(marker_row_ranges, Some(0)),
3438                                );
3439                            }
3440
3441                            for (background_highlight_id, (_, background_ranges)) in
3442                                background_highlights.iter()
3443                            {
3444                                let is_search_highlights = *background_highlight_id
3445                                    == TypeId::of::<BufferSearchHighlights>();
3446                                let is_symbol_occurrences = *background_highlight_id
3447                                    == TypeId::of::<DocumentHighlightRead>()
3448                                    || *background_highlight_id
3449                                        == TypeId::of::<DocumentHighlightWrite>();
3450                                if (is_search_highlights && scrollbar_settings.search_results)
3451                                    || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
3452                                {
3453                                    let mut color = theme.status().info;
3454                                    if is_symbol_occurrences {
3455                                        color.fade_out(0.5);
3456                                    }
3457                                    let marker_row_ranges =
3458                                        background_ranges.into_iter().map(|range| {
3459                                            let display_start = range
3460                                                .start
3461                                                .to_display_point(&snapshot.display_snapshot);
3462                                            let display_end = range
3463                                                .end
3464                                                .to_display_point(&snapshot.display_snapshot);
3465                                            ColoredRange {
3466                                                start: display_start.row(),
3467                                                end: display_end.row(),
3468                                                color,
3469                                            }
3470                                        });
3471                                    marker_quads.extend(
3472                                        scrollbar_layout
3473                                            .marker_quads_for_ranges(marker_row_ranges, Some(1)),
3474                                    );
3475                                }
3476                            }
3477
3478                            if scrollbar_settings.diagnostics {
3479                                let diagnostics = snapshot
3480                                    .buffer_snapshot
3481                                    .diagnostics_in_range::<_, Point>(
3482                                        Point::zero()..max_point,
3483                                        false,
3484                                    )
3485                                    // We want to sort by severity, in order to paint the most severe diagnostics last.
3486                                    .sorted_by_key(|diagnostic| {
3487                                        std::cmp::Reverse(diagnostic.diagnostic.severity)
3488                                    });
3489
3490                                let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
3491                                    let start_display = diagnostic
3492                                        .range
3493                                        .start
3494                                        .to_display_point(&snapshot.display_snapshot);
3495                                    let end_display = diagnostic
3496                                        .range
3497                                        .end
3498                                        .to_display_point(&snapshot.display_snapshot);
3499                                    let color = match diagnostic.diagnostic.severity {
3500                                        DiagnosticSeverity::ERROR => theme.status().error,
3501                                        DiagnosticSeverity::WARNING => theme.status().warning,
3502                                        DiagnosticSeverity::INFORMATION => theme.status().info,
3503                                        _ => theme.status().hint,
3504                                    };
3505                                    ColoredRange {
3506                                        start: start_display.row(),
3507                                        end: end_display.row(),
3508                                        color,
3509                                    }
3510                                });
3511                                marker_quads.extend(
3512                                    scrollbar_layout
3513                                        .marker_quads_for_ranges(marker_row_ranges, Some(2)),
3514                                );
3515                            }
3516
3517                            Arc::from(marker_quads)
3518                        })
3519                        .await;
3520
3521                    editor.update(&mut cx, |editor, cx| {
3522                        editor.scrollbar_marker_state.markers = scrollbar_markers;
3523                        editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
3524                        editor.scrollbar_marker_state.pending_refresh = None;
3525                        cx.notify();
3526                    })?;
3527
3528                    Ok(())
3529                }));
3530        });
3531    }
3532
3533    #[allow(clippy::too_many_arguments)]
3534    fn paint_highlighted_range(
3535        &self,
3536        range: Range<DisplayPoint>,
3537        color: Hsla,
3538        corner_radius: Pixels,
3539        line_end_overshoot: Pixels,
3540        layout: &EditorLayout,
3541        cx: &mut WindowContext,
3542    ) {
3543        let start_row = layout.visible_display_row_range.start;
3544        let end_row = layout.visible_display_row_range.end;
3545        if range.start != range.end {
3546            let row_range = if range.end.column() == 0 {
3547                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
3548            } else {
3549                cmp::max(range.start.row(), start_row)
3550                    ..cmp::min(range.end.row().next_row(), end_row)
3551            };
3552
3553            let highlighted_range = HighlightedRange {
3554                color,
3555                line_height: layout.position_map.line_height,
3556                corner_radius,
3557                start_y: layout.content_origin.y
3558                    + row_range.start.as_f32() * layout.position_map.line_height
3559                    - layout.position_map.scroll_pixel_position.y,
3560                lines: row_range
3561                    .iter_rows()
3562                    .map(|row| {
3563                        let line_layout =
3564                            &layout.position_map.line_layouts[row.minus(start_row) as usize];
3565                        HighlightedRangeLine {
3566                            start_x: if row == range.start.row() {
3567                                layout.content_origin.x
3568                                    + line_layout.x_for_index(range.start.column() as usize)
3569                                    - layout.position_map.scroll_pixel_position.x
3570                            } else {
3571                                layout.content_origin.x
3572                                    - layout.position_map.scroll_pixel_position.x
3573                            },
3574                            end_x: if row == range.end.row() {
3575                                layout.content_origin.x
3576                                    + line_layout.x_for_index(range.end.column() as usize)
3577                                    - layout.position_map.scroll_pixel_position.x
3578                            } else {
3579                                layout.content_origin.x + line_layout.width + line_end_overshoot
3580                                    - layout.position_map.scroll_pixel_position.x
3581                            },
3582                        }
3583                    })
3584                    .collect(),
3585            };
3586
3587            highlighted_range.paint(layout.text_hitbox.bounds, cx);
3588        }
3589    }
3590
3591    fn paint_inline_blame(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3592        if let Some(mut inline_blame) = layout.inline_blame.take() {
3593            cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3594                inline_blame.paint(cx);
3595            })
3596        }
3597    }
3598
3599    fn paint_blocks(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3600        for mut block in layout.blocks.drain(..) {
3601            block.element.paint(cx);
3602        }
3603    }
3604
3605    fn paint_mouse_context_menu(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3606        if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
3607            mouse_context_menu.paint(cx);
3608        }
3609    }
3610
3611    fn paint_scroll_wheel_listener(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
3612        cx.on_mouse_event({
3613            let position_map = layout.position_map.clone();
3614            let editor = self.editor.clone();
3615            let hitbox = layout.hitbox.clone();
3616            let mut delta = ScrollDelta::default();
3617
3618            // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
3619            // accidentally turn off their scrolling.
3620            let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
3621
3622            move |event: &ScrollWheelEvent, phase, cx| {
3623                if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
3624                    delta = delta.coalesce(event.delta);
3625                    editor.update(cx, |editor, cx| {
3626                        let position_map: &PositionMap = &position_map;
3627
3628                        let line_height = position_map.line_height;
3629                        let max_glyph_width = position_map.em_width;
3630                        let (delta, axis) = match delta {
3631                            gpui::ScrollDelta::Pixels(mut pixels) => {
3632                                //Trackpad
3633                                let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
3634                                (pixels, axis)
3635                            }
3636
3637                            gpui::ScrollDelta::Lines(lines) => {
3638                                //Not trackpad
3639                                let pixels =
3640                                    point(lines.x * max_glyph_width, lines.y * line_height);
3641                                (pixels, None)
3642                            }
3643                        };
3644
3645                        let current_scroll_position = position_map.snapshot.scroll_position();
3646                        let x = (current_scroll_position.x * max_glyph_width
3647                            - (delta.x * scroll_sensitivity))
3648                            / max_glyph_width;
3649                        let y = (current_scroll_position.y * line_height
3650                            - (delta.y * scroll_sensitivity))
3651                            / line_height;
3652                        let mut scroll_position =
3653                            point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
3654                        let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
3655                        if forbid_vertical_scroll {
3656                            scroll_position.y = current_scroll_position.y;
3657                        }
3658
3659                        if scroll_position != current_scroll_position {
3660                            editor.scroll(scroll_position, axis, cx);
3661                            cx.stop_propagation();
3662                        }
3663                    });
3664                }
3665            }
3666        });
3667    }
3668
3669    fn paint_mouse_listeners(
3670        &mut self,
3671        layout: &EditorLayout,
3672        hovered_hunk: Option<HunkToExpand>,
3673        cx: &mut WindowContext,
3674    ) {
3675        self.paint_scroll_wheel_listener(layout, cx);
3676
3677        cx.on_mouse_event({
3678            let position_map = layout.position_map.clone();
3679            let editor = self.editor.clone();
3680            let text_hitbox = layout.text_hitbox.clone();
3681            let gutter_hitbox = layout.gutter_hitbox.clone();
3682
3683            move |event: &MouseDownEvent, phase, cx| {
3684                if phase == DispatchPhase::Bubble {
3685                    match event.button {
3686                        MouseButton::Left => editor.update(cx, |editor, cx| {
3687                            Self::mouse_left_down(
3688                                editor,
3689                                event,
3690                                hovered_hunk.as_ref(),
3691                                &position_map,
3692                                &text_hitbox,
3693                                &gutter_hitbox,
3694                                cx,
3695                            );
3696                        }),
3697                        MouseButton::Right => editor.update(cx, |editor, cx| {
3698                            Self::mouse_right_down(editor, event, &position_map, &text_hitbox, cx);
3699                        }),
3700                        MouseButton::Middle => editor.update(cx, |editor, cx| {
3701                            Self::mouse_middle_down(editor, event, &position_map, &text_hitbox, cx);
3702                        }),
3703                        _ => {}
3704                    };
3705                }
3706            }
3707        });
3708
3709        cx.on_mouse_event({
3710            let editor = self.editor.clone();
3711            let position_map = layout.position_map.clone();
3712            let text_hitbox = layout.text_hitbox.clone();
3713
3714            move |event: &MouseUpEvent, phase, cx| {
3715                if phase == DispatchPhase::Bubble {
3716                    editor.update(cx, |editor, cx| {
3717                        Self::mouse_up(editor, event, &position_map, &text_hitbox, cx)
3718                    });
3719                }
3720            }
3721        });
3722        cx.on_mouse_event({
3723            let position_map = layout.position_map.clone();
3724            let editor = self.editor.clone();
3725            let text_hitbox = layout.text_hitbox.clone();
3726            let gutter_hitbox = layout.gutter_hitbox.clone();
3727
3728            move |event: &MouseMoveEvent, phase, cx| {
3729                if phase == DispatchPhase::Bubble {
3730                    editor.update(cx, |editor, cx| {
3731                        if event.pressed_button == Some(MouseButton::Left)
3732                            || event.pressed_button == Some(MouseButton::Middle)
3733                        {
3734                            Self::mouse_dragged(
3735                                editor,
3736                                event,
3737                                &position_map,
3738                                text_hitbox.bounds,
3739                                cx,
3740                            )
3741                        }
3742
3743                        Self::mouse_moved(
3744                            editor,
3745                            event,
3746                            &position_map,
3747                            &text_hitbox,
3748                            &gutter_hitbox,
3749                            cx,
3750                        )
3751                    });
3752                }
3753            }
3754        });
3755    }
3756
3757    fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
3758        bounds.upper_right().x - self.style.scrollbar_width
3759    }
3760
3761    fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
3762        let style = &self.style;
3763        let font_size = style.text.font_size.to_pixels(cx.rem_size());
3764        let layout = cx
3765            .text_system()
3766            .shape_line(
3767                SharedString::from(" ".repeat(column)),
3768                font_size,
3769                &[TextRun {
3770                    len: column,
3771                    font: style.text.font(),
3772                    color: Hsla::default(),
3773                    background_color: None,
3774                    underline: None,
3775                    strikethrough: None,
3776                }],
3777            )
3778            .unwrap();
3779
3780        layout.width
3781    }
3782
3783    fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
3784        let digit_count = snapshot
3785            .max_buffer_row()
3786            .next_row()
3787            .as_f32()
3788            .log10()
3789            .floor() as usize
3790            + 1;
3791        self.column_pixels(digit_count, cx)
3792    }
3793}
3794
3795fn prepaint_gutter_button(
3796    button: IconButton,
3797    row: DisplayRow,
3798    line_height: Pixels,
3799    gutter_dimensions: &GutterDimensions,
3800    scroll_pixel_position: gpui::Point<Pixels>,
3801    gutter_hitbox: &Hitbox,
3802    cx: &mut WindowContext<'_>,
3803) -> AnyElement {
3804    let mut button = button.into_any_element();
3805    let available_space = size(
3806        AvailableSpace::MinContent,
3807        AvailableSpace::Definite(line_height),
3808    );
3809    let indicator_size = button.layout_as_root(available_space, cx);
3810
3811    let blame_width = gutter_dimensions
3812        .git_blame_entries_width
3813        .unwrap_or(Pixels::ZERO);
3814
3815    let mut x = blame_width;
3816    let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
3817        - indicator_size.width
3818        - blame_width;
3819    x += available_width / 2.;
3820
3821    let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
3822    y += (line_height - indicator_size.height) / 2.;
3823
3824    button.prepaint_as_root(gutter_hitbox.origin + point(x, y), available_space, cx);
3825    button
3826}
3827
3828fn render_inline_blame_entry(
3829    blame: &gpui::Model<GitBlame>,
3830    blame_entry: BlameEntry,
3831    style: &EditorStyle,
3832    workspace: Option<WeakView<Workspace>>,
3833    cx: &mut WindowContext<'_>,
3834) -> AnyElement {
3835    let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
3836
3837    let author = blame_entry.author.as_deref().unwrap_or_default();
3838    let text = format!("{}, {}", author, relative_timestamp);
3839
3840    let details = blame.read(cx).details_for_entry(&blame_entry);
3841
3842    let tooltip = cx.new_view(|_| BlameEntryTooltip::new(blame_entry, details, style, workspace));
3843
3844    h_flex()
3845        .id("inline-blame")
3846        .w_full()
3847        .font_family(style.text.font().family)
3848        .text_color(cx.theme().status().hint)
3849        .line_height(style.text.line_height)
3850        .child(Icon::new(IconName::FileGit).color(Color::Hint))
3851        .child(text)
3852        .gap_2()
3853        .hoverable_tooltip(move |_| tooltip.clone().into())
3854        .into_any()
3855}
3856
3857fn render_blame_entry(
3858    ix: usize,
3859    blame: &gpui::Model<GitBlame>,
3860    blame_entry: BlameEntry,
3861    style: &EditorStyle,
3862    last_used_color: &mut Option<(PlayerColor, Oid)>,
3863    editor: View<Editor>,
3864    cx: &mut WindowContext<'_>,
3865) -> AnyElement {
3866    let mut sha_color = cx
3867        .theme()
3868        .players()
3869        .color_for_participant(blame_entry.sha.into());
3870    // If the last color we used is the same as the one we get for this line, but
3871    // the commit SHAs are different, then we try again to get a different color.
3872    match *last_used_color {
3873        Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
3874            let index: u32 = blame_entry.sha.into();
3875            sha_color = cx.theme().players().color_for_participant(index + 1);
3876        }
3877        _ => {}
3878    };
3879    last_used_color.replace((sha_color, blame_entry.sha));
3880
3881    let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
3882
3883    let short_commit_id = blame_entry.sha.display_short();
3884
3885    let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
3886    let name = util::truncate_and_trailoff(author_name, 20);
3887
3888    let details = blame.read(cx).details_for_entry(&blame_entry);
3889
3890    let workspace = editor.read(cx).workspace.as_ref().map(|(w, _)| w.clone());
3891
3892    let tooltip = cx.new_view(|_| {
3893        BlameEntryTooltip::new(blame_entry.clone(), details.clone(), style, workspace)
3894    });
3895
3896    h_flex()
3897        .w_full()
3898        .font_family(style.text.font().family)
3899        .line_height(style.text.line_height)
3900        .id(("blame", ix))
3901        .children([
3902            div()
3903                .text_color(sha_color.cursor)
3904                .child(short_commit_id)
3905                .mr_2(),
3906            div()
3907                .w_full()
3908                .h_flex()
3909                .justify_between()
3910                .text_color(cx.theme().status().hint)
3911                .child(name)
3912                .child(relative_timestamp),
3913        ])
3914        .on_mouse_down(MouseButton::Right, {
3915            let blame_entry = blame_entry.clone();
3916            let details = details.clone();
3917            move |event, cx| {
3918                deploy_blame_entry_context_menu(
3919                    &blame_entry,
3920                    details.as_ref(),
3921                    editor.clone(),
3922                    event.position,
3923                    cx,
3924                );
3925            }
3926        })
3927        .hover(|style| style.bg(cx.theme().colors().element_hover))
3928        .when_some(
3929            details.and_then(|details| details.permalink),
3930            |this, url| {
3931                let url = url.clone();
3932                this.cursor_pointer().on_click(move |_, cx| {
3933                    cx.stop_propagation();
3934                    cx.open_url(url.as_str())
3935                })
3936            },
3937        )
3938        .hoverable_tooltip(move |_| tooltip.clone().into())
3939        .into_any()
3940}
3941
3942fn deploy_blame_entry_context_menu(
3943    blame_entry: &BlameEntry,
3944    details: Option<&CommitDetails>,
3945    editor: View<Editor>,
3946    position: gpui::Point<Pixels>,
3947    cx: &mut WindowContext<'_>,
3948) {
3949    let context_menu = ContextMenu::build(cx, move |this, _| {
3950        let sha = format!("{}", blame_entry.sha);
3951        this.entry("Copy commit SHA", None, move |cx| {
3952            cx.write_to_clipboard(ClipboardItem::new(sha.clone()));
3953        })
3954        .when_some(
3955            details.and_then(|details| details.permalink.clone()),
3956            |this, url| this.entry("Open permalink", None, move |cx| cx.open_url(url.as_str())),
3957        )
3958    });
3959
3960    editor.update(cx, move |editor, cx| {
3961        editor.mouse_context_menu = Some(MouseContextMenu::new(position, context_menu, cx));
3962        cx.notify();
3963    });
3964}
3965
3966#[derive(Debug)]
3967pub(crate) struct LineWithInvisibles {
3968    fragments: SmallVec<[LineFragment; 1]>,
3969    invisibles: Vec<Invisible>,
3970    len: usize,
3971    width: Pixels,
3972    font_size: Pixels,
3973}
3974
3975#[allow(clippy::large_enum_variant)]
3976enum LineFragment {
3977    Text(ShapedLine),
3978    Element {
3979        element: Option<AnyElement>,
3980        size: Size<Pixels>,
3981        len: usize,
3982    },
3983}
3984
3985impl fmt::Debug for LineFragment {
3986    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3987        match self {
3988            LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
3989            LineFragment::Element { size, len, .. } => f
3990                .debug_struct("Element")
3991                .field("size", size)
3992                .field("len", len)
3993                .finish(),
3994        }
3995    }
3996}
3997
3998impl LineWithInvisibles {
3999    fn from_chunks<'a>(
4000        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
4001        text_style: &TextStyle,
4002        max_line_len: usize,
4003        max_line_count: usize,
4004        line_number_layouts: &[Option<ShapedLine>],
4005        editor_mode: EditorMode,
4006        cx: &mut WindowContext,
4007    ) -> Vec<Self> {
4008        let mut layouts = Vec::with_capacity(max_line_count);
4009        let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
4010        let mut line = String::new();
4011        let mut invisibles = Vec::new();
4012        let mut width = Pixels::ZERO;
4013        let mut len = 0;
4014        let mut styles = Vec::new();
4015        let mut non_whitespace_added = false;
4016        let mut row = 0;
4017        let mut line_exceeded_max_len = false;
4018        let font_size = text_style.font_size.to_pixels(cx.rem_size());
4019
4020        let ellipsis = SharedString::from("");
4021
4022        for highlighted_chunk in chunks.chain([HighlightedChunk {
4023            text: "\n",
4024            style: None,
4025            is_tab: false,
4026            renderer: None,
4027        }]) {
4028            if let Some(renderer) = highlighted_chunk.renderer {
4029                if !line.is_empty() {
4030                    let shaped_line = cx
4031                        .text_system()
4032                        .shape_line(line.clone().into(), font_size, &styles)
4033                        .unwrap();
4034                    width += shaped_line.width;
4035                    len += shaped_line.len;
4036                    fragments.push(LineFragment::Text(shaped_line));
4037                    line.clear();
4038                    styles.clear();
4039                }
4040
4041                let available_width = if renderer.constrain_width {
4042                    let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
4043                        ellipsis.clone()
4044                    } else {
4045                        SharedString::from(Arc::from(highlighted_chunk.text))
4046                    };
4047                    let shaped_line = cx
4048                        .text_system()
4049                        .shape_line(
4050                            chunk,
4051                            font_size,
4052                            &[text_style.to_run(highlighted_chunk.text.len())],
4053                        )
4054                        .unwrap();
4055                    AvailableSpace::Definite(shaped_line.width)
4056                } else {
4057                    AvailableSpace::MinContent
4058                };
4059
4060                let mut element = (renderer.render)(cx);
4061                let line_height = text_style.line_height_in_pixels(cx.rem_size());
4062                let size = element.layout_as_root(
4063                    size(available_width, AvailableSpace::Definite(line_height)),
4064                    cx,
4065                );
4066
4067                width += size.width;
4068                len += highlighted_chunk.text.len();
4069                fragments.push(LineFragment::Element {
4070                    element: Some(element),
4071                    size,
4072                    len: highlighted_chunk.text.len(),
4073                });
4074            } else {
4075                for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
4076                    if ix > 0 {
4077                        let shaped_line = cx
4078                            .text_system()
4079                            .shape_line(line.clone().into(), font_size, &styles)
4080                            .unwrap();
4081                        width += shaped_line.width;
4082                        len += shaped_line.len;
4083                        fragments.push(LineFragment::Text(shaped_line));
4084                        layouts.push(Self {
4085                            width: mem::take(&mut width),
4086                            len: mem::take(&mut len),
4087                            fragments: mem::take(&mut fragments),
4088                            invisibles: std::mem::take(&mut invisibles),
4089                            font_size,
4090                        });
4091
4092                        line.clear();
4093                        styles.clear();
4094                        row += 1;
4095                        line_exceeded_max_len = false;
4096                        non_whitespace_added = false;
4097                        if row == max_line_count {
4098                            return layouts;
4099                        }
4100                    }
4101
4102                    if !line_chunk.is_empty() && !line_exceeded_max_len {
4103                        let text_style = if let Some(style) = highlighted_chunk.style {
4104                            Cow::Owned(text_style.clone().highlight(style))
4105                        } else {
4106                            Cow::Borrowed(text_style)
4107                        };
4108
4109                        if line.len() + line_chunk.len() > max_line_len {
4110                            let mut chunk_len = max_line_len - line.len();
4111                            while !line_chunk.is_char_boundary(chunk_len) {
4112                                chunk_len -= 1;
4113                            }
4114                            line_chunk = &line_chunk[..chunk_len];
4115                            line_exceeded_max_len = true;
4116                        }
4117
4118                        styles.push(TextRun {
4119                            len: line_chunk.len(),
4120                            font: text_style.font(),
4121                            color: text_style.color,
4122                            background_color: text_style.background_color,
4123                            underline: text_style.underline,
4124                            strikethrough: text_style.strikethrough,
4125                        });
4126
4127                        if editor_mode == EditorMode::Full {
4128                            // Line wrap pads its contents with fake whitespaces,
4129                            // avoid printing them
4130                            let inside_wrapped_string = line_number_layouts
4131                                .get(row)
4132                                .and_then(|layout| layout.as_ref())
4133                                .is_none();
4134                            if highlighted_chunk.is_tab {
4135                                if non_whitespace_added || !inside_wrapped_string {
4136                                    invisibles.push(Invisible::Tab {
4137                                        line_start_offset: line.len(),
4138                                        line_end_offset: line.len() + line_chunk.len(),
4139                                    });
4140                                }
4141                            } else {
4142                                invisibles.extend(
4143                                    line_chunk
4144                                        .bytes()
4145                                        .enumerate()
4146                                        .filter(|(_, line_byte)| {
4147                                            let is_whitespace =
4148                                                (*line_byte as char).is_whitespace();
4149                                            non_whitespace_added |= !is_whitespace;
4150                                            is_whitespace
4151                                                && (non_whitespace_added || !inside_wrapped_string)
4152                                        })
4153                                        .map(|(whitespace_index, _)| Invisible::Whitespace {
4154                                            line_offset: line.len() + whitespace_index,
4155                                        }),
4156                                )
4157                            }
4158                        }
4159
4160                        line.push_str(line_chunk);
4161                    }
4162                }
4163            }
4164        }
4165
4166        layouts
4167    }
4168
4169    fn prepaint(
4170        &mut self,
4171        line_height: Pixels,
4172        scroll_pixel_position: gpui::Point<Pixels>,
4173        row: DisplayRow,
4174        content_origin: gpui::Point<Pixels>,
4175        line_elements: &mut SmallVec<[AnyElement; 1]>,
4176        cx: &mut WindowContext,
4177    ) {
4178        let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
4179        let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
4180        for fragment in &mut self.fragments {
4181            match fragment {
4182                LineFragment::Text(line) => {
4183                    fragment_origin.x += line.width;
4184                }
4185                LineFragment::Element { element, size, .. } => {
4186                    let mut element = element
4187                        .take()
4188                        .expect("you can't prepaint LineWithInvisibles twice");
4189
4190                    // Center the element vertically within the line.
4191                    let mut element_origin = fragment_origin;
4192                    element_origin.y += (line_height - size.height) / 2.;
4193                    element.prepaint_at(element_origin, cx);
4194                    line_elements.push(element);
4195
4196                    fragment_origin.x += size.width;
4197                }
4198            }
4199        }
4200    }
4201
4202    fn draw(
4203        &self,
4204        layout: &EditorLayout,
4205        row: DisplayRow,
4206        content_origin: gpui::Point<Pixels>,
4207        whitespace_setting: ShowWhitespaceSetting,
4208        selection_ranges: &[Range<DisplayPoint>],
4209        cx: &mut WindowContext,
4210    ) {
4211        let line_height = layout.position_map.line_height;
4212        let line_y = line_height
4213            * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
4214
4215        let mut fragment_origin =
4216            content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
4217
4218        for fragment in &self.fragments {
4219            match fragment {
4220                LineFragment::Text(line) => {
4221                    line.paint(fragment_origin, line_height, cx).log_err();
4222                    fragment_origin.x += line.width;
4223                }
4224                LineFragment::Element { size, .. } => {
4225                    fragment_origin.x += size.width;
4226                }
4227            }
4228        }
4229
4230        self.draw_invisibles(
4231            &selection_ranges,
4232            layout,
4233            content_origin,
4234            line_y,
4235            row,
4236            line_height,
4237            whitespace_setting,
4238            cx,
4239        );
4240    }
4241
4242    #[allow(clippy::too_many_arguments)]
4243    fn draw_invisibles(
4244        &self,
4245        selection_ranges: &[Range<DisplayPoint>],
4246        layout: &EditorLayout,
4247        content_origin: gpui::Point<Pixels>,
4248        line_y: Pixels,
4249        row: DisplayRow,
4250        line_height: Pixels,
4251        whitespace_setting: ShowWhitespaceSetting,
4252        cx: &mut WindowContext,
4253    ) {
4254        let extract_whitespace_info = |invisible: &Invisible| {
4255            let (token_offset, token_end_offset, invisible_symbol) = match invisible {
4256                Invisible::Tab {
4257                    line_start_offset,
4258                    line_end_offset,
4259                } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
4260                Invisible::Whitespace { line_offset } => {
4261                    (*line_offset, line_offset + 1, &layout.space_invisible)
4262                }
4263            };
4264
4265            let x_offset = self.x_for_index(token_offset);
4266            let invisible_offset =
4267                (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
4268            let origin = content_origin
4269                + gpui::point(
4270                    x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
4271                    line_y,
4272                );
4273
4274            (
4275                [token_offset, token_end_offset],
4276                Box::new(move |cx: &mut WindowContext| {
4277                    invisible_symbol.paint(origin, line_height, cx).log_err();
4278                }),
4279            )
4280        };
4281
4282        let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
4283        match whitespace_setting {
4284            ShowWhitespaceSetting::None => return,
4285            ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(cx)),
4286            ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
4287                let invisible_point = DisplayPoint::new(row, start as u32);
4288                if !selection_ranges
4289                    .iter()
4290                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
4291                {
4292                    return;
4293                }
4294
4295                paint(cx);
4296            }),
4297
4298            // For a whitespace to be on a boundary, any of the following conditions need to be met:
4299            // - It is a tab
4300            // - It is adjacent to an edge (start or end)
4301            // - It is adjacent to a whitespace (left or right)
4302            ShowWhitespaceSetting::Boundary => {
4303                // We'll need to keep track of the last invisible we've seen and then check if we are adjacent to it for some of
4304                // the above cases.
4305                // Note: We zip in the original `invisibles` to check for tab equality
4306                let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut WindowContext)>)> = None;
4307                for (([start, end], paint), invisible) in
4308                    invisible_iter.zip_eq(self.invisibles.iter())
4309                {
4310                    let should_render = match (&last_seen, invisible) {
4311                        (_, Invisible::Tab { .. }) => true,
4312                        (Some((_, last_end, _)), _) => *last_end == start,
4313                        _ => false,
4314                    };
4315
4316                    if should_render || start == 0 || end == self.len {
4317                        paint(cx);
4318
4319                        // Since we are scanning from the left, we will skip over the first available whitespace that is part
4320                        // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
4321                        if let Some((should_render_last, last_end, paint_last)) = last_seen {
4322                            // Note that we need to make sure that the last one is actually adjacent
4323                            if !should_render_last && last_end == start {
4324                                paint_last(cx);
4325                            }
4326                        }
4327                    }
4328
4329                    // Manually render anything within a selection
4330                    let invisible_point = DisplayPoint::new(row, start as u32);
4331                    if selection_ranges.iter().any(|region| {
4332                        region.start <= invisible_point && invisible_point < region.end
4333                    }) {
4334                        paint(cx);
4335                    }
4336
4337                    last_seen = Some((should_render, end, paint));
4338                }
4339            }
4340        };
4341    }
4342
4343    pub fn x_for_index(&self, index: usize) -> Pixels {
4344        let mut fragment_start_x = Pixels::ZERO;
4345        let mut fragment_start_index = 0;
4346
4347        for fragment in &self.fragments {
4348            match fragment {
4349                LineFragment::Text(shaped_line) => {
4350                    let fragment_end_index = fragment_start_index + shaped_line.len;
4351                    if index < fragment_end_index {
4352                        return fragment_start_x
4353                            + shaped_line.x_for_index(index - fragment_start_index);
4354                    }
4355                    fragment_start_x += shaped_line.width;
4356                    fragment_start_index = fragment_end_index;
4357                }
4358                LineFragment::Element { len, size, .. } => {
4359                    let fragment_end_index = fragment_start_index + len;
4360                    if index < fragment_end_index {
4361                        return fragment_start_x;
4362                    }
4363                    fragment_start_x += size.width;
4364                    fragment_start_index = fragment_end_index;
4365                }
4366            }
4367        }
4368
4369        fragment_start_x
4370    }
4371
4372    pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
4373        let mut fragment_start_x = Pixels::ZERO;
4374        let mut fragment_start_index = 0;
4375
4376        for fragment in &self.fragments {
4377            match fragment {
4378                LineFragment::Text(shaped_line) => {
4379                    let fragment_end_x = fragment_start_x + shaped_line.width;
4380                    if x < fragment_end_x {
4381                        return Some(
4382                            fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
4383                        );
4384                    }
4385                    fragment_start_x = fragment_end_x;
4386                    fragment_start_index += shaped_line.len;
4387                }
4388                LineFragment::Element { len, size, .. } => {
4389                    let fragment_end_x = fragment_start_x + size.width;
4390                    if x < fragment_end_x {
4391                        return Some(fragment_start_index);
4392                    }
4393                    fragment_start_index += len;
4394                    fragment_start_x = fragment_end_x;
4395                }
4396            }
4397        }
4398
4399        None
4400    }
4401
4402    pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
4403        let mut fragment_start_index = 0;
4404
4405        for fragment in &self.fragments {
4406            match fragment {
4407                LineFragment::Text(shaped_line) => {
4408                    let fragment_end_index = fragment_start_index + shaped_line.len;
4409                    if index < fragment_end_index {
4410                        return shaped_line.font_id_for_index(index - fragment_start_index);
4411                    }
4412                    fragment_start_index = fragment_end_index;
4413                }
4414                LineFragment::Element { len, .. } => {
4415                    let fragment_end_index = fragment_start_index + len;
4416                    if index < fragment_end_index {
4417                        return None;
4418                    }
4419                    fragment_start_index = fragment_end_index;
4420                }
4421            }
4422        }
4423
4424        None
4425    }
4426}
4427
4428#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4429enum Invisible {
4430    /// A tab character
4431    ///
4432    /// A tab character is internally represented by spaces (configured by the user's tab width)
4433    /// aligned to the nearest column, so it's necessary to store the start and end offset for
4434    /// adjacency checks.
4435    Tab {
4436        line_start_offset: usize,
4437        line_end_offset: usize,
4438    },
4439    Whitespace {
4440        line_offset: usize,
4441    },
4442}
4443
4444impl EditorElement {
4445    /// Returns the rem size to use when rendering the [`EditorElement`].
4446    ///
4447    /// This allows UI elements to scale based on the `buffer_font_size`.
4448    fn rem_size(&self, cx: &WindowContext) -> Option<Pixels> {
4449        match self.editor.read(cx).mode {
4450            EditorMode::Full => {
4451                let buffer_font_size = self.style.text.font_size;
4452                match buffer_font_size {
4453                    AbsoluteLength::Pixels(pixels) => {
4454                        let rem_size_scale = {
4455                            // Our default UI font size is 14px on a 16px base scale.
4456                            // This means the default UI font size is 0.875rems.
4457                            let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
4458
4459                            // We then determine the delta between a single rem and the default font
4460                            // size scale.
4461                            let default_font_size_delta = 1. - default_font_size_scale;
4462
4463                            // Finally, we add this delta to 1rem to get the scale factor that
4464                            // should be used to scale up the UI.
4465                            1. + default_font_size_delta
4466                        };
4467
4468                        Some(pixels * rem_size_scale)
4469                    }
4470                    AbsoluteLength::Rems(rems) => {
4471                        Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
4472                    }
4473                }
4474            }
4475            // We currently use single-line and auto-height editors in UI contexts,
4476            // so we don't want to scale everything with the buffer font size, as it
4477            // ends up looking off.
4478            EditorMode::SingleLine | EditorMode::AutoHeight { .. } => None,
4479        }
4480    }
4481}
4482
4483impl Element for EditorElement {
4484    type RequestLayoutState = ();
4485    type PrepaintState = EditorLayout;
4486
4487    fn id(&self) -> Option<ElementId> {
4488        None
4489    }
4490
4491    fn request_layout(
4492        &mut self,
4493        _: Option<&GlobalElementId>,
4494        cx: &mut WindowContext,
4495    ) -> (gpui::LayoutId, ()) {
4496        let rem_size = self.rem_size(cx);
4497        cx.with_rem_size(rem_size, |cx| {
4498            self.editor.update(cx, |editor, cx| {
4499                editor.set_style(self.style.clone(), cx);
4500
4501                let layout_id = match editor.mode {
4502                    EditorMode::SingleLine => {
4503                        let rem_size = cx.rem_size();
4504                        let mut style = Style::default();
4505                        style.size.width = relative(1.).into();
4506                        style.size.height = self.style.text.line_height_in_pixels(rem_size).into();
4507                        cx.request_layout(style, None)
4508                    }
4509                    EditorMode::AutoHeight { max_lines } => {
4510                        let editor_handle = cx.view().clone();
4511                        let max_line_number_width =
4512                            self.max_line_number_width(&editor.snapshot(cx), cx);
4513                        cx.request_measured_layout(
4514                            Style::default(),
4515                            move |known_dimensions, available_space, cx| {
4516                                editor_handle
4517                                    .update(cx, |editor, cx| {
4518                                        compute_auto_height_layout(
4519                                            editor,
4520                                            max_lines,
4521                                            max_line_number_width,
4522                                            known_dimensions,
4523                                            available_space.width,
4524                                            cx,
4525                                        )
4526                                    })
4527                                    .unwrap_or_default()
4528                            },
4529                        )
4530                    }
4531                    EditorMode::Full => {
4532                        let mut style = Style::default();
4533                        style.size.width = relative(1.).into();
4534                        style.size.height = relative(1.).into();
4535                        cx.request_layout(style, None)
4536                    }
4537                };
4538
4539                (layout_id, ())
4540            })
4541        })
4542    }
4543
4544    fn prepaint(
4545        &mut self,
4546        _: Option<&GlobalElementId>,
4547        bounds: Bounds<Pixels>,
4548        _: &mut Self::RequestLayoutState,
4549        cx: &mut WindowContext,
4550    ) -> Self::PrepaintState {
4551        let text_style = TextStyleRefinement {
4552            font_size: Some(self.style.text.font_size),
4553            line_height: Some(self.style.text.line_height),
4554            ..Default::default()
4555        };
4556        cx.set_view_id(self.editor.entity_id());
4557
4558        let rem_size = self.rem_size(cx);
4559        cx.with_rem_size(rem_size, |cx| {
4560            cx.with_text_style(Some(text_style), |cx| {
4561                cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
4562                    let mut snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
4563                    let style = self.style.clone();
4564
4565                    let font_id = cx.text_system().resolve_font(&style.text.font());
4566                    let font_size = style.text.font_size.to_pixels(cx.rem_size());
4567                    let line_height = style.text.line_height_in_pixels(cx.rem_size());
4568                    let em_width = cx
4569                        .text_system()
4570                        .typographic_bounds(font_id, font_size, 'm')
4571                        .unwrap()
4572                        .size
4573                        .width;
4574                    let em_advance = cx
4575                        .text_system()
4576                        .advance(font_id, font_size, 'm')
4577                        .unwrap()
4578                        .width;
4579
4580                    let gutter_dimensions = snapshot.gutter_dimensions(
4581                        font_id,
4582                        font_size,
4583                        em_width,
4584                        self.max_line_number_width(&snapshot, cx),
4585                        cx,
4586                    );
4587                    let text_width = bounds.size.width - gutter_dimensions.width;
4588
4589                    let right_margin = if snapshot.mode == EditorMode::Full {
4590                        EditorElement::SCROLLBAR_WIDTH
4591                    } else {
4592                        px(0.)
4593                    };
4594                    let overscroll = size(em_width + right_margin, px(0.));
4595
4596                    snapshot = self.editor.update(cx, |editor, cx| {
4597                        editor.last_bounds = Some(bounds);
4598                        editor.gutter_dimensions = gutter_dimensions;
4599                        editor.set_visible_line_count(bounds.size.height / line_height, cx);
4600
4601                        let editor_width =
4602                            text_width - gutter_dimensions.margin - overscroll.width - em_width;
4603                        let wrap_width = match editor.soft_wrap_mode(cx) {
4604                            SoftWrap::None => None,
4605                            SoftWrap::PreferLine => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
4606                            SoftWrap::EditorWidth => Some(editor_width),
4607                            SoftWrap::Column(column) => {
4608                                Some(editor_width.min(column as f32 * em_advance))
4609                            }
4610                        };
4611
4612                        if editor.set_wrap_width(wrap_width, cx) {
4613                            editor.snapshot(cx)
4614                        } else {
4615                            snapshot
4616                        }
4617                    });
4618
4619                    let wrap_guides = self
4620                        .editor
4621                        .read(cx)
4622                        .wrap_guides(cx)
4623                        .iter()
4624                        .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
4625                        .collect::<SmallVec<[_; 2]>>();
4626
4627                    let hitbox = cx.insert_hitbox(bounds, false);
4628                    let gutter_hitbox = cx.insert_hitbox(
4629                        Bounds {
4630                            origin: bounds.origin,
4631                            size: size(gutter_dimensions.width, bounds.size.height),
4632                        },
4633                        false,
4634                    );
4635                    let text_hitbox = cx.insert_hitbox(
4636                        Bounds {
4637                            origin: gutter_hitbox.upper_right(),
4638                            size: size(text_width, bounds.size.height),
4639                        },
4640                        false,
4641                    );
4642                    // Offset the content_bounds from the text_bounds by the gutter margin (which
4643                    // is roughly half a character wide) to make hit testing work more like how we want.
4644                    let content_origin =
4645                        text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
4646
4647                    let height_in_lines = bounds.size.height / line_height;
4648                    let max_scroll_top = if matches!(snapshot.mode, EditorMode::AutoHeight { .. }) {
4649                        (snapshot.max_point().row().as_f32() - height_in_lines + 1.).max(0.)
4650                    } else {
4651                        let settings = EditorSettings::get_global(cx);
4652                        let max_row = snapshot.max_point().row().as_f32();
4653                        match settings.scroll_beyond_last_line {
4654                            ScrollBeyondLastLine::OnePage => max_row,
4655                            ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.0).max(0.0),
4656                            ScrollBeyondLastLine::VerticalScrollMargin => {
4657                                (max_row - height_in_lines + 1.0 + settings.vertical_scroll_margin)
4658                                    .max(0.0)
4659                            }
4660                        }
4661                    };
4662
4663                    let mut autoscroll_containing_element = false;
4664                    let mut autoscroll_horizontally = false;
4665                    self.editor.update(cx, |editor, cx| {
4666                        autoscroll_containing_element =
4667                            editor.autoscroll_requested() || editor.has_pending_selection();
4668                        autoscroll_horizontally =
4669                            editor.autoscroll_vertically(bounds, line_height, max_scroll_top, cx);
4670                        snapshot = editor.snapshot(cx);
4671                    });
4672
4673                    let mut scroll_position = snapshot.scroll_position();
4674                    // The scroll position is a fractional point, the whole number of which represents
4675                    // the top of the window in terms of display rows.
4676                    let start_row = DisplayRow(scroll_position.y as u32);
4677                    let max_row = snapshot.max_point().row();
4678                    let end_row = cmp::min(
4679                        (scroll_position.y + height_in_lines).ceil() as u32,
4680                        max_row.next_row().0,
4681                    );
4682                    let end_row = DisplayRow(end_row);
4683
4684                    let buffer_rows = snapshot
4685                        .buffer_rows(start_row)
4686                        .take((start_row..end_row).len())
4687                        .collect::<Vec<_>>();
4688
4689                    let start_anchor = if start_row == Default::default() {
4690                        Anchor::min()
4691                    } else {
4692                        snapshot.buffer_snapshot.anchor_before(
4693                            DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
4694                        )
4695                    };
4696                    let end_anchor = if end_row > max_row {
4697                        Anchor::max()
4698                    } else {
4699                        snapshot.buffer_snapshot.anchor_before(
4700                            DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
4701                        )
4702                    };
4703
4704                    let highlighted_rows = self
4705                        .editor
4706                        .update(cx, |editor, cx| editor.highlighted_display_rows(cx));
4707                    let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
4708                        start_anchor..end_anchor,
4709                        &snapshot.display_snapshot,
4710                        cx.theme().colors(),
4711                    );
4712                    let highlighted_gutter_ranges =
4713                        self.editor.read(cx).gutter_highlights_in_range(
4714                            start_anchor..end_anchor,
4715                            &snapshot.display_snapshot,
4716                            cx,
4717                        );
4718
4719                    let redacted_ranges = self.editor.read(cx).redacted_ranges(
4720                        start_anchor..end_anchor,
4721                        &snapshot.display_snapshot,
4722                        cx,
4723                    );
4724
4725                    let (selections, active_rows, newest_selection_head) = self.layout_selections(
4726                        start_anchor,
4727                        end_anchor,
4728                        &snapshot,
4729                        start_row,
4730                        end_row,
4731                        cx,
4732                    );
4733
4734                    let line_numbers = self.layout_line_numbers(
4735                        start_row..end_row,
4736                        buffer_rows.iter().copied(),
4737                        &active_rows,
4738                        newest_selection_head,
4739                        &snapshot,
4740                        cx,
4741                    );
4742
4743                    let mut gutter_fold_toggles =
4744                        cx.with_element_namespace("gutter_fold_toggles", |cx| {
4745                            self.layout_gutter_fold_toggles(
4746                                start_row..end_row,
4747                                buffer_rows.iter().copied(),
4748                                &active_rows,
4749                                &snapshot,
4750                                cx,
4751                            )
4752                        });
4753                    let crease_trailers = cx.with_element_namespace("crease_trailers", |cx| {
4754                        self.layout_crease_trailers(buffer_rows.iter().copied(), &snapshot, cx)
4755                    });
4756
4757                    let display_hunks = self.layout_git_gutters(
4758                        line_height,
4759                        &gutter_hitbox,
4760                        start_row..end_row,
4761                        &snapshot,
4762                        cx,
4763                    );
4764
4765                    let mut max_visible_line_width = Pixels::ZERO;
4766                    let mut line_layouts =
4767                        self.layout_lines(start_row..end_row, &line_numbers, &snapshot, cx);
4768                    for line_with_invisibles in &line_layouts {
4769                        if line_with_invisibles.width > max_visible_line_width {
4770                            max_visible_line_width = line_with_invisibles.width;
4771                        }
4772                    }
4773
4774                    let longest_line_width =
4775                        layout_line(snapshot.longest_row(), &snapshot, &style, cx).width;
4776                    let mut scroll_width =
4777                        longest_line_width.max(max_visible_line_width) + overscroll.width;
4778
4779                    let mut blocks = cx.with_element_namespace("blocks", |cx| {
4780                        self.build_blocks(
4781                            start_row..end_row,
4782                            &snapshot,
4783                            &hitbox,
4784                            &text_hitbox,
4785                            &mut scroll_width,
4786                            &gutter_dimensions,
4787                            em_width,
4788                            gutter_dimensions.full_width(),
4789                            line_height,
4790                            &line_layouts,
4791                            cx,
4792                        )
4793                    });
4794
4795                    let scroll_pixel_position = point(
4796                        scroll_position.x * em_width,
4797                        scroll_position.y * line_height,
4798                    );
4799
4800                    let start_buffer_row =
4801                        MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
4802                    let end_buffer_row =
4803                        MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
4804
4805                    let indent_guides = self.layout_indent_guides(
4806                        content_origin,
4807                        text_hitbox.origin,
4808                        start_buffer_row..end_buffer_row,
4809                        scroll_pixel_position,
4810                        line_height,
4811                        &snapshot,
4812                        cx,
4813                    );
4814
4815                    let crease_trailers = cx.with_element_namespace("crease_trailers", |cx| {
4816                        self.prepaint_crease_trailers(
4817                            crease_trailers,
4818                            &line_layouts,
4819                            line_height,
4820                            content_origin,
4821                            scroll_pixel_position,
4822                            em_width,
4823                            cx,
4824                        )
4825                    });
4826
4827                    let mut inline_blame = None;
4828                    if let Some(newest_selection_head) = newest_selection_head {
4829                        let display_row = newest_selection_head.row();
4830                        if (start_row..end_row).contains(&display_row) {
4831                            let line_ix = display_row.minus(start_row) as usize;
4832                            let line_layout = &line_layouts[line_ix];
4833                            let crease_trailer_layout = crease_trailers[line_ix].as_ref();
4834                            inline_blame = self.layout_inline_blame(
4835                                display_row,
4836                                &snapshot.display_snapshot,
4837                                line_layout,
4838                                crease_trailer_layout,
4839                                em_width,
4840                                content_origin,
4841                                scroll_pixel_position,
4842                                line_height,
4843                                cx,
4844                            );
4845                        }
4846                    }
4847
4848                    let blamed_display_rows = self.layout_blame_entries(
4849                        buffer_rows.into_iter(),
4850                        em_width,
4851                        scroll_position,
4852                        line_height,
4853                        &gutter_hitbox,
4854                        gutter_dimensions.git_blame_entries_width,
4855                        cx,
4856                    );
4857
4858                    let scroll_max = point(
4859                        ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
4860                        max_scroll_top,
4861                    );
4862
4863                    self.editor.update(cx, |editor, cx| {
4864                        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
4865
4866                        let autoscrolled = if autoscroll_horizontally {
4867                            editor.autoscroll_horizontally(
4868                                start_row,
4869                                text_hitbox.size.width,
4870                                scroll_width,
4871                                em_width,
4872                                &line_layouts,
4873                                cx,
4874                            )
4875                        } else {
4876                            false
4877                        };
4878
4879                        if clamped || autoscrolled {
4880                            snapshot = editor.snapshot(cx);
4881                            scroll_position = snapshot.scroll_position();
4882                        }
4883                    });
4884
4885                    let line_elements = self.prepaint_lines(
4886                        start_row,
4887                        &mut line_layouts,
4888                        line_height,
4889                        scroll_pixel_position,
4890                        content_origin,
4891                        cx,
4892                    );
4893
4894                    cx.with_element_namespace("blocks", |cx| {
4895                        self.layout_blocks(
4896                            &mut blocks,
4897                            &hitbox,
4898                            line_height,
4899                            scroll_pixel_position,
4900                            cx,
4901                        );
4902                    });
4903
4904                    let cursors = self.collect_cursors(&snapshot, cx);
4905                    let visible_row_range = start_row..end_row;
4906                    let non_visible_cursors = cursors
4907                        .iter()
4908                        .any(move |c| !visible_row_range.contains(&c.0.row()));
4909
4910                    let visible_cursors = self.layout_visible_cursors(
4911                        &snapshot,
4912                        &selections,
4913                        start_row..end_row,
4914                        &line_layouts,
4915                        &text_hitbox,
4916                        content_origin,
4917                        scroll_position,
4918                        scroll_pixel_position,
4919                        line_height,
4920                        em_width,
4921                        autoscroll_containing_element,
4922                        cx,
4923                    );
4924
4925                    let scrollbar_layout = self.layout_scrollbar(
4926                        &snapshot,
4927                        bounds,
4928                        scroll_position,
4929                        height_in_lines,
4930                        non_visible_cursors,
4931                        cx,
4932                    );
4933
4934                    let gutter_settings = EditorSettings::get_global(cx).gutter;
4935
4936                    let mut _context_menu_visible = false;
4937                    let mut code_actions_indicator = None;
4938                    if let Some(newest_selection_head) = newest_selection_head {
4939                        if (start_row..end_row).contains(&newest_selection_head.row()) {
4940                            _context_menu_visible = self.layout_context_menu(
4941                                line_height,
4942                                &hitbox,
4943                                &text_hitbox,
4944                                content_origin,
4945                                start_row,
4946                                scroll_pixel_position,
4947                                &line_layouts,
4948                                newest_selection_head,
4949                                gutter_dimensions.width - gutter_dimensions.left_padding,
4950                                cx,
4951                            );
4952
4953                            let show_code_actions = snapshot
4954                                .show_code_actions
4955                                .unwrap_or_else(|| gutter_settings.code_actions);
4956                            if show_code_actions {
4957                                let newest_selection_point =
4958                                    newest_selection_head.to_point(&snapshot.display_snapshot);
4959                                let buffer = snapshot.buffer_snapshot.buffer_line_for_row(
4960                                    MultiBufferRow(newest_selection_point.row),
4961                                );
4962                                if let Some((buffer, range)) = buffer {
4963                                    let buffer_id = buffer.remote_id();
4964                                    let row = range.start.row;
4965                                    let has_test_indicator =
4966                                        self.editor.read(cx).tasks.contains_key(&(buffer_id, row));
4967
4968                                    if !has_test_indicator {
4969                                        code_actions_indicator = self
4970                                            .layout_code_actions_indicator(
4971                                                line_height,
4972                                                newest_selection_head,
4973                                                scroll_pixel_position,
4974                                                &gutter_dimensions,
4975                                                &gutter_hitbox,
4976                                                cx,
4977                                            );
4978                                    }
4979                                }
4980                            }
4981                        }
4982                    }
4983
4984                    let test_indicators = if gutter_settings.runnables {
4985                        self.layout_run_indicators(
4986                            line_height,
4987                            scroll_pixel_position,
4988                            &gutter_dimensions,
4989                            &gutter_hitbox,
4990                            &snapshot,
4991                            cx,
4992                        )
4993                    } else {
4994                        vec![]
4995                    };
4996
4997                    if !cx.has_active_drag() {
4998                        self.layout_hover_popovers(
4999                            &snapshot,
5000                            &hitbox,
5001                            &text_hitbox,
5002                            start_row..end_row,
5003                            content_origin,
5004                            scroll_pixel_position,
5005                            &line_layouts,
5006                            line_height,
5007                            em_width,
5008                            cx,
5009                        );
5010                    }
5011
5012                    let mouse_context_menu = self.layout_mouse_context_menu(cx);
5013
5014                    cx.with_element_namespace("gutter_fold_toggles", |cx| {
5015                        self.prepaint_gutter_fold_toggles(
5016                            &mut gutter_fold_toggles,
5017                            line_height,
5018                            &gutter_dimensions,
5019                            gutter_settings,
5020                            scroll_pixel_position,
5021                            &gutter_hitbox,
5022                            cx,
5023                        )
5024                    });
5025
5026                    let invisible_symbol_font_size = font_size / 2.;
5027                    let tab_invisible = cx
5028                        .text_system()
5029                        .shape_line(
5030                            "".into(),
5031                            invisible_symbol_font_size,
5032                            &[TextRun {
5033                                len: "".len(),
5034                                font: self.style.text.font(),
5035                                color: cx.theme().colors().editor_invisible,
5036                                background_color: None,
5037                                underline: None,
5038                                strikethrough: None,
5039                            }],
5040                        )
5041                        .unwrap();
5042                    let space_invisible = cx
5043                        .text_system()
5044                        .shape_line(
5045                            "".into(),
5046                            invisible_symbol_font_size,
5047                            &[TextRun {
5048                                len: "".len(),
5049                                font: self.style.text.font(),
5050                                color: cx.theme().colors().editor_invisible,
5051                                background_color: None,
5052                                underline: None,
5053                                strikethrough: None,
5054                            }],
5055                        )
5056                        .unwrap();
5057
5058                    EditorLayout {
5059                        mode: snapshot.mode,
5060                        position_map: Arc::new(PositionMap {
5061                            size: bounds.size,
5062                            scroll_pixel_position,
5063                            scroll_max,
5064                            line_layouts,
5065                            line_height,
5066                            em_width,
5067                            em_advance,
5068                            snapshot,
5069                        }),
5070                        visible_display_row_range: start_row..end_row,
5071                        wrap_guides,
5072                        indent_guides,
5073                        hitbox,
5074                        text_hitbox,
5075                        gutter_hitbox,
5076                        gutter_dimensions,
5077                        content_origin,
5078                        scrollbar_layout,
5079                        active_rows,
5080                        highlighted_rows,
5081                        highlighted_ranges,
5082                        highlighted_gutter_ranges,
5083                        redacted_ranges,
5084                        line_elements,
5085                        line_numbers,
5086                        display_hunks,
5087                        blamed_display_rows,
5088                        inline_blame,
5089                        blocks,
5090                        cursors,
5091                        visible_cursors,
5092                        selections,
5093                        mouse_context_menu,
5094                        test_indicators,
5095                        code_actions_indicator,
5096                        gutter_fold_toggles,
5097                        crease_trailers,
5098                        tab_invisible,
5099                        space_invisible,
5100                    }
5101                })
5102            })
5103        })
5104    }
5105
5106    fn paint(
5107        &mut self,
5108        _: Option<&GlobalElementId>,
5109        bounds: Bounds<gpui::Pixels>,
5110        _: &mut Self::RequestLayoutState,
5111        layout: &mut Self::PrepaintState,
5112        cx: &mut WindowContext,
5113    ) {
5114        let focus_handle = self.editor.focus_handle(cx);
5115        let key_context = self.editor.read(cx).key_context(cx);
5116        cx.set_focus_handle(&focus_handle);
5117        cx.set_key_context(key_context);
5118        cx.handle_input(
5119            &focus_handle,
5120            ElementInputHandler::new(bounds, self.editor.clone()),
5121        );
5122        self.register_actions(cx);
5123        self.register_key_listeners(cx, layout);
5124
5125        let text_style = TextStyleRefinement {
5126            font_size: Some(self.style.text.font_size),
5127            line_height: Some(self.style.text.line_height),
5128            ..Default::default()
5129        };
5130        let mouse_position = cx.mouse_position();
5131        let hovered_hunk = layout
5132            .display_hunks
5133            .iter()
5134            .find_map(|(hunk, hunk_hitbox)| match hunk {
5135                DisplayDiffHunk::Folded { .. } => None,
5136                DisplayDiffHunk::Unfolded {
5137                    diff_base_byte_range,
5138                    multi_buffer_range,
5139                    status,
5140                    ..
5141                } => {
5142                    if hunk_hitbox
5143                        .as_ref()
5144                        .map(|hitbox| hitbox.contains(&mouse_position))
5145                        .unwrap_or(false)
5146                    {
5147                        Some(HunkToExpand {
5148                            status: *status,
5149                            multi_buffer_range: multi_buffer_range.clone(),
5150                            diff_base_byte_range: diff_base_byte_range.clone(),
5151                        })
5152                    } else {
5153                        None
5154                    }
5155                }
5156            });
5157        let rem_size = self.rem_size(cx);
5158        cx.with_rem_size(rem_size, |cx| {
5159            cx.with_text_style(Some(text_style), |cx| {
5160                cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
5161                    self.paint_mouse_listeners(layout, hovered_hunk, cx);
5162                    self.paint_background(layout, cx);
5163                    self.paint_indent_guides(layout, cx);
5164
5165                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
5166                        self.paint_blamed_display_rows(layout, cx);
5167                        self.paint_line_numbers(layout, cx);
5168                    }
5169
5170                    self.paint_text(layout, cx);
5171
5172                    if !layout.blocks.is_empty() {
5173                        cx.with_element_namespace("blocks", |cx| {
5174                            self.paint_blocks(layout, cx);
5175                        });
5176                    }
5177
5178                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
5179                        self.paint_gutter_highlights(layout, cx);
5180                        self.paint_gutter_indicators(layout, cx);
5181                    }
5182
5183                    self.paint_scrollbar(layout, cx);
5184                    self.paint_mouse_context_menu(layout, cx);
5185                });
5186            })
5187        })
5188    }
5189}
5190
5191impl IntoElement for EditorElement {
5192    type Element = Self;
5193
5194    fn into_element(self) -> Self::Element {
5195        self
5196    }
5197}
5198
5199pub struct EditorLayout {
5200    position_map: Arc<PositionMap>,
5201    hitbox: Hitbox,
5202    text_hitbox: Hitbox,
5203    gutter_hitbox: Hitbox,
5204    gutter_dimensions: GutterDimensions,
5205    content_origin: gpui::Point<Pixels>,
5206    scrollbar_layout: Option<ScrollbarLayout>,
5207    mode: EditorMode,
5208    wrap_guides: SmallVec<[(Pixels, bool); 2]>,
5209    indent_guides: Option<Vec<IndentGuideLayout>>,
5210    visible_display_row_range: Range<DisplayRow>,
5211    active_rows: BTreeMap<DisplayRow, bool>,
5212    highlighted_rows: BTreeMap<DisplayRow, Hsla>,
5213    line_elements: SmallVec<[AnyElement; 1]>,
5214    line_numbers: Vec<Option<ShapedLine>>,
5215    display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
5216    blamed_display_rows: Option<Vec<AnyElement>>,
5217    inline_blame: Option<AnyElement>,
5218    blocks: Vec<BlockLayout>,
5219    highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
5220    highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
5221    redacted_ranges: Vec<Range<DisplayPoint>>,
5222    cursors: Vec<(DisplayPoint, Hsla)>,
5223    visible_cursors: Vec<CursorLayout>,
5224    selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
5225    code_actions_indicator: Option<AnyElement>,
5226    test_indicators: Vec<AnyElement>,
5227    gutter_fold_toggles: Vec<Option<AnyElement>>,
5228    crease_trailers: Vec<Option<CreaseTrailerLayout>>,
5229    mouse_context_menu: Option<AnyElement>,
5230    tab_invisible: ShapedLine,
5231    space_invisible: ShapedLine,
5232}
5233
5234impl EditorLayout {
5235    fn line_end_overshoot(&self) -> Pixels {
5236        0.15 * self.position_map.line_height
5237    }
5238}
5239
5240struct ColoredRange<T> {
5241    start: T,
5242    end: T,
5243    color: Hsla,
5244}
5245
5246#[derive(Clone)]
5247struct ScrollbarLayout {
5248    hitbox: Hitbox,
5249    visible_row_range: Range<f32>,
5250    visible: bool,
5251    row_height: Pixels,
5252    thumb_height: Pixels,
5253}
5254
5255impl ScrollbarLayout {
5256    const BORDER_WIDTH: Pixels = px(1.0);
5257    const LINE_MARKER_HEIGHT: Pixels = px(2.0);
5258    const MIN_MARKER_HEIGHT: Pixels = px(5.0);
5259    const MIN_THUMB_HEIGHT: Pixels = px(20.0);
5260
5261    fn thumb_bounds(&self) -> Bounds<Pixels> {
5262        let thumb_top = self.y_for_row(self.visible_row_range.start);
5263        let thumb_bottom = thumb_top + self.thumb_height;
5264        Bounds::from_corners(
5265            point(self.hitbox.left(), thumb_top),
5266            point(self.hitbox.right(), thumb_bottom),
5267        )
5268    }
5269
5270    fn y_for_row(&self, row: f32) -> Pixels {
5271        self.hitbox.top() + row * self.row_height
5272    }
5273
5274    fn marker_quads_for_ranges(
5275        &self,
5276        row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
5277        column: Option<usize>,
5278    ) -> Vec<PaintQuad> {
5279        struct MinMax {
5280            min: Pixels,
5281            max: Pixels,
5282        }
5283        let (x_range, height_limit) = if let Some(column) = column {
5284            let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
5285            let start = Self::BORDER_WIDTH + (column as f32 * column_width);
5286            let end = start + column_width;
5287            (
5288                Range { start, end },
5289                MinMax {
5290                    min: Self::MIN_MARKER_HEIGHT,
5291                    max: px(f32::MAX),
5292                },
5293            )
5294        } else {
5295            (
5296                Range {
5297                    start: Self::BORDER_WIDTH,
5298                    end: self.hitbox.size.width,
5299                },
5300                MinMax {
5301                    min: Self::LINE_MARKER_HEIGHT,
5302                    max: Self::LINE_MARKER_HEIGHT,
5303                },
5304            )
5305        };
5306
5307        let row_to_y = |row: DisplayRow| row.as_f32() * self.row_height;
5308        let mut pixel_ranges = row_ranges
5309            .into_iter()
5310            .map(|range| {
5311                let start_y = row_to_y(range.start);
5312                let end_y = row_to_y(range.end)
5313                    + self.row_height.max(height_limit.min).min(height_limit.max);
5314                ColoredRange {
5315                    start: start_y,
5316                    end: end_y,
5317                    color: range.color,
5318                }
5319            })
5320            .peekable();
5321
5322        let mut quads = Vec::new();
5323        while let Some(mut pixel_range) = pixel_ranges.next() {
5324            while let Some(next_pixel_range) = pixel_ranges.peek() {
5325                if pixel_range.end >= next_pixel_range.start - px(1.0)
5326                    && pixel_range.color == next_pixel_range.color
5327                {
5328                    pixel_range.end = next_pixel_range.end.max(pixel_range.end);
5329                    pixel_ranges.next();
5330                } else {
5331                    break;
5332                }
5333            }
5334
5335            let bounds = Bounds::from_corners(
5336                point(x_range.start, pixel_range.start),
5337                point(x_range.end, pixel_range.end),
5338            );
5339            quads.push(quad(
5340                bounds,
5341                Corners::default(),
5342                pixel_range.color,
5343                Edges::default(),
5344                Hsla::transparent_black(),
5345            ));
5346        }
5347
5348        quads
5349    }
5350}
5351
5352struct CreaseTrailerLayout {
5353    element: AnyElement,
5354    bounds: Bounds<Pixels>,
5355}
5356
5357struct PositionMap {
5358    size: Size<Pixels>,
5359    line_height: Pixels,
5360    scroll_pixel_position: gpui::Point<Pixels>,
5361    scroll_max: gpui::Point<f32>,
5362    em_width: Pixels,
5363    em_advance: Pixels,
5364    line_layouts: Vec<LineWithInvisibles>,
5365    snapshot: EditorSnapshot,
5366}
5367
5368#[derive(Debug, Copy, Clone)]
5369pub struct PointForPosition {
5370    pub previous_valid: DisplayPoint,
5371    pub next_valid: DisplayPoint,
5372    pub exact_unclipped: DisplayPoint,
5373    pub column_overshoot_after_line_end: u32,
5374}
5375
5376impl PointForPosition {
5377    pub fn as_valid(&self) -> Option<DisplayPoint> {
5378        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
5379            Some(self.previous_valid)
5380        } else {
5381            None
5382        }
5383    }
5384}
5385
5386impl PositionMap {
5387    fn point_for_position(
5388        &self,
5389        text_bounds: Bounds<Pixels>,
5390        position: gpui::Point<Pixels>,
5391    ) -> PointForPosition {
5392        let scroll_position = self.snapshot.scroll_position();
5393        let position = position - text_bounds.origin;
5394        let y = position.y.max(px(0.)).min(self.size.height);
5395        let x = position.x + (scroll_position.x * self.em_width);
5396        let row = ((y / self.line_height) + scroll_position.y) as u32;
5397
5398        let (column, x_overshoot_after_line_end) = if let Some(line) = self
5399            .line_layouts
5400            .get(row as usize - scroll_position.y as usize)
5401        {
5402            if let Some(ix) = line.index_for_x(x) {
5403                (ix as u32, px(0.))
5404            } else {
5405                (line.len as u32, px(0.).max(x - line.width))
5406            }
5407        } else {
5408            (0, x)
5409        };
5410
5411        let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
5412        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
5413        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
5414
5415        let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
5416        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
5417        PointForPosition {
5418            previous_valid,
5419            next_valid,
5420            exact_unclipped,
5421            column_overshoot_after_line_end,
5422        }
5423    }
5424}
5425
5426struct BlockLayout {
5427    row: DisplayRow,
5428    element: AnyElement,
5429    available_space: Size<AvailableSpace>,
5430    style: BlockStyle,
5431}
5432
5433fn layout_line(
5434    row: DisplayRow,
5435    snapshot: &EditorSnapshot,
5436    style: &EditorStyle,
5437    cx: &mut WindowContext,
5438) -> LineWithInvisibles {
5439    let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
5440    LineWithInvisibles::from_chunks(chunks, &style.text, MAX_LINE_LEN, 1, &[], snapshot.mode, cx)
5441        .pop()
5442        .unwrap()
5443}
5444
5445#[derive(Debug)]
5446pub struct IndentGuideLayout {
5447    origin: gpui::Point<Pixels>,
5448    length: Pixels,
5449    single_indent_width: Pixels,
5450    depth: u32,
5451    active: bool,
5452    settings: IndentGuideSettings,
5453}
5454
5455pub struct CursorLayout {
5456    origin: gpui::Point<Pixels>,
5457    block_width: Pixels,
5458    line_height: Pixels,
5459    color: Hsla,
5460    shape: CursorShape,
5461    block_text: Option<ShapedLine>,
5462    cursor_name: Option<AnyElement>,
5463}
5464
5465#[derive(Debug)]
5466pub struct CursorName {
5467    string: SharedString,
5468    color: Hsla,
5469    is_top_row: bool,
5470}
5471
5472impl CursorLayout {
5473    pub fn new(
5474        origin: gpui::Point<Pixels>,
5475        block_width: Pixels,
5476        line_height: Pixels,
5477        color: Hsla,
5478        shape: CursorShape,
5479        block_text: Option<ShapedLine>,
5480    ) -> CursorLayout {
5481        CursorLayout {
5482            origin,
5483            block_width,
5484            line_height,
5485            color,
5486            shape,
5487            block_text,
5488            cursor_name: None,
5489        }
5490    }
5491
5492    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
5493        Bounds {
5494            origin: self.origin + origin,
5495            size: size(self.block_width, self.line_height),
5496        }
5497    }
5498
5499    fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
5500        match self.shape {
5501            CursorShape::Bar => Bounds {
5502                origin: self.origin + origin,
5503                size: size(px(2.0), self.line_height),
5504            },
5505            CursorShape::Block | CursorShape::Hollow => Bounds {
5506                origin: self.origin + origin,
5507                size: size(self.block_width, self.line_height),
5508            },
5509            CursorShape::Underscore => Bounds {
5510                origin: self.origin
5511                    + origin
5512                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
5513                size: size(self.block_width, px(2.0)),
5514            },
5515        }
5516    }
5517
5518    pub fn layout(
5519        &mut self,
5520        origin: gpui::Point<Pixels>,
5521        cursor_name: Option<CursorName>,
5522        cx: &mut WindowContext,
5523    ) {
5524        if let Some(cursor_name) = cursor_name {
5525            let bounds = self.bounds(origin);
5526            let text_size = self.line_height / 1.5;
5527
5528            let name_origin = if cursor_name.is_top_row {
5529                point(bounds.right() - px(1.), bounds.top())
5530            } else {
5531                point(bounds.left(), bounds.top() - text_size / 2. - px(1.))
5532            };
5533            let mut name_element = div()
5534                .bg(self.color)
5535                .text_size(text_size)
5536                .px_0p5()
5537                .line_height(text_size + px(2.))
5538                .text_color(cursor_name.color)
5539                .child(cursor_name.string.clone())
5540                .into_any_element();
5541
5542            name_element.prepaint_as_root(
5543                name_origin,
5544                size(AvailableSpace::MinContent, AvailableSpace::MinContent),
5545                cx,
5546            );
5547
5548            self.cursor_name = Some(name_element);
5549        }
5550    }
5551
5552    pub fn paint(&mut self, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
5553        let bounds = self.bounds(origin);
5554
5555        //Draw background or border quad
5556        let cursor = if matches!(self.shape, CursorShape::Hollow) {
5557            outline(bounds, self.color)
5558        } else {
5559            fill(bounds, self.color)
5560        };
5561
5562        if let Some(name) = &mut self.cursor_name {
5563            name.paint(cx);
5564        }
5565
5566        cx.paint_quad(cursor);
5567
5568        if let Some(block_text) = &self.block_text {
5569            block_text
5570                .paint(self.origin + origin, self.line_height, cx)
5571                .log_err();
5572        }
5573    }
5574
5575    pub fn shape(&self) -> CursorShape {
5576        self.shape
5577    }
5578}
5579
5580#[derive(Debug)]
5581pub struct HighlightedRange {
5582    pub start_y: Pixels,
5583    pub line_height: Pixels,
5584    pub lines: Vec<HighlightedRangeLine>,
5585    pub color: Hsla,
5586    pub corner_radius: Pixels,
5587}
5588
5589#[derive(Debug)]
5590pub struct HighlightedRangeLine {
5591    pub start_x: Pixels,
5592    pub end_x: Pixels,
5593}
5594
5595impl HighlightedRange {
5596    pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut WindowContext) {
5597        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
5598            self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
5599            self.paint_lines(
5600                self.start_y + self.line_height,
5601                &self.lines[1..],
5602                bounds,
5603                cx,
5604            );
5605        } else {
5606            self.paint_lines(self.start_y, &self.lines, bounds, cx);
5607        }
5608    }
5609
5610    fn paint_lines(
5611        &self,
5612        start_y: Pixels,
5613        lines: &[HighlightedRangeLine],
5614        _bounds: Bounds<Pixels>,
5615        cx: &mut WindowContext,
5616    ) {
5617        if lines.is_empty() {
5618            return;
5619        }
5620
5621        let first_line = lines.first().unwrap();
5622        let last_line = lines.last().unwrap();
5623
5624        let first_top_left = point(first_line.start_x, start_y);
5625        let first_top_right = point(first_line.end_x, start_y);
5626
5627        let curve_height = point(Pixels::ZERO, self.corner_radius);
5628        let curve_width = |start_x: Pixels, end_x: Pixels| {
5629            let max = (end_x - start_x) / 2.;
5630            let width = if max < self.corner_radius {
5631                max
5632            } else {
5633                self.corner_radius
5634            };
5635
5636            point(width, Pixels::ZERO)
5637        };
5638
5639        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
5640        let mut path = gpui::Path::new(first_top_right - top_curve_width);
5641        path.curve_to(first_top_right + curve_height, first_top_right);
5642
5643        let mut iter = lines.iter().enumerate().peekable();
5644        while let Some((ix, line)) = iter.next() {
5645            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
5646
5647            if let Some((_, next_line)) = iter.peek() {
5648                let next_top_right = point(next_line.end_x, bottom_right.y);
5649
5650                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
5651                    Ordering::Equal => {
5652                        path.line_to(bottom_right);
5653                    }
5654                    Ordering::Less => {
5655                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
5656                        path.line_to(bottom_right - curve_height);
5657                        if self.corner_radius > Pixels::ZERO {
5658                            path.curve_to(bottom_right - curve_width, bottom_right);
5659                        }
5660                        path.line_to(next_top_right + curve_width);
5661                        if self.corner_radius > Pixels::ZERO {
5662                            path.curve_to(next_top_right + curve_height, next_top_right);
5663                        }
5664                    }
5665                    Ordering::Greater => {
5666                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
5667                        path.line_to(bottom_right - curve_height);
5668                        if self.corner_radius > Pixels::ZERO {
5669                            path.curve_to(bottom_right + curve_width, bottom_right);
5670                        }
5671                        path.line_to(next_top_right - curve_width);
5672                        if self.corner_radius > Pixels::ZERO {
5673                            path.curve_to(next_top_right + curve_height, next_top_right);
5674                        }
5675                    }
5676                }
5677            } else {
5678                let curve_width = curve_width(line.start_x, line.end_x);
5679                path.line_to(bottom_right - curve_height);
5680                if self.corner_radius > Pixels::ZERO {
5681                    path.curve_to(bottom_right - curve_width, bottom_right);
5682                }
5683
5684                let bottom_left = point(line.start_x, bottom_right.y);
5685                path.line_to(bottom_left + curve_width);
5686                if self.corner_radius > Pixels::ZERO {
5687                    path.curve_to(bottom_left - curve_height, bottom_left);
5688                }
5689            }
5690        }
5691
5692        if first_line.start_x > last_line.start_x {
5693            let curve_width = curve_width(last_line.start_x, first_line.start_x);
5694            let second_top_left = point(last_line.start_x, start_y + self.line_height);
5695            path.line_to(second_top_left + curve_height);
5696            if self.corner_radius > Pixels::ZERO {
5697                path.curve_to(second_top_left + curve_width, second_top_left);
5698            }
5699            let first_bottom_left = point(first_line.start_x, second_top_left.y);
5700            path.line_to(first_bottom_left - curve_width);
5701            if self.corner_radius > Pixels::ZERO {
5702                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
5703            }
5704        }
5705
5706        path.line_to(first_top_left + curve_height);
5707        if self.corner_radius > Pixels::ZERO {
5708            path.curve_to(first_top_left + top_curve_width, first_top_left);
5709        }
5710        path.line_to(first_top_right - top_curve_width);
5711
5712        cx.paint_path(path, self.color);
5713    }
5714}
5715
5716pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
5717    (delta.pow(1.5) / 100.0).into()
5718}
5719
5720fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
5721    (delta.pow(1.2) / 300.0).into()
5722}
5723
5724#[cfg(test)]
5725mod tests {
5726    use super::*;
5727    use crate::{
5728        display_map::{BlockDisposition, BlockProperties},
5729        editor_tests::{init_test, update_test_language_settings},
5730        Editor, MultiBuffer,
5731    };
5732    use gpui::{TestAppContext, VisualTestContext};
5733    use language::language_settings;
5734    use log::info;
5735    use std::num::NonZeroU32;
5736    use ui::Context;
5737    use util::test::sample_text;
5738
5739    #[gpui::test]
5740    fn test_shape_line_numbers(cx: &mut TestAppContext) {
5741        init_test(cx, |_| {});
5742        let window = cx.add_window(|cx| {
5743            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
5744            Editor::new(EditorMode::Full, buffer, None, true, cx)
5745        });
5746
5747        let editor = window.root(cx).unwrap();
5748        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5749        let element = EditorElement::new(&editor, style);
5750        let snapshot = window.update(cx, |editor, cx| editor.snapshot(cx)).unwrap();
5751
5752        let layouts = cx
5753            .update_window(*window, |_, cx| {
5754                element.layout_line_numbers(
5755                    DisplayRow(0)..DisplayRow(6),
5756                    (0..6).map(MultiBufferRow).map(Some),
5757                    &Default::default(),
5758                    Some(DisplayPoint::new(DisplayRow(0), 0)),
5759                    &snapshot,
5760                    cx,
5761                )
5762            })
5763            .unwrap();
5764        assert_eq!(layouts.len(), 6);
5765
5766        let relative_rows = window
5767            .update(cx, |editor, cx| {
5768                let snapshot = editor.snapshot(cx);
5769                element.calculate_relative_line_numbers(
5770                    &snapshot,
5771                    &(DisplayRow(0)..DisplayRow(6)),
5772                    Some(DisplayRow(3)),
5773                )
5774            })
5775            .unwrap();
5776        assert_eq!(relative_rows[&DisplayRow(0)], 3);
5777        assert_eq!(relative_rows[&DisplayRow(1)], 2);
5778        assert_eq!(relative_rows[&DisplayRow(2)], 1);
5779        // current line has no relative number
5780        assert_eq!(relative_rows[&DisplayRow(4)], 1);
5781        assert_eq!(relative_rows[&DisplayRow(5)], 2);
5782
5783        // works if cursor is before screen
5784        let relative_rows = window
5785            .update(cx, |editor, cx| {
5786                let snapshot = editor.snapshot(cx);
5787                element.calculate_relative_line_numbers(
5788                    &snapshot,
5789                    &(DisplayRow(3)..DisplayRow(6)),
5790                    Some(DisplayRow(1)),
5791                )
5792            })
5793            .unwrap();
5794        assert_eq!(relative_rows.len(), 3);
5795        assert_eq!(relative_rows[&DisplayRow(3)], 2);
5796        assert_eq!(relative_rows[&DisplayRow(4)], 3);
5797        assert_eq!(relative_rows[&DisplayRow(5)], 4);
5798
5799        // works if cursor is after screen
5800        let relative_rows = window
5801            .update(cx, |editor, cx| {
5802                let snapshot = editor.snapshot(cx);
5803                element.calculate_relative_line_numbers(
5804                    &snapshot,
5805                    &(DisplayRow(0)..DisplayRow(3)),
5806                    Some(DisplayRow(6)),
5807                )
5808            })
5809            .unwrap();
5810        assert_eq!(relative_rows.len(), 3);
5811        assert_eq!(relative_rows[&DisplayRow(0)], 5);
5812        assert_eq!(relative_rows[&DisplayRow(1)], 4);
5813        assert_eq!(relative_rows[&DisplayRow(2)], 3);
5814    }
5815
5816    #[gpui::test]
5817    async fn test_vim_visual_selections(cx: &mut TestAppContext) {
5818        init_test(cx, |_| {});
5819
5820        let window = cx.add_window(|cx| {
5821            let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
5822            Editor::new(EditorMode::Full, buffer, None, true, cx)
5823        });
5824        let cx = &mut VisualTestContext::from_window(*window, cx);
5825        let editor = window.root(cx).unwrap();
5826        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5827
5828        window
5829            .update(cx, |editor, cx| {
5830                editor.cursor_shape = CursorShape::Block;
5831                editor.change_selections(None, cx, |s| {
5832                    s.select_ranges([
5833                        Point::new(0, 0)..Point::new(1, 0),
5834                        Point::new(3, 2)..Point::new(3, 3),
5835                        Point::new(5, 6)..Point::new(6, 0),
5836                    ]);
5837                });
5838            })
5839            .unwrap();
5840
5841        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
5842            EditorElement::new(&editor, style)
5843        });
5844
5845        assert_eq!(state.selections.len(), 1);
5846        let local_selections = &state.selections[0].1;
5847        assert_eq!(local_selections.len(), 3);
5848        // moves cursor back one line
5849        assert_eq!(
5850            local_selections[0].head,
5851            DisplayPoint::new(DisplayRow(0), 6)
5852        );
5853        assert_eq!(
5854            local_selections[0].range,
5855            DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
5856        );
5857
5858        // moves cursor back one column
5859        assert_eq!(
5860            local_selections[1].range,
5861            DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
5862        );
5863        assert_eq!(
5864            local_selections[1].head,
5865            DisplayPoint::new(DisplayRow(3), 2)
5866        );
5867
5868        // leaves cursor on the max point
5869        assert_eq!(
5870            local_selections[2].range,
5871            DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
5872        );
5873        assert_eq!(
5874            local_selections[2].head,
5875            DisplayPoint::new(DisplayRow(6), 0)
5876        );
5877
5878        // active lines does not include 1 (even though the range of the selection does)
5879        assert_eq!(
5880            state.active_rows.keys().cloned().collect::<Vec<_>>(),
5881            vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
5882        );
5883
5884        // multi-buffer support
5885        // in DisplayPoint coordinates, this is what we're dealing with:
5886        //  0: [[file
5887        //  1:   header
5888        //  2:   section]]
5889        //  3: aaaaaa
5890        //  4: bbbbbb
5891        //  5: cccccc
5892        //  6:
5893        //  7: [[footer]]
5894        //  8: [[header]]
5895        //  9: ffffff
5896        // 10: gggggg
5897        // 11: hhhhhh
5898        // 12:
5899        // 13: [[footer]]
5900        // 14: [[file
5901        // 15:   header
5902        // 16:   section]]
5903        // 17: bbbbbb
5904        // 18: cccccc
5905        // 19: dddddd
5906        // 20: [[footer]]
5907        let window = cx.add_window(|cx| {
5908            let buffer = MultiBuffer::build_multi(
5909                [
5910                    (
5911                        &(sample_text(8, 6, 'a') + "\n"),
5912                        vec![
5913                            Point::new(0, 0)..Point::new(3, 0),
5914                            Point::new(4, 0)..Point::new(7, 0),
5915                        ],
5916                    ),
5917                    (
5918                        &(sample_text(8, 6, 'a') + "\n"),
5919                        vec![Point::new(1, 0)..Point::new(3, 0)],
5920                    ),
5921                ],
5922                cx,
5923            );
5924            Editor::new(EditorMode::Full, buffer, None, true, cx)
5925        });
5926        let editor = window.root(cx).unwrap();
5927        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5928        let _state = window.update(cx, |editor, cx| {
5929            editor.cursor_shape = CursorShape::Block;
5930            editor.change_selections(None, cx, |s| {
5931                s.select_display_ranges([
5932                    DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0),
5933                    DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0),
5934                ]);
5935            });
5936        });
5937
5938        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
5939            EditorElement::new(&editor, style)
5940        });
5941        assert_eq!(state.selections.len(), 1);
5942        let local_selections = &state.selections[0].1;
5943        assert_eq!(local_selections.len(), 2);
5944
5945        // moves cursor on excerpt boundary back a line
5946        // and doesn't allow selection to bleed through
5947        assert_eq!(
5948            local_selections[0].range,
5949            DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0)
5950        );
5951        assert_eq!(
5952            local_selections[0].head,
5953            DisplayPoint::new(DisplayRow(6), 0)
5954        );
5955        // moves cursor on buffer boundary back two lines
5956        // and doesn't allow selection to bleed through
5957        assert_eq!(
5958            local_selections[1].range,
5959            DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0)
5960        );
5961        assert_eq!(
5962            local_selections[1].head,
5963            DisplayPoint::new(DisplayRow(12), 0)
5964        );
5965    }
5966
5967    #[gpui::test]
5968    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
5969        init_test(cx, |_| {});
5970
5971        let window = cx.add_window(|cx| {
5972            let buffer = MultiBuffer::build_simple("", cx);
5973            Editor::new(EditorMode::Full, buffer, None, true, cx)
5974        });
5975        let cx = &mut VisualTestContext::from_window(*window, cx);
5976        let editor = window.root(cx).unwrap();
5977        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5978        window
5979            .update(cx, |editor, cx| {
5980                editor.set_placeholder_text("hello", cx);
5981                editor.insert_blocks(
5982                    [BlockProperties {
5983                        style: BlockStyle::Fixed,
5984                        disposition: BlockDisposition::Above,
5985                        height: 3,
5986                        position: Anchor::min(),
5987                        render: Box::new(|_| div().into_any()),
5988                    }],
5989                    None,
5990                    cx,
5991                );
5992
5993                // Blur the editor so that it displays placeholder text.
5994                cx.blur();
5995            })
5996            .unwrap();
5997
5998        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
5999            EditorElement::new(&editor, style)
6000        });
6001        assert_eq!(state.position_map.line_layouts.len(), 4);
6002        assert_eq!(
6003            state
6004                .line_numbers
6005                .iter()
6006                .map(Option::is_some)
6007                .collect::<Vec<_>>(),
6008            &[false, false, false, true]
6009        );
6010    }
6011
6012    #[gpui::test]
6013    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
6014        const TAB_SIZE: u32 = 4;
6015
6016        let input_text = "\t \t|\t| a b";
6017        let expected_invisibles = vec![
6018            Invisible::Tab {
6019                line_start_offset: 0,
6020                line_end_offset: TAB_SIZE as usize,
6021            },
6022            Invisible::Whitespace {
6023                line_offset: TAB_SIZE as usize,
6024            },
6025            Invisible::Tab {
6026                line_start_offset: TAB_SIZE as usize + 1,
6027                line_end_offset: TAB_SIZE as usize * 2,
6028            },
6029            Invisible::Tab {
6030                line_start_offset: TAB_SIZE as usize * 2 + 1,
6031                line_end_offset: TAB_SIZE as usize * 3,
6032            },
6033            Invisible::Whitespace {
6034                line_offset: TAB_SIZE as usize * 3 + 1,
6035            },
6036            Invisible::Whitespace {
6037                line_offset: TAB_SIZE as usize * 3 + 3,
6038            },
6039        ];
6040        assert_eq!(
6041            expected_invisibles.len(),
6042            input_text
6043                .chars()
6044                .filter(|initial_char| initial_char.is_whitespace())
6045                .count(),
6046            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
6047        );
6048
6049        init_test(cx, |s| {
6050            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6051            s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
6052        });
6053
6054        let actual_invisibles =
6055            collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, px(500.0));
6056
6057        assert_eq!(expected_invisibles, actual_invisibles);
6058    }
6059
6060    #[gpui::test]
6061    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
6062        init_test(cx, |s| {
6063            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6064            s.defaults.tab_size = NonZeroU32::new(4);
6065        });
6066
6067        for editor_mode_without_invisibles in [
6068            EditorMode::SingleLine,
6069            EditorMode::AutoHeight { max_lines: 100 },
6070        ] {
6071            let invisibles = collect_invisibles_from_new_editor(
6072                cx,
6073                editor_mode_without_invisibles,
6074                "\t\t\t| | a b",
6075                px(500.0),
6076            );
6077            assert!(invisibles.is_empty(),
6078                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
6079        }
6080    }
6081
6082    #[gpui::test]
6083    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
6084        let tab_size = 4;
6085        let input_text = "a\tbcd     ".repeat(9);
6086        let repeated_invisibles = [
6087            Invisible::Tab {
6088                line_start_offset: 1,
6089                line_end_offset: tab_size as usize,
6090            },
6091            Invisible::Whitespace {
6092                line_offset: tab_size as usize + 3,
6093            },
6094            Invisible::Whitespace {
6095                line_offset: tab_size as usize + 4,
6096            },
6097            Invisible::Whitespace {
6098                line_offset: tab_size as usize + 5,
6099            },
6100            Invisible::Whitespace {
6101                line_offset: tab_size as usize + 6,
6102            },
6103            Invisible::Whitespace {
6104                line_offset: tab_size as usize + 7,
6105            },
6106        ];
6107        let expected_invisibles = std::iter::once(repeated_invisibles)
6108            .cycle()
6109            .take(9)
6110            .flatten()
6111            .collect::<Vec<_>>();
6112        assert_eq!(
6113            expected_invisibles.len(),
6114            input_text
6115                .chars()
6116                .filter(|initial_char| initial_char.is_whitespace())
6117                .count(),
6118            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
6119        );
6120        info!("Expected invisibles: {expected_invisibles:?}");
6121
6122        init_test(cx, |_| {});
6123
6124        // Put the same string with repeating whitespace pattern into editors of various size,
6125        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
6126        let resize_step = 10.0;
6127        let mut editor_width = 200.0;
6128        while editor_width <= 1000.0 {
6129            update_test_language_settings(cx, |s| {
6130                s.defaults.tab_size = NonZeroU32::new(tab_size);
6131                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6132                s.defaults.preferred_line_length = Some(editor_width as u32);
6133                s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
6134            });
6135
6136            let actual_invisibles = collect_invisibles_from_new_editor(
6137                cx,
6138                EditorMode::Full,
6139                &input_text,
6140                px(editor_width),
6141            );
6142
6143            // Whatever the editor size is, ensure it has the same invisible kinds in the same order
6144            // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
6145            let mut i = 0;
6146            for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
6147                i = actual_index;
6148                match expected_invisibles.get(i) {
6149                    Some(expected_invisible) => match (expected_invisible, actual_invisible) {
6150                        (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
6151                        | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
6152                        _ => {
6153                            panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
6154                        }
6155                    },
6156                    None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
6157                }
6158            }
6159            let missing_expected_invisibles = &expected_invisibles[i + 1..];
6160            assert!(
6161                missing_expected_invisibles.is_empty(),
6162                "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
6163            );
6164
6165            editor_width += resize_step;
6166        }
6167    }
6168
6169    fn collect_invisibles_from_new_editor(
6170        cx: &mut TestAppContext,
6171        editor_mode: EditorMode,
6172        input_text: &str,
6173        editor_width: Pixels,
6174    ) -> Vec<Invisible> {
6175        info!(
6176            "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
6177            editor_width.0
6178        );
6179        let window = cx.add_window(|cx| {
6180            let buffer = MultiBuffer::build_simple(&input_text, cx);
6181            Editor::new(editor_mode, buffer, None, true, cx)
6182        });
6183        let cx = &mut VisualTestContext::from_window(*window, cx);
6184        let editor = window.root(cx).unwrap();
6185        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6186        window
6187            .update(cx, |editor, cx| {
6188                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
6189                editor.set_wrap_width(Some(editor_width), cx);
6190            })
6191            .unwrap();
6192        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6193            EditorElement::new(&editor, style)
6194        });
6195        state
6196            .position_map
6197            .line_layouts
6198            .iter()
6199            .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
6200            .cloned()
6201            .collect()
6202    }
6203}
6204
6205pub fn register_action<T: Action>(
6206    view: &View<Editor>,
6207    cx: &mut WindowContext,
6208    listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
6209) {
6210    let view = view.clone();
6211    cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
6212        let action = action.downcast_ref().unwrap();
6213        if phase == DispatchPhase::Bubble {
6214            view.update(cx, |editor, cx| {
6215                listener(editor, action, cx);
6216            })
6217        }
6218    })
6219}
6220
6221fn compute_auto_height_layout(
6222    editor: &mut Editor,
6223    max_lines: usize,
6224    max_line_number_width: Pixels,
6225    known_dimensions: Size<Option<Pixels>>,
6226    available_width: AvailableSpace,
6227    cx: &mut ViewContext<Editor>,
6228) -> Option<Size<Pixels>> {
6229    let width = known_dimensions.width.or_else(|| {
6230        if let AvailableSpace::Definite(available_width) = available_width {
6231            Some(available_width)
6232        } else {
6233            None
6234        }
6235    })?;
6236    if let Some(height) = known_dimensions.height {
6237        return Some(size(width, height));
6238    }
6239
6240    let style = editor.style.as_ref().unwrap();
6241    let font_id = cx.text_system().resolve_font(&style.text.font());
6242    let font_size = style.text.font_size.to_pixels(cx.rem_size());
6243    let line_height = style.text.line_height_in_pixels(cx.rem_size());
6244    let em_width = cx
6245        .text_system()
6246        .typographic_bounds(font_id, font_size, 'm')
6247        .unwrap()
6248        .size
6249        .width;
6250
6251    let mut snapshot = editor.snapshot(cx);
6252    let gutter_dimensions =
6253        snapshot.gutter_dimensions(font_id, font_size, em_width, max_line_number_width, cx);
6254
6255    editor.gutter_dimensions = gutter_dimensions;
6256    let text_width = width - gutter_dimensions.width;
6257    let overscroll = size(em_width, px(0.));
6258
6259    let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
6260    if editor.set_wrap_width(Some(editor_width), cx) {
6261        snapshot = editor.snapshot(cx);
6262    }
6263
6264    let scroll_height = Pixels::from(snapshot.max_point().row().next_row().0) * line_height;
6265    let height = scroll_height
6266        .max(line_height)
6267        .min(line_height * max_lines as f32);
6268
6269    Some(size(width, height))
6270}