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