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