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