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