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