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