element.rs

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