element.rs

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