element.rs

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