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        rows: Range<DisplayRow>,
1835        line_number_layouts: &[Option<ShapedLine>],
1836        snapshot: &EditorSnapshot,
1837        style: &EditorStyle,
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 = 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: 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, style);
1881            LineWithInvisibles::from_chunks(
1882                chunks,
1883                &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 { auto_width } => {
4503                        let rem_size = cx.rem_size();
4504
4505                        let height = self.style.text.line_height_in_pixels(rem_size);
4506                        if auto_width {
4507                            let editor_handle = cx.view().clone();
4508                            let style = self.style.clone();
4509                            cx.request_measured_layout(Style::default(), move |_, _, cx| {
4510                                let editor_snapshot =
4511                                    editor_handle.update(cx, |editor, cx| editor.snapshot(cx));
4512                                let line = Self::layout_lines(
4513                                    DisplayRow(0)..DisplayRow(1),
4514                                    &[],
4515                                    &editor_snapshot,
4516                                    &style,
4517                                    cx,
4518                                )
4519                                .pop()
4520                                .unwrap();
4521
4522                                let font_id = cx.text_system().resolve_font(&style.text.font());
4523                                let font_size = style.text.font_size.to_pixels(cx.rem_size());
4524                                let em_width = cx
4525                                    .text_system()
4526                                    .typographic_bounds(font_id, font_size, 'm')
4527                                    .unwrap()
4528                                    .size
4529                                    .width;
4530
4531                                size(line.width + em_width, height)
4532                            })
4533                        } else {
4534                            let mut style = Style::default();
4535                            style.size.height = height.into();
4536                            style.size.width = relative(1.).into();
4537                            cx.request_layout(style, None)
4538                        }
4539                    }
4540                    EditorMode::AutoHeight { max_lines } => {
4541                        let editor_handle = cx.view().clone();
4542                        let max_line_number_width =
4543                            self.max_line_number_width(&editor.snapshot(cx), cx);
4544                        cx.request_measured_layout(
4545                            Style::default(),
4546                            move |known_dimensions, available_space, cx| {
4547                                editor_handle
4548                                    .update(cx, |editor, cx| {
4549                                        compute_auto_height_layout(
4550                                            editor,
4551                                            max_lines,
4552                                            max_line_number_width,
4553                                            known_dimensions,
4554                                            available_space.width,
4555                                            cx,
4556                                        )
4557                                    })
4558                                    .unwrap_or_default()
4559                            },
4560                        )
4561                    }
4562                    EditorMode::Full => {
4563                        let mut style = Style::default();
4564                        style.size.width = relative(1.).into();
4565                        style.size.height = relative(1.).into();
4566                        cx.request_layout(style, None)
4567                    }
4568                };
4569
4570                (layout_id, ())
4571            })
4572        })
4573    }
4574
4575    fn prepaint(
4576        &mut self,
4577        _: Option<&GlobalElementId>,
4578        bounds: Bounds<Pixels>,
4579        _: &mut Self::RequestLayoutState,
4580        cx: &mut WindowContext,
4581    ) -> Self::PrepaintState {
4582        let text_style = TextStyleRefinement {
4583            font_size: Some(self.style.text.font_size),
4584            line_height: Some(self.style.text.line_height),
4585            ..Default::default()
4586        };
4587        cx.set_view_id(self.editor.entity_id());
4588
4589        let rem_size = self.rem_size(cx);
4590        cx.with_rem_size(rem_size, |cx| {
4591            cx.with_text_style(Some(text_style), |cx| {
4592                cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
4593                    let mut snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
4594                    let style = self.style.clone();
4595
4596                    let font_id = cx.text_system().resolve_font(&style.text.font());
4597                    let font_size = style.text.font_size.to_pixels(cx.rem_size());
4598                    let line_height = style.text.line_height_in_pixels(cx.rem_size());
4599                    let em_width = cx
4600                        .text_system()
4601                        .typographic_bounds(font_id, font_size, 'm')
4602                        .unwrap()
4603                        .size
4604                        .width;
4605                    let em_advance = cx
4606                        .text_system()
4607                        .advance(font_id, font_size, 'm')
4608                        .unwrap()
4609                        .width;
4610
4611                    let gutter_dimensions = snapshot.gutter_dimensions(
4612                        font_id,
4613                        font_size,
4614                        em_width,
4615                        self.max_line_number_width(&snapshot, cx),
4616                        cx,
4617                    );
4618                    let text_width = bounds.size.width - gutter_dimensions.width;
4619
4620                    let right_margin = if snapshot.mode == EditorMode::Full {
4621                        EditorElement::SCROLLBAR_WIDTH
4622                    } else {
4623                        px(0.)
4624                    };
4625                    let overscroll = size(em_width + right_margin, px(0.));
4626
4627                    snapshot = self.editor.update(cx, |editor, cx| {
4628                        editor.last_bounds = Some(bounds);
4629                        editor.gutter_dimensions = gutter_dimensions;
4630                        editor.set_visible_line_count(bounds.size.height / line_height, cx);
4631
4632                        let editor_width =
4633                            text_width - gutter_dimensions.margin - overscroll.width - em_width;
4634                        let wrap_width = match editor.soft_wrap_mode(cx) {
4635                            SoftWrap::None => None,
4636                            SoftWrap::PreferLine => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
4637                            SoftWrap::EditorWidth => Some(editor_width),
4638                            SoftWrap::Column(column) => {
4639                                Some(editor_width.min(column as f32 * em_advance))
4640                            }
4641                        };
4642
4643                        if editor.set_wrap_width(wrap_width, cx) {
4644                            editor.snapshot(cx)
4645                        } else {
4646                            snapshot
4647                        }
4648                    });
4649
4650                    let wrap_guides = self
4651                        .editor
4652                        .read(cx)
4653                        .wrap_guides(cx)
4654                        .iter()
4655                        .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
4656                        .collect::<SmallVec<[_; 2]>>();
4657
4658                    let hitbox = cx.insert_hitbox(bounds, false);
4659                    let gutter_hitbox = cx.insert_hitbox(
4660                        Bounds {
4661                            origin: bounds.origin,
4662                            size: size(gutter_dimensions.width, bounds.size.height),
4663                        },
4664                        false,
4665                    );
4666                    let text_hitbox = cx.insert_hitbox(
4667                        Bounds {
4668                            origin: gutter_hitbox.upper_right(),
4669                            size: size(text_width, bounds.size.height),
4670                        },
4671                        false,
4672                    );
4673                    // Offset the content_bounds from the text_bounds by the gutter margin (which
4674                    // is roughly half a character wide) to make hit testing work more like how we want.
4675                    let content_origin =
4676                        text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
4677
4678                    let height_in_lines = bounds.size.height / line_height;
4679                    let max_scroll_top = if matches!(snapshot.mode, EditorMode::AutoHeight { .. }) {
4680                        (snapshot.max_point().row().as_f32() - height_in_lines + 1.).max(0.)
4681                    } else {
4682                        let settings = EditorSettings::get_global(cx);
4683                        let max_row = snapshot.max_point().row().as_f32();
4684                        match settings.scroll_beyond_last_line {
4685                            ScrollBeyondLastLine::OnePage => max_row,
4686                            ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.0).max(0.0),
4687                            ScrollBeyondLastLine::VerticalScrollMargin => {
4688                                (max_row - height_in_lines + 1.0 + settings.vertical_scroll_margin)
4689                                    .max(0.0)
4690                            }
4691                        }
4692                    };
4693
4694                    let mut autoscroll_containing_element = false;
4695                    let mut autoscroll_horizontally = false;
4696                    self.editor.update(cx, |editor, cx| {
4697                        autoscroll_containing_element =
4698                            editor.autoscroll_requested() || editor.has_pending_selection();
4699                        autoscroll_horizontally =
4700                            editor.autoscroll_vertically(bounds, line_height, max_scroll_top, cx);
4701                        snapshot = editor.snapshot(cx);
4702                    });
4703
4704                    let mut scroll_position = snapshot.scroll_position();
4705                    // The scroll position is a fractional point, the whole number of which represents
4706                    // the top of the window in terms of display rows.
4707                    let start_row = DisplayRow(scroll_position.y as u32);
4708                    let max_row = snapshot.max_point().row();
4709                    let end_row = cmp::min(
4710                        (scroll_position.y + height_in_lines).ceil() as u32,
4711                        max_row.next_row().0,
4712                    );
4713                    let end_row = DisplayRow(end_row);
4714
4715                    let buffer_rows = snapshot
4716                        .buffer_rows(start_row)
4717                        .take((start_row..end_row).len())
4718                        .collect::<Vec<_>>();
4719
4720                    let start_anchor = if start_row == Default::default() {
4721                        Anchor::min()
4722                    } else {
4723                        snapshot.buffer_snapshot.anchor_before(
4724                            DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
4725                        )
4726                    };
4727                    let end_anchor = if end_row > max_row {
4728                        Anchor::max()
4729                    } else {
4730                        snapshot.buffer_snapshot.anchor_before(
4731                            DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
4732                        )
4733                    };
4734
4735                    let highlighted_rows = self
4736                        .editor
4737                        .update(cx, |editor, cx| editor.highlighted_display_rows(cx));
4738                    let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
4739                        start_anchor..end_anchor,
4740                        &snapshot.display_snapshot,
4741                        cx.theme().colors(),
4742                    );
4743                    let highlighted_gutter_ranges =
4744                        self.editor.read(cx).gutter_highlights_in_range(
4745                            start_anchor..end_anchor,
4746                            &snapshot.display_snapshot,
4747                            cx,
4748                        );
4749
4750                    let redacted_ranges = self.editor.read(cx).redacted_ranges(
4751                        start_anchor..end_anchor,
4752                        &snapshot.display_snapshot,
4753                        cx,
4754                    );
4755
4756                    let (selections, active_rows, newest_selection_head) = self.layout_selections(
4757                        start_anchor,
4758                        end_anchor,
4759                        &snapshot,
4760                        start_row,
4761                        end_row,
4762                        cx,
4763                    );
4764
4765                    let line_numbers = self.layout_line_numbers(
4766                        start_row..end_row,
4767                        buffer_rows.iter().copied(),
4768                        &active_rows,
4769                        newest_selection_head,
4770                        &snapshot,
4771                        cx,
4772                    );
4773
4774                    let mut gutter_fold_toggles =
4775                        cx.with_element_namespace("gutter_fold_toggles", |cx| {
4776                            self.layout_gutter_fold_toggles(
4777                                start_row..end_row,
4778                                buffer_rows.iter().copied(),
4779                                &active_rows,
4780                                &snapshot,
4781                                cx,
4782                            )
4783                        });
4784                    let crease_trailers = cx.with_element_namespace("crease_trailers", |cx| {
4785                        self.layout_crease_trailers(buffer_rows.iter().copied(), &snapshot, cx)
4786                    });
4787
4788                    let display_hunks = self.layout_git_gutters(
4789                        line_height,
4790                        &gutter_hitbox,
4791                        start_row..end_row,
4792                        &snapshot,
4793                        cx,
4794                    );
4795
4796                    let mut max_visible_line_width = Pixels::ZERO;
4797                    let mut line_layouts = Self::layout_lines(
4798                        start_row..end_row,
4799                        &line_numbers,
4800                        &snapshot,
4801                        &self.style,
4802                        cx,
4803                    );
4804                    for line_with_invisibles in &line_layouts {
4805                        if line_with_invisibles.width > max_visible_line_width {
4806                            max_visible_line_width = line_with_invisibles.width;
4807                        }
4808                    }
4809
4810                    let longest_line_width =
4811                        layout_line(snapshot.longest_row(), &snapshot, &style, cx).width;
4812                    let mut scroll_width =
4813                        longest_line_width.max(max_visible_line_width) + overscroll.width;
4814
4815                    let mut blocks = cx.with_element_namespace("blocks", |cx| {
4816                        self.build_blocks(
4817                            start_row..end_row,
4818                            &snapshot,
4819                            &hitbox,
4820                            &text_hitbox,
4821                            &mut scroll_width,
4822                            &gutter_dimensions,
4823                            em_width,
4824                            gutter_dimensions.full_width(),
4825                            line_height,
4826                            &line_layouts,
4827                            cx,
4828                        )
4829                    });
4830
4831                    let start_buffer_row =
4832                        MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
4833                    let end_buffer_row =
4834                        MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
4835
4836                    let scroll_max = point(
4837                        ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
4838                        max_row.as_f32(),
4839                    );
4840
4841                    self.editor.update(cx, |editor, cx| {
4842                        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
4843
4844                        let autoscrolled = if autoscroll_horizontally {
4845                            editor.autoscroll_horizontally(
4846                                start_row,
4847                                text_hitbox.size.width,
4848                                scroll_width,
4849                                em_width,
4850                                &line_layouts,
4851                                cx,
4852                            )
4853                        } else {
4854                            false
4855                        };
4856
4857                        if clamped || autoscrolled {
4858                            snapshot = editor.snapshot(cx);
4859                            scroll_position = snapshot.scroll_position();
4860                        }
4861                    });
4862
4863                    let scroll_pixel_position = point(
4864                        scroll_position.x * em_width,
4865                        scroll_position.y * line_height,
4866                    );
4867
4868                    let indent_guides = self.layout_indent_guides(
4869                        content_origin,
4870                        text_hitbox.origin,
4871                        start_buffer_row..end_buffer_row,
4872                        scroll_pixel_position,
4873                        line_height,
4874                        &snapshot,
4875                        cx,
4876                    );
4877
4878                    let crease_trailers = cx.with_element_namespace("crease_trailers", |cx| {
4879                        self.prepaint_crease_trailers(
4880                            crease_trailers,
4881                            &line_layouts,
4882                            line_height,
4883                            content_origin,
4884                            scroll_pixel_position,
4885                            em_width,
4886                            cx,
4887                        )
4888                    });
4889
4890                    let mut inline_blame = None;
4891                    if let Some(newest_selection_head) = newest_selection_head {
4892                        let display_row = newest_selection_head.row();
4893                        if (start_row..end_row).contains(&display_row) {
4894                            let line_ix = display_row.minus(start_row) as usize;
4895                            let line_layout = &line_layouts[line_ix];
4896                            let crease_trailer_layout = crease_trailers[line_ix].as_ref();
4897                            inline_blame = self.layout_inline_blame(
4898                                display_row,
4899                                &snapshot.display_snapshot,
4900                                line_layout,
4901                                crease_trailer_layout,
4902                                em_width,
4903                                content_origin,
4904                                scroll_pixel_position,
4905                                line_height,
4906                                cx,
4907                            );
4908                        }
4909                    }
4910
4911                    let blamed_display_rows = self.layout_blame_entries(
4912                        buffer_rows.into_iter(),
4913                        em_width,
4914                        scroll_position,
4915                        line_height,
4916                        &gutter_hitbox,
4917                        gutter_dimensions.git_blame_entries_width,
4918                        cx,
4919                    );
4920
4921                    let scroll_max = point(
4922                        ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
4923                        max_scroll_top,
4924                    );
4925
4926                    self.editor.update(cx, |editor, cx| {
4927                        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
4928
4929                        let autoscrolled = if autoscroll_horizontally {
4930                            editor.autoscroll_horizontally(
4931                                start_row,
4932                                text_hitbox.size.width,
4933                                scroll_width,
4934                                em_width,
4935                                &line_layouts,
4936                                cx,
4937                            )
4938                        } else {
4939                            false
4940                        };
4941
4942                        if clamped || autoscrolled {
4943                            snapshot = editor.snapshot(cx);
4944                            scroll_position = snapshot.scroll_position();
4945                        }
4946                    });
4947
4948                    let line_elements = self.prepaint_lines(
4949                        start_row,
4950                        &mut line_layouts,
4951                        line_height,
4952                        scroll_pixel_position,
4953                        content_origin,
4954                        cx,
4955                    );
4956
4957                    cx.with_element_namespace("blocks", |cx| {
4958                        self.layout_blocks(
4959                            &mut blocks,
4960                            &hitbox,
4961                            line_height,
4962                            scroll_pixel_position,
4963                            cx,
4964                        );
4965                    });
4966
4967                    let cursors = self.collect_cursors(&snapshot, cx);
4968                    let visible_row_range = start_row..end_row;
4969                    let non_visible_cursors = cursors
4970                        .iter()
4971                        .any(move |c| !visible_row_range.contains(&c.0.row()));
4972
4973                    let visible_cursors = self.layout_visible_cursors(
4974                        &snapshot,
4975                        &selections,
4976                        start_row..end_row,
4977                        &line_layouts,
4978                        &text_hitbox,
4979                        content_origin,
4980                        scroll_position,
4981                        scroll_pixel_position,
4982                        line_height,
4983                        em_width,
4984                        autoscroll_containing_element,
4985                        cx,
4986                    );
4987
4988                    let scrollbar_layout = self.layout_scrollbar(
4989                        &snapshot,
4990                        bounds,
4991                        scroll_position,
4992                        height_in_lines,
4993                        non_visible_cursors,
4994                        cx,
4995                    );
4996
4997                    let gutter_settings = EditorSettings::get_global(cx).gutter;
4998
4999                    let mut _context_menu_visible = false;
5000                    let mut code_actions_indicator = None;
5001                    if let Some(newest_selection_head) = newest_selection_head {
5002                        if (start_row..end_row).contains(&newest_selection_head.row()) {
5003                            _context_menu_visible = self.layout_context_menu(
5004                                line_height,
5005                                &hitbox,
5006                                &text_hitbox,
5007                                content_origin,
5008                                start_row,
5009                                scroll_pixel_position,
5010                                &line_layouts,
5011                                newest_selection_head,
5012                                gutter_dimensions.width - gutter_dimensions.left_padding,
5013                                cx,
5014                            );
5015
5016                            let show_code_actions = snapshot
5017                                .show_code_actions
5018                                .unwrap_or_else(|| gutter_settings.code_actions);
5019                            if show_code_actions {
5020                                let newest_selection_point =
5021                                    newest_selection_head.to_point(&snapshot.display_snapshot);
5022                                let buffer = snapshot.buffer_snapshot.buffer_line_for_row(
5023                                    MultiBufferRow(newest_selection_point.row),
5024                                );
5025                                if let Some((buffer, range)) = buffer {
5026                                    let buffer_id = buffer.remote_id();
5027                                    let row = range.start.row;
5028                                    let has_test_indicator =
5029                                        self.editor.read(cx).tasks.contains_key(&(buffer_id, row));
5030
5031                                    if !has_test_indicator {
5032                                        code_actions_indicator = self
5033                                            .layout_code_actions_indicator(
5034                                                line_height,
5035                                                newest_selection_head,
5036                                                scroll_pixel_position,
5037                                                &gutter_dimensions,
5038                                                &gutter_hitbox,
5039                                                cx,
5040                                            );
5041                                    }
5042                                }
5043                            }
5044                        }
5045                    }
5046
5047                    let test_indicators = if gutter_settings.runnables {
5048                        self.layout_run_indicators(
5049                            line_height,
5050                            scroll_pixel_position,
5051                            &gutter_dimensions,
5052                            &gutter_hitbox,
5053                            &snapshot,
5054                            cx,
5055                        )
5056                    } else {
5057                        vec![]
5058                    };
5059
5060                    if !cx.has_active_drag() {
5061                        self.layout_hover_popovers(
5062                            &snapshot,
5063                            &hitbox,
5064                            &text_hitbox,
5065                            start_row..end_row,
5066                            content_origin,
5067                            scroll_pixel_position,
5068                            &line_layouts,
5069                            line_height,
5070                            em_width,
5071                            cx,
5072                        );
5073                    }
5074
5075                    let mouse_context_menu = self.layout_mouse_context_menu(cx);
5076
5077                    cx.with_element_namespace("gutter_fold_toggles", |cx| {
5078                        self.prepaint_gutter_fold_toggles(
5079                            &mut gutter_fold_toggles,
5080                            line_height,
5081                            &gutter_dimensions,
5082                            gutter_settings,
5083                            scroll_pixel_position,
5084                            &gutter_hitbox,
5085                            cx,
5086                        )
5087                    });
5088
5089                    let invisible_symbol_font_size = font_size / 2.;
5090                    let tab_invisible = cx
5091                        .text_system()
5092                        .shape_line(
5093                            "".into(),
5094                            invisible_symbol_font_size,
5095                            &[TextRun {
5096                                len: "".len(),
5097                                font: self.style.text.font(),
5098                                color: cx.theme().colors().editor_invisible,
5099                                background_color: None,
5100                                underline: None,
5101                                strikethrough: None,
5102                            }],
5103                        )
5104                        .unwrap();
5105                    let space_invisible = cx
5106                        .text_system()
5107                        .shape_line(
5108                            "".into(),
5109                            invisible_symbol_font_size,
5110                            &[TextRun {
5111                                len: "".len(),
5112                                font: self.style.text.font(),
5113                                color: cx.theme().colors().editor_invisible,
5114                                background_color: None,
5115                                underline: None,
5116                                strikethrough: None,
5117                            }],
5118                        )
5119                        .unwrap();
5120
5121                    EditorLayout {
5122                        mode: snapshot.mode,
5123                        position_map: Arc::new(PositionMap {
5124                            size: bounds.size,
5125                            scroll_pixel_position,
5126                            scroll_max,
5127                            line_layouts,
5128                            line_height,
5129                            em_width,
5130                            em_advance,
5131                            snapshot,
5132                        }),
5133                        visible_display_row_range: start_row..end_row,
5134                        wrap_guides,
5135                        indent_guides,
5136                        hitbox,
5137                        text_hitbox,
5138                        gutter_hitbox,
5139                        gutter_dimensions,
5140                        content_origin,
5141                        scrollbar_layout,
5142                        active_rows,
5143                        highlighted_rows,
5144                        highlighted_ranges,
5145                        highlighted_gutter_ranges,
5146                        redacted_ranges,
5147                        line_elements,
5148                        line_numbers,
5149                        display_hunks,
5150                        blamed_display_rows,
5151                        inline_blame,
5152                        blocks,
5153                        cursors,
5154                        visible_cursors,
5155                        selections,
5156                        mouse_context_menu,
5157                        test_indicators,
5158                        code_actions_indicator,
5159                        gutter_fold_toggles,
5160                        crease_trailers,
5161                        tab_invisible,
5162                        space_invisible,
5163                    }
5164                })
5165            })
5166        })
5167    }
5168
5169    fn paint(
5170        &mut self,
5171        _: Option<&GlobalElementId>,
5172        bounds: Bounds<gpui::Pixels>,
5173        _: &mut Self::RequestLayoutState,
5174        layout: &mut Self::PrepaintState,
5175        cx: &mut WindowContext,
5176    ) {
5177        let focus_handle = self.editor.focus_handle(cx);
5178        let key_context = self.editor.read(cx).key_context(cx);
5179        cx.set_focus_handle(&focus_handle);
5180        cx.set_key_context(key_context);
5181        cx.handle_input(
5182            &focus_handle,
5183            ElementInputHandler::new(bounds, self.editor.clone()),
5184        );
5185        self.register_actions(cx);
5186        self.register_key_listeners(cx, layout);
5187
5188        let text_style = TextStyleRefinement {
5189            font_size: Some(self.style.text.font_size),
5190            line_height: Some(self.style.text.line_height),
5191            ..Default::default()
5192        };
5193        let mouse_position = cx.mouse_position();
5194        let hovered_hunk = layout
5195            .display_hunks
5196            .iter()
5197            .find_map(|(hunk, hunk_hitbox)| match hunk {
5198                DisplayDiffHunk::Folded { .. } => None,
5199                DisplayDiffHunk::Unfolded {
5200                    diff_base_byte_range,
5201                    multi_buffer_range,
5202                    status,
5203                    ..
5204                } => {
5205                    if hunk_hitbox
5206                        .as_ref()
5207                        .map(|hitbox| hitbox.contains(&mouse_position))
5208                        .unwrap_or(false)
5209                    {
5210                        Some(HunkToExpand {
5211                            status: *status,
5212                            multi_buffer_range: multi_buffer_range.clone(),
5213                            diff_base_byte_range: diff_base_byte_range.clone(),
5214                        })
5215                    } else {
5216                        None
5217                    }
5218                }
5219            });
5220        let rem_size = self.rem_size(cx);
5221        cx.with_rem_size(rem_size, |cx| {
5222            cx.with_text_style(Some(text_style), |cx| {
5223                cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
5224                    self.paint_mouse_listeners(layout, hovered_hunk, cx);
5225                    self.paint_background(layout, cx);
5226                    self.paint_indent_guides(layout, cx);
5227
5228                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
5229                        self.paint_blamed_display_rows(layout, cx);
5230                        self.paint_line_numbers(layout, cx);
5231                    }
5232
5233                    self.paint_text(layout, cx);
5234
5235                    if !layout.blocks.is_empty() {
5236                        cx.with_element_namespace("blocks", |cx| {
5237                            self.paint_blocks(layout, cx);
5238                        });
5239                    }
5240
5241                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
5242                        self.paint_gutter_highlights(layout, cx);
5243                        self.paint_gutter_indicators(layout, cx);
5244                    }
5245
5246                    self.paint_scrollbar(layout, cx);
5247                    self.paint_mouse_context_menu(layout, cx);
5248                });
5249            })
5250        })
5251    }
5252}
5253
5254impl IntoElement for EditorElement {
5255    type Element = Self;
5256
5257    fn into_element(self) -> Self::Element {
5258        self
5259    }
5260}
5261
5262pub struct EditorLayout {
5263    position_map: Arc<PositionMap>,
5264    hitbox: Hitbox,
5265    text_hitbox: Hitbox,
5266    gutter_hitbox: Hitbox,
5267    gutter_dimensions: GutterDimensions,
5268    content_origin: gpui::Point<Pixels>,
5269    scrollbar_layout: Option<ScrollbarLayout>,
5270    mode: EditorMode,
5271    wrap_guides: SmallVec<[(Pixels, bool); 2]>,
5272    indent_guides: Option<Vec<IndentGuideLayout>>,
5273    visible_display_row_range: Range<DisplayRow>,
5274    active_rows: BTreeMap<DisplayRow, bool>,
5275    highlighted_rows: BTreeMap<DisplayRow, Hsla>,
5276    line_elements: SmallVec<[AnyElement; 1]>,
5277    line_numbers: Vec<Option<ShapedLine>>,
5278    display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
5279    blamed_display_rows: Option<Vec<AnyElement>>,
5280    inline_blame: Option<AnyElement>,
5281    blocks: Vec<BlockLayout>,
5282    highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
5283    highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
5284    redacted_ranges: Vec<Range<DisplayPoint>>,
5285    cursors: Vec<(DisplayPoint, Hsla)>,
5286    visible_cursors: Vec<CursorLayout>,
5287    selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
5288    code_actions_indicator: Option<AnyElement>,
5289    test_indicators: Vec<AnyElement>,
5290    gutter_fold_toggles: Vec<Option<AnyElement>>,
5291    crease_trailers: Vec<Option<CreaseTrailerLayout>>,
5292    mouse_context_menu: Option<AnyElement>,
5293    tab_invisible: ShapedLine,
5294    space_invisible: ShapedLine,
5295}
5296
5297impl EditorLayout {
5298    fn line_end_overshoot(&self) -> Pixels {
5299        0.15 * self.position_map.line_height
5300    }
5301}
5302
5303struct ColoredRange<T> {
5304    start: T,
5305    end: T,
5306    color: Hsla,
5307}
5308
5309#[derive(Clone)]
5310struct ScrollbarLayout {
5311    hitbox: Hitbox,
5312    visible_row_range: Range<f32>,
5313    visible: bool,
5314    row_height: Pixels,
5315    thumb_height: Pixels,
5316}
5317
5318impl ScrollbarLayout {
5319    const BORDER_WIDTH: Pixels = px(1.0);
5320    const LINE_MARKER_HEIGHT: Pixels = px(2.0);
5321    const MIN_MARKER_HEIGHT: Pixels = px(5.0);
5322    const MIN_THUMB_HEIGHT: Pixels = px(20.0);
5323
5324    fn thumb_bounds(&self) -> Bounds<Pixels> {
5325        let thumb_top = self.y_for_row(self.visible_row_range.start);
5326        let thumb_bottom = thumb_top + self.thumb_height;
5327        Bounds::from_corners(
5328            point(self.hitbox.left(), thumb_top),
5329            point(self.hitbox.right(), thumb_bottom),
5330        )
5331    }
5332
5333    fn y_for_row(&self, row: f32) -> Pixels {
5334        self.hitbox.top() + row * self.row_height
5335    }
5336
5337    fn marker_quads_for_ranges(
5338        &self,
5339        row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
5340        column: Option<usize>,
5341    ) -> Vec<PaintQuad> {
5342        struct MinMax {
5343            min: Pixels,
5344            max: Pixels,
5345        }
5346        let (x_range, height_limit) = if let Some(column) = column {
5347            let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
5348            let start = Self::BORDER_WIDTH + (column as f32 * column_width);
5349            let end = start + column_width;
5350            (
5351                Range { start, end },
5352                MinMax {
5353                    min: Self::MIN_MARKER_HEIGHT,
5354                    max: px(f32::MAX),
5355                },
5356            )
5357        } else {
5358            (
5359                Range {
5360                    start: Self::BORDER_WIDTH,
5361                    end: self.hitbox.size.width,
5362                },
5363                MinMax {
5364                    min: Self::LINE_MARKER_HEIGHT,
5365                    max: Self::LINE_MARKER_HEIGHT,
5366                },
5367            )
5368        };
5369
5370        let row_to_y = |row: DisplayRow| row.as_f32() * self.row_height;
5371        let mut pixel_ranges = row_ranges
5372            .into_iter()
5373            .map(|range| {
5374                let start_y = row_to_y(range.start);
5375                let end_y = row_to_y(range.end)
5376                    + self.row_height.max(height_limit.min).min(height_limit.max);
5377                ColoredRange {
5378                    start: start_y,
5379                    end: end_y,
5380                    color: range.color,
5381                }
5382            })
5383            .peekable();
5384
5385        let mut quads = Vec::new();
5386        while let Some(mut pixel_range) = pixel_ranges.next() {
5387            while let Some(next_pixel_range) = pixel_ranges.peek() {
5388                if pixel_range.end >= next_pixel_range.start - px(1.0)
5389                    && pixel_range.color == next_pixel_range.color
5390                {
5391                    pixel_range.end = next_pixel_range.end.max(pixel_range.end);
5392                    pixel_ranges.next();
5393                } else {
5394                    break;
5395                }
5396            }
5397
5398            let bounds = Bounds::from_corners(
5399                point(x_range.start, pixel_range.start),
5400                point(x_range.end, pixel_range.end),
5401            );
5402            quads.push(quad(
5403                bounds,
5404                Corners::default(),
5405                pixel_range.color,
5406                Edges::default(),
5407                Hsla::transparent_black(),
5408            ));
5409        }
5410
5411        quads
5412    }
5413}
5414
5415struct CreaseTrailerLayout {
5416    element: AnyElement,
5417    bounds: Bounds<Pixels>,
5418}
5419
5420struct PositionMap {
5421    size: Size<Pixels>,
5422    line_height: Pixels,
5423    scroll_pixel_position: gpui::Point<Pixels>,
5424    scroll_max: gpui::Point<f32>,
5425    em_width: Pixels,
5426    em_advance: Pixels,
5427    line_layouts: Vec<LineWithInvisibles>,
5428    snapshot: EditorSnapshot,
5429}
5430
5431#[derive(Debug, Copy, Clone)]
5432pub struct PointForPosition {
5433    pub previous_valid: DisplayPoint,
5434    pub next_valid: DisplayPoint,
5435    pub exact_unclipped: DisplayPoint,
5436    pub column_overshoot_after_line_end: u32,
5437}
5438
5439impl PointForPosition {
5440    pub fn as_valid(&self) -> Option<DisplayPoint> {
5441        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
5442            Some(self.previous_valid)
5443        } else {
5444            None
5445        }
5446    }
5447}
5448
5449impl PositionMap {
5450    fn point_for_position(
5451        &self,
5452        text_bounds: Bounds<Pixels>,
5453        position: gpui::Point<Pixels>,
5454    ) -> PointForPosition {
5455        let scroll_position = self.snapshot.scroll_position();
5456        let position = position - text_bounds.origin;
5457        let y = position.y.max(px(0.)).min(self.size.height);
5458        let x = position.x + (scroll_position.x * self.em_width);
5459        let row = ((y / self.line_height) + scroll_position.y) as u32;
5460
5461        let (column, x_overshoot_after_line_end) = if let Some(line) = self
5462            .line_layouts
5463            .get(row as usize - scroll_position.y as usize)
5464        {
5465            if let Some(ix) = line.index_for_x(x) {
5466                (ix as u32, px(0.))
5467            } else {
5468                (line.len as u32, px(0.).max(x - line.width))
5469            }
5470        } else {
5471            (0, x)
5472        };
5473
5474        let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
5475        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
5476        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
5477
5478        let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
5479        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
5480        PointForPosition {
5481            previous_valid,
5482            next_valid,
5483            exact_unclipped,
5484            column_overshoot_after_line_end,
5485        }
5486    }
5487}
5488
5489struct BlockLayout {
5490    row: DisplayRow,
5491    element: AnyElement,
5492    available_space: Size<AvailableSpace>,
5493    style: BlockStyle,
5494}
5495
5496fn layout_line(
5497    row: DisplayRow,
5498    snapshot: &EditorSnapshot,
5499    style: &EditorStyle,
5500    cx: &mut WindowContext,
5501) -> LineWithInvisibles {
5502    let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
5503    LineWithInvisibles::from_chunks(chunks, &style.text, MAX_LINE_LEN, 1, &[], snapshot.mode, cx)
5504        .pop()
5505        .unwrap()
5506}
5507
5508#[derive(Debug)]
5509pub struct IndentGuideLayout {
5510    origin: gpui::Point<Pixels>,
5511    length: Pixels,
5512    single_indent_width: Pixels,
5513    depth: u32,
5514    active: bool,
5515    settings: IndentGuideSettings,
5516}
5517
5518pub struct CursorLayout {
5519    origin: gpui::Point<Pixels>,
5520    block_width: Pixels,
5521    line_height: Pixels,
5522    color: Hsla,
5523    shape: CursorShape,
5524    block_text: Option<ShapedLine>,
5525    cursor_name: Option<AnyElement>,
5526}
5527
5528#[derive(Debug)]
5529pub struct CursorName {
5530    string: SharedString,
5531    color: Hsla,
5532    is_top_row: bool,
5533}
5534
5535impl CursorLayout {
5536    pub fn new(
5537        origin: gpui::Point<Pixels>,
5538        block_width: Pixels,
5539        line_height: Pixels,
5540        color: Hsla,
5541        shape: CursorShape,
5542        block_text: Option<ShapedLine>,
5543    ) -> CursorLayout {
5544        CursorLayout {
5545            origin,
5546            block_width,
5547            line_height,
5548            color,
5549            shape,
5550            block_text,
5551            cursor_name: None,
5552        }
5553    }
5554
5555    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
5556        Bounds {
5557            origin: self.origin + origin,
5558            size: size(self.block_width, self.line_height),
5559        }
5560    }
5561
5562    fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
5563        match self.shape {
5564            CursorShape::Bar => Bounds {
5565                origin: self.origin + origin,
5566                size: size(px(2.0), self.line_height),
5567            },
5568            CursorShape::Block | CursorShape::Hollow => Bounds {
5569                origin: self.origin + origin,
5570                size: size(self.block_width, self.line_height),
5571            },
5572            CursorShape::Underscore => Bounds {
5573                origin: self.origin
5574                    + origin
5575                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
5576                size: size(self.block_width, px(2.0)),
5577            },
5578        }
5579    }
5580
5581    pub fn layout(
5582        &mut self,
5583        origin: gpui::Point<Pixels>,
5584        cursor_name: Option<CursorName>,
5585        cx: &mut WindowContext,
5586    ) {
5587        if let Some(cursor_name) = cursor_name {
5588            let bounds = self.bounds(origin);
5589            let text_size = self.line_height / 1.5;
5590
5591            let name_origin = if cursor_name.is_top_row {
5592                point(bounds.right() - px(1.), bounds.top())
5593            } else {
5594                point(bounds.left(), bounds.top() - text_size / 2. - px(1.))
5595            };
5596            let mut name_element = div()
5597                .bg(self.color)
5598                .text_size(text_size)
5599                .px_0p5()
5600                .line_height(text_size + px(2.))
5601                .text_color(cursor_name.color)
5602                .child(cursor_name.string.clone())
5603                .into_any_element();
5604
5605            name_element.prepaint_as_root(
5606                name_origin,
5607                size(AvailableSpace::MinContent, AvailableSpace::MinContent),
5608                cx,
5609            );
5610
5611            self.cursor_name = Some(name_element);
5612        }
5613    }
5614
5615    pub fn paint(&mut self, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
5616        let bounds = self.bounds(origin);
5617
5618        //Draw background or border quad
5619        let cursor = if matches!(self.shape, CursorShape::Hollow) {
5620            outline(bounds, self.color)
5621        } else {
5622            fill(bounds, self.color)
5623        };
5624
5625        if let Some(name) = &mut self.cursor_name {
5626            name.paint(cx);
5627        }
5628
5629        cx.paint_quad(cursor);
5630
5631        if let Some(block_text) = &self.block_text {
5632            block_text
5633                .paint(self.origin + origin, self.line_height, cx)
5634                .log_err();
5635        }
5636    }
5637
5638    pub fn shape(&self) -> CursorShape {
5639        self.shape
5640    }
5641}
5642
5643#[derive(Debug)]
5644pub struct HighlightedRange {
5645    pub start_y: Pixels,
5646    pub line_height: Pixels,
5647    pub lines: Vec<HighlightedRangeLine>,
5648    pub color: Hsla,
5649    pub corner_radius: Pixels,
5650}
5651
5652#[derive(Debug)]
5653pub struct HighlightedRangeLine {
5654    pub start_x: Pixels,
5655    pub end_x: Pixels,
5656}
5657
5658impl HighlightedRange {
5659    pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut WindowContext) {
5660        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
5661            self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
5662            self.paint_lines(
5663                self.start_y + self.line_height,
5664                &self.lines[1..],
5665                bounds,
5666                cx,
5667            );
5668        } else {
5669            self.paint_lines(self.start_y, &self.lines, bounds, cx);
5670        }
5671    }
5672
5673    fn paint_lines(
5674        &self,
5675        start_y: Pixels,
5676        lines: &[HighlightedRangeLine],
5677        _bounds: Bounds<Pixels>,
5678        cx: &mut WindowContext,
5679    ) {
5680        if lines.is_empty() {
5681            return;
5682        }
5683
5684        let first_line = lines.first().unwrap();
5685        let last_line = lines.last().unwrap();
5686
5687        let first_top_left = point(first_line.start_x, start_y);
5688        let first_top_right = point(first_line.end_x, start_y);
5689
5690        let curve_height = point(Pixels::ZERO, self.corner_radius);
5691        let curve_width = |start_x: Pixels, end_x: Pixels| {
5692            let max = (end_x - start_x) / 2.;
5693            let width = if max < self.corner_radius {
5694                max
5695            } else {
5696                self.corner_radius
5697            };
5698
5699            point(width, Pixels::ZERO)
5700        };
5701
5702        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
5703        let mut path = gpui::Path::new(first_top_right - top_curve_width);
5704        path.curve_to(first_top_right + curve_height, first_top_right);
5705
5706        let mut iter = lines.iter().enumerate().peekable();
5707        while let Some((ix, line)) = iter.next() {
5708            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
5709
5710            if let Some((_, next_line)) = iter.peek() {
5711                let next_top_right = point(next_line.end_x, bottom_right.y);
5712
5713                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
5714                    Ordering::Equal => {
5715                        path.line_to(bottom_right);
5716                    }
5717                    Ordering::Less => {
5718                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
5719                        path.line_to(bottom_right - curve_height);
5720                        if self.corner_radius > Pixels::ZERO {
5721                            path.curve_to(bottom_right - curve_width, bottom_right);
5722                        }
5723                        path.line_to(next_top_right + curve_width);
5724                        if self.corner_radius > Pixels::ZERO {
5725                            path.curve_to(next_top_right + curve_height, next_top_right);
5726                        }
5727                    }
5728                    Ordering::Greater => {
5729                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
5730                        path.line_to(bottom_right - curve_height);
5731                        if self.corner_radius > Pixels::ZERO {
5732                            path.curve_to(bottom_right + curve_width, bottom_right);
5733                        }
5734                        path.line_to(next_top_right - curve_width);
5735                        if self.corner_radius > Pixels::ZERO {
5736                            path.curve_to(next_top_right + curve_height, next_top_right);
5737                        }
5738                    }
5739                }
5740            } else {
5741                let curve_width = curve_width(line.start_x, line.end_x);
5742                path.line_to(bottom_right - curve_height);
5743                if self.corner_radius > Pixels::ZERO {
5744                    path.curve_to(bottom_right - curve_width, bottom_right);
5745                }
5746
5747                let bottom_left = point(line.start_x, bottom_right.y);
5748                path.line_to(bottom_left + curve_width);
5749                if self.corner_radius > Pixels::ZERO {
5750                    path.curve_to(bottom_left - curve_height, bottom_left);
5751                }
5752            }
5753        }
5754
5755        if first_line.start_x > last_line.start_x {
5756            let curve_width = curve_width(last_line.start_x, first_line.start_x);
5757            let second_top_left = point(last_line.start_x, start_y + self.line_height);
5758            path.line_to(second_top_left + curve_height);
5759            if self.corner_radius > Pixels::ZERO {
5760                path.curve_to(second_top_left + curve_width, second_top_left);
5761            }
5762            let first_bottom_left = point(first_line.start_x, second_top_left.y);
5763            path.line_to(first_bottom_left - curve_width);
5764            if self.corner_radius > Pixels::ZERO {
5765                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
5766            }
5767        }
5768
5769        path.line_to(first_top_left + curve_height);
5770        if self.corner_radius > Pixels::ZERO {
5771            path.curve_to(first_top_left + top_curve_width, first_top_left);
5772        }
5773        path.line_to(first_top_right - top_curve_width);
5774
5775        cx.paint_path(path, self.color);
5776    }
5777}
5778
5779pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
5780    (delta.pow(1.5) / 100.0).into()
5781}
5782
5783fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
5784    (delta.pow(1.2) / 300.0).into()
5785}
5786
5787#[cfg(test)]
5788mod tests {
5789    use super::*;
5790    use crate::{
5791        display_map::{BlockDisposition, BlockProperties},
5792        editor_tests::{init_test, update_test_language_settings},
5793        Editor, MultiBuffer,
5794    };
5795    use gpui::{TestAppContext, VisualTestContext};
5796    use language::language_settings;
5797    use log::info;
5798    use std::num::NonZeroU32;
5799    use ui::Context;
5800    use util::test::sample_text;
5801
5802    #[gpui::test]
5803    fn test_shape_line_numbers(cx: &mut TestAppContext) {
5804        init_test(cx, |_| {});
5805        let window = cx.add_window(|cx| {
5806            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
5807            Editor::new(EditorMode::Full, buffer, None, true, cx)
5808        });
5809
5810        let editor = window.root(cx).unwrap();
5811        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5812        let element = EditorElement::new(&editor, style);
5813        let snapshot = window.update(cx, |editor, cx| editor.snapshot(cx)).unwrap();
5814
5815        let layouts = cx
5816            .update_window(*window, |_, cx| {
5817                element.layout_line_numbers(
5818                    DisplayRow(0)..DisplayRow(6),
5819                    (0..6).map(MultiBufferRow).map(Some),
5820                    &Default::default(),
5821                    Some(DisplayPoint::new(DisplayRow(0), 0)),
5822                    &snapshot,
5823                    cx,
5824                )
5825            })
5826            .unwrap();
5827        assert_eq!(layouts.len(), 6);
5828
5829        let relative_rows = window
5830            .update(cx, |editor, cx| {
5831                let snapshot = editor.snapshot(cx);
5832                element.calculate_relative_line_numbers(
5833                    &snapshot,
5834                    &(DisplayRow(0)..DisplayRow(6)),
5835                    Some(DisplayRow(3)),
5836                )
5837            })
5838            .unwrap();
5839        assert_eq!(relative_rows[&DisplayRow(0)], 3);
5840        assert_eq!(relative_rows[&DisplayRow(1)], 2);
5841        assert_eq!(relative_rows[&DisplayRow(2)], 1);
5842        // current line has no relative number
5843        assert_eq!(relative_rows[&DisplayRow(4)], 1);
5844        assert_eq!(relative_rows[&DisplayRow(5)], 2);
5845
5846        // works if cursor is before screen
5847        let relative_rows = window
5848            .update(cx, |editor, cx| {
5849                let snapshot = editor.snapshot(cx);
5850                element.calculate_relative_line_numbers(
5851                    &snapshot,
5852                    &(DisplayRow(3)..DisplayRow(6)),
5853                    Some(DisplayRow(1)),
5854                )
5855            })
5856            .unwrap();
5857        assert_eq!(relative_rows.len(), 3);
5858        assert_eq!(relative_rows[&DisplayRow(3)], 2);
5859        assert_eq!(relative_rows[&DisplayRow(4)], 3);
5860        assert_eq!(relative_rows[&DisplayRow(5)], 4);
5861
5862        // works if cursor is after screen
5863        let relative_rows = window
5864            .update(cx, |editor, cx| {
5865                let snapshot = editor.snapshot(cx);
5866                element.calculate_relative_line_numbers(
5867                    &snapshot,
5868                    &(DisplayRow(0)..DisplayRow(3)),
5869                    Some(DisplayRow(6)),
5870                )
5871            })
5872            .unwrap();
5873        assert_eq!(relative_rows.len(), 3);
5874        assert_eq!(relative_rows[&DisplayRow(0)], 5);
5875        assert_eq!(relative_rows[&DisplayRow(1)], 4);
5876        assert_eq!(relative_rows[&DisplayRow(2)], 3);
5877    }
5878
5879    #[gpui::test]
5880    async fn test_vim_visual_selections(cx: &mut TestAppContext) {
5881        init_test(cx, |_| {});
5882
5883        let window = cx.add_window(|cx| {
5884            let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
5885            Editor::new(EditorMode::Full, buffer, None, true, cx)
5886        });
5887        let cx = &mut VisualTestContext::from_window(*window, cx);
5888        let editor = window.root(cx).unwrap();
5889        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5890
5891        window
5892            .update(cx, |editor, cx| {
5893                editor.cursor_shape = CursorShape::Block;
5894                editor.change_selections(None, cx, |s| {
5895                    s.select_ranges([
5896                        Point::new(0, 0)..Point::new(1, 0),
5897                        Point::new(3, 2)..Point::new(3, 3),
5898                        Point::new(5, 6)..Point::new(6, 0),
5899                    ]);
5900                });
5901            })
5902            .unwrap();
5903
5904        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
5905            EditorElement::new(&editor, style)
5906        });
5907
5908        assert_eq!(state.selections.len(), 1);
5909        let local_selections = &state.selections[0].1;
5910        assert_eq!(local_selections.len(), 3);
5911        // moves cursor back one line
5912        assert_eq!(
5913            local_selections[0].head,
5914            DisplayPoint::new(DisplayRow(0), 6)
5915        );
5916        assert_eq!(
5917            local_selections[0].range,
5918            DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
5919        );
5920
5921        // moves cursor back one column
5922        assert_eq!(
5923            local_selections[1].range,
5924            DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
5925        );
5926        assert_eq!(
5927            local_selections[1].head,
5928            DisplayPoint::new(DisplayRow(3), 2)
5929        );
5930
5931        // leaves cursor on the max point
5932        assert_eq!(
5933            local_selections[2].range,
5934            DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
5935        );
5936        assert_eq!(
5937            local_selections[2].head,
5938            DisplayPoint::new(DisplayRow(6), 0)
5939        );
5940
5941        // active lines does not include 1 (even though the range of the selection does)
5942        assert_eq!(
5943            state.active_rows.keys().cloned().collect::<Vec<_>>(),
5944            vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
5945        );
5946
5947        // multi-buffer support
5948        // in DisplayPoint coordinates, this is what we're dealing with:
5949        //  0: [[file
5950        //  1:   header
5951        //  2:   section]]
5952        //  3: aaaaaa
5953        //  4: bbbbbb
5954        //  5: cccccc
5955        //  6:
5956        //  7: [[footer]]
5957        //  8: [[header]]
5958        //  9: ffffff
5959        // 10: gggggg
5960        // 11: hhhhhh
5961        // 12:
5962        // 13: [[footer]]
5963        // 14: [[file
5964        // 15:   header
5965        // 16:   section]]
5966        // 17: bbbbbb
5967        // 18: cccccc
5968        // 19: dddddd
5969        // 20: [[footer]]
5970        let window = cx.add_window(|cx| {
5971            let buffer = MultiBuffer::build_multi(
5972                [
5973                    (
5974                        &(sample_text(8, 6, 'a') + "\n"),
5975                        vec![
5976                            Point::new(0, 0)..Point::new(3, 0),
5977                            Point::new(4, 0)..Point::new(7, 0),
5978                        ],
5979                    ),
5980                    (
5981                        &(sample_text(8, 6, 'a') + "\n"),
5982                        vec![Point::new(1, 0)..Point::new(3, 0)],
5983                    ),
5984                ],
5985                cx,
5986            );
5987            Editor::new(EditorMode::Full, buffer, None, true, cx)
5988        });
5989        let editor = window.root(cx).unwrap();
5990        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5991        let _state = window.update(cx, |editor, cx| {
5992            editor.cursor_shape = CursorShape::Block;
5993            editor.change_selections(None, cx, |s| {
5994                s.select_display_ranges([
5995                    DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0),
5996                    DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0),
5997                ]);
5998            });
5999        });
6000
6001        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6002            EditorElement::new(&editor, style)
6003        });
6004        assert_eq!(state.selections.len(), 1);
6005        let local_selections = &state.selections[0].1;
6006        assert_eq!(local_selections.len(), 2);
6007
6008        // moves cursor on excerpt boundary back a line
6009        // and doesn't allow selection to bleed through
6010        assert_eq!(
6011            local_selections[0].range,
6012            DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0)
6013        );
6014        assert_eq!(
6015            local_selections[0].head,
6016            DisplayPoint::new(DisplayRow(6), 0)
6017        );
6018        // moves cursor on buffer boundary back two lines
6019        // and doesn't allow selection to bleed through
6020        assert_eq!(
6021            local_selections[1].range,
6022            DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0)
6023        );
6024        assert_eq!(
6025            local_selections[1].head,
6026            DisplayPoint::new(DisplayRow(12), 0)
6027        );
6028    }
6029
6030    #[gpui::test]
6031    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
6032        init_test(cx, |_| {});
6033
6034        let window = cx.add_window(|cx| {
6035            let buffer = MultiBuffer::build_simple("", cx);
6036            Editor::new(EditorMode::Full, buffer, None, true, cx)
6037        });
6038        let cx = &mut VisualTestContext::from_window(*window, cx);
6039        let editor = window.root(cx).unwrap();
6040        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6041        window
6042            .update(cx, |editor, cx| {
6043                editor.set_placeholder_text("hello", cx);
6044                editor.insert_blocks(
6045                    [BlockProperties {
6046                        style: BlockStyle::Fixed,
6047                        disposition: BlockDisposition::Above,
6048                        height: 3,
6049                        position: Anchor::min(),
6050                        render: Box::new(|_| div().into_any()),
6051                    }],
6052                    None,
6053                    cx,
6054                );
6055
6056                // Blur the editor so that it displays placeholder text.
6057                cx.blur();
6058            })
6059            .unwrap();
6060
6061        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6062            EditorElement::new(&editor, style)
6063        });
6064        assert_eq!(state.position_map.line_layouts.len(), 4);
6065        assert_eq!(
6066            state
6067                .line_numbers
6068                .iter()
6069                .map(Option::is_some)
6070                .collect::<Vec<_>>(),
6071            &[false, false, false, true]
6072        );
6073    }
6074
6075    #[gpui::test]
6076    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
6077        const TAB_SIZE: u32 = 4;
6078
6079        let input_text = "\t \t|\t| a b";
6080        let expected_invisibles = vec![
6081            Invisible::Tab {
6082                line_start_offset: 0,
6083                line_end_offset: TAB_SIZE as usize,
6084            },
6085            Invisible::Whitespace {
6086                line_offset: TAB_SIZE as usize,
6087            },
6088            Invisible::Tab {
6089                line_start_offset: TAB_SIZE as usize + 1,
6090                line_end_offset: TAB_SIZE as usize * 2,
6091            },
6092            Invisible::Tab {
6093                line_start_offset: TAB_SIZE as usize * 2 + 1,
6094                line_end_offset: TAB_SIZE as usize * 3,
6095            },
6096            Invisible::Whitespace {
6097                line_offset: TAB_SIZE as usize * 3 + 1,
6098            },
6099            Invisible::Whitespace {
6100                line_offset: TAB_SIZE as usize * 3 + 3,
6101            },
6102        ];
6103        assert_eq!(
6104            expected_invisibles.len(),
6105            input_text
6106                .chars()
6107                .filter(|initial_char| initial_char.is_whitespace())
6108                .count(),
6109            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
6110        );
6111
6112        init_test(cx, |s| {
6113            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6114            s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
6115        });
6116
6117        let actual_invisibles =
6118            collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, px(500.0));
6119
6120        assert_eq!(expected_invisibles, actual_invisibles);
6121    }
6122
6123    #[gpui::test]
6124    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
6125        init_test(cx, |s| {
6126            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6127            s.defaults.tab_size = NonZeroU32::new(4);
6128        });
6129
6130        for editor_mode_without_invisibles in [
6131            EditorMode::SingleLine { auto_width: false },
6132            EditorMode::AutoHeight { max_lines: 100 },
6133        ] {
6134            let invisibles = collect_invisibles_from_new_editor(
6135                cx,
6136                editor_mode_without_invisibles,
6137                "\t\t\t| | a b",
6138                px(500.0),
6139            );
6140            assert!(invisibles.is_empty(),
6141                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
6142        }
6143    }
6144
6145    #[gpui::test]
6146    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
6147        let tab_size = 4;
6148        let input_text = "a\tbcd     ".repeat(9);
6149        let repeated_invisibles = [
6150            Invisible::Tab {
6151                line_start_offset: 1,
6152                line_end_offset: tab_size as usize,
6153            },
6154            Invisible::Whitespace {
6155                line_offset: tab_size as usize + 3,
6156            },
6157            Invisible::Whitespace {
6158                line_offset: tab_size as usize + 4,
6159            },
6160            Invisible::Whitespace {
6161                line_offset: tab_size as usize + 5,
6162            },
6163            Invisible::Whitespace {
6164                line_offset: tab_size as usize + 6,
6165            },
6166            Invisible::Whitespace {
6167                line_offset: tab_size as usize + 7,
6168            },
6169        ];
6170        let expected_invisibles = std::iter::once(repeated_invisibles)
6171            .cycle()
6172            .take(9)
6173            .flatten()
6174            .collect::<Vec<_>>();
6175        assert_eq!(
6176            expected_invisibles.len(),
6177            input_text
6178                .chars()
6179                .filter(|initial_char| initial_char.is_whitespace())
6180                .count(),
6181            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
6182        );
6183        info!("Expected invisibles: {expected_invisibles:?}");
6184
6185        init_test(cx, |_| {});
6186
6187        // Put the same string with repeating whitespace pattern into editors of various size,
6188        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
6189        let resize_step = 10.0;
6190        let mut editor_width = 200.0;
6191        while editor_width <= 1000.0 {
6192            update_test_language_settings(cx, |s| {
6193                s.defaults.tab_size = NonZeroU32::new(tab_size);
6194                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6195                s.defaults.preferred_line_length = Some(editor_width as u32);
6196                s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
6197            });
6198
6199            let actual_invisibles = collect_invisibles_from_new_editor(
6200                cx,
6201                EditorMode::Full,
6202                &input_text,
6203                px(editor_width),
6204            );
6205
6206            // Whatever the editor size is, ensure it has the same invisible kinds in the same order
6207            // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
6208            let mut i = 0;
6209            for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
6210                i = actual_index;
6211                match expected_invisibles.get(i) {
6212                    Some(expected_invisible) => match (expected_invisible, actual_invisible) {
6213                        (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
6214                        | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
6215                        _ => {
6216                            panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
6217                        }
6218                    },
6219                    None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
6220                }
6221            }
6222            let missing_expected_invisibles = &expected_invisibles[i + 1..];
6223            assert!(
6224                missing_expected_invisibles.is_empty(),
6225                "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
6226            );
6227
6228            editor_width += resize_step;
6229        }
6230    }
6231
6232    fn collect_invisibles_from_new_editor(
6233        cx: &mut TestAppContext,
6234        editor_mode: EditorMode,
6235        input_text: &str,
6236        editor_width: Pixels,
6237    ) -> Vec<Invisible> {
6238        info!(
6239            "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
6240            editor_width.0
6241        );
6242        let window = cx.add_window(|cx| {
6243            let buffer = MultiBuffer::build_simple(&input_text, cx);
6244            Editor::new(editor_mode, buffer, None, true, cx)
6245        });
6246        let cx = &mut VisualTestContext::from_window(*window, cx);
6247        let editor = window.root(cx).unwrap();
6248        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6249        window
6250            .update(cx, |editor, cx| {
6251                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
6252                editor.set_wrap_width(Some(editor_width), cx);
6253            })
6254            .unwrap();
6255        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6256            EditorElement::new(&editor, style)
6257        });
6258        state
6259            .position_map
6260            .line_layouts
6261            .iter()
6262            .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
6263            .cloned()
6264            .collect()
6265    }
6266}
6267
6268pub fn register_action<T: Action>(
6269    view: &View<Editor>,
6270    cx: &mut WindowContext,
6271    listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
6272) {
6273    let view = view.clone();
6274    cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
6275        let action = action.downcast_ref().unwrap();
6276        if phase == DispatchPhase::Bubble {
6277            view.update(cx, |editor, cx| {
6278                listener(editor, action, cx);
6279            })
6280        }
6281    })
6282}
6283
6284fn compute_auto_height_layout(
6285    editor: &mut Editor,
6286    max_lines: usize,
6287    max_line_number_width: Pixels,
6288    known_dimensions: Size<Option<Pixels>>,
6289    available_width: AvailableSpace,
6290    cx: &mut ViewContext<Editor>,
6291) -> Option<Size<Pixels>> {
6292    let width = known_dimensions.width.or_else(|| {
6293        if let AvailableSpace::Definite(available_width) = available_width {
6294            Some(available_width)
6295        } else {
6296            None
6297        }
6298    })?;
6299    if let Some(height) = known_dimensions.height {
6300        return Some(size(width, height));
6301    }
6302
6303    let style = editor.style.as_ref().unwrap();
6304    let font_id = cx.text_system().resolve_font(&style.text.font());
6305    let font_size = style.text.font_size.to_pixels(cx.rem_size());
6306    let line_height = style.text.line_height_in_pixels(cx.rem_size());
6307    let em_width = cx
6308        .text_system()
6309        .typographic_bounds(font_id, font_size, 'm')
6310        .unwrap()
6311        .size
6312        .width;
6313
6314    let mut snapshot = editor.snapshot(cx);
6315    let gutter_dimensions =
6316        snapshot.gutter_dimensions(font_id, font_size, em_width, max_line_number_width, cx);
6317
6318    editor.gutter_dimensions = gutter_dimensions;
6319    let text_width = width - gutter_dimensions.width;
6320    let overscroll = size(em_width, px(0.));
6321
6322    let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
6323    if editor.set_wrap_width(Some(editor_width), cx) {
6324        snapshot = editor.snapshot(cx);
6325    }
6326
6327    let scroll_height = Pixels::from(snapshot.max_point().row().next_row().0) * line_height;
6328    let height = scroll_height
6329        .max(line_height)
6330        .min(line_height * max_lines as f32);
6331
6332    Some(size(width, height))
6333}