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