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