element.rs

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