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