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