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