element.rs

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