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 available_space =
1030                            size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1031                        let context_menu_size = context_menu.measure(available_space, cx);
1032
1033                        let cursor_row_layout = &layout.position_map.line_layouts
1034                            [(position.row() - start_row) as usize]
1035                            .line;
1036                        let x = cursor_row_layout.x_for_index(position.column() as usize)
1037                            - layout.position_map.scroll_position.x;
1038                        let y = (position.row() + 1) as f32 * layout.position_map.line_height
1039                            - layout.position_map.scroll_position.y;
1040                        let mut list_origin = content_origin + point(x, y);
1041                        let list_width = context_menu_size.width;
1042                        let list_height = context_menu_size.height;
1043
1044                        // Snap the right edge of the list to the right edge of the window if
1045                        // its horizontal bounds overflow.
1046                        if list_origin.x + list_width > cx.viewport_size().width {
1047                            list_origin.x =
1048                                (cx.viewport_size().width - list_width).max(Pixels::ZERO);
1049                        }
1050
1051                        if list_origin.y + list_height > text_bounds.lower_right().y {
1052                            list_origin.y -= layout.position_map.line_height + list_height;
1053                        }
1054
1055                        context_menu.draw(list_origin, available_space, cx);
1056                    })
1057                }
1058
1059                // if let Some((position, hover_popovers)) = layout.hover_popovers.as_mut() {
1060                //     cx.scene().push_stacking_context(None, None);
1061
1062                //     // This is safe because we check on layout whether the required row is available
1063                //     let hovered_row_layout =
1064                //         &layout.position_map.line_layouts[(position.row() - start_row) as usize].line;
1065
1066                //     // Minimum required size: Take the first popover, and add 1.5 times the minimum popover
1067                //     // height. This is the size we will use to decide whether to render popovers above or below
1068                //     // the hovered line.
1069                //     let first_size = hover_popovers[0].size();
1070                //     let height_to_reserve = first_size.y
1071                //         + 1.5 * MIN_POPOVER_LINE_HEIGHT as f32 * layout.position_map.line_height;
1072
1073                //     // Compute Hovered Point
1074                //     let x = hovered_row_layout.x_for_index(position.column() as usize) - scroll_left;
1075                //     let y = position.row() as f32 * layout.position_map.line_height - scroll_top;
1076                //     let hovered_point = content_origin + point(x, y);
1077
1078                //     if hovered_point.y - height_to_reserve > 0.0 {
1079                //         // There is enough space above. Render popovers above the hovered point
1080                //         let mut current_y = hovered_point.y;
1081                //         for hover_popover in hover_popovers {
1082                //             let size = hover_popover.size();
1083                //             let mut popover_origin = point(hovered_point.x, current_y - size.y);
1084
1085                //             let x_out_of_bounds = bounds.max_x - (popover_origin.x + size.x);
1086                //             if x_out_of_bounds < 0.0 {
1087                //                 popover_origin.set_x(popover_origin.x + x_out_of_bounds);
1088                //             }
1089
1090                //             hover_popover.paint(
1091                //                 popover_origin,
1092                //                 Bounds::<Pixels>::from_points(
1093                //                     gpui::Point::<Pixels>::zero(),
1094                //                     point(f32::MAX, f32::MAX),
1095                //                 ), // Let content bleed outside of editor
1096                //                 editor,
1097                //                 cx,
1098                //             );
1099
1100                //             current_y = popover_origin.y - HOVER_POPOVER_GAP;
1101                //         }
1102                //     } else {
1103                //         // There is not enough space above. Render popovers below the hovered point
1104                //         let mut current_y = hovered_point.y + layout.position_map.line_height;
1105                //         for hover_popover in hover_popovers {
1106                //             let size = hover_popover.size();
1107                //             let mut popover_origin = point(hovered_point.x, current_y);
1108
1109                //             let x_out_of_bounds = bounds.max_x - (popover_origin.x + size.x);
1110                //             if x_out_of_bounds < 0.0 {
1111                //                 popover_origin.set_x(popover_origin.x + x_out_of_bounds);
1112                //             }
1113
1114                //             hover_popover.paint(
1115                //                 popover_origin,
1116                //                 Bounds::<Pixels>::from_points(
1117                //                     gpui::Point::<Pixels>::zero(),
1118                //                     point(f32::MAX, f32::MAX),
1119                //                 ), // Let content bleed outside of editor
1120                //                 editor,
1121                //                 cx,
1122                //             );
1123
1124                //             current_y = popover_origin.y + size.y + HOVER_POPOVER_GAP;
1125                //         }
1126                //     }
1127
1128                //     cx.scene().pop_stacking_context();
1129                // }
1130            },
1131        )
1132    }
1133
1134    fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
1135        bounds.upper_right().x - self.style.scrollbar_width
1136    }
1137
1138    // fn paint_scrollbar(
1139    //     &mut self,
1140    //     bounds: Bounds<Pixels>,
1141    //     layout: &mut LayoutState,
1142    //     editor: &Editor,
1143    //     cx: &mut ViewContext<Editor>,
1144    // ) {
1145    //     enum ScrollbarMouseHandlers {}
1146    //     if layout.mode != EditorMode::Full {
1147    //         return;
1148    //     }
1149
1150    //     let style = &self.style.theme.scrollbar;
1151
1152    //     let top = bounds.min_y;
1153    //     let bottom = bounds.max_y;
1154    //     let right = bounds.max_x;
1155    //     let left = self.scrollbar_left(&bounds);
1156    //     let row_range = &layout.scrollbar_row_range;
1157    //     let max_row = layout.max_row as f32 + (row_range.end - row_range.start);
1158
1159    //     let mut height = bounds.height();
1160    //     let mut first_row_y_offset = 0.0;
1161
1162    //     // Impose a minimum height on the scrollbar thumb
1163    //     let row_height = height / max_row;
1164    //     let min_thumb_height =
1165    //         style.min_height_factor * cx.font_cache.line_height(self.style.text.font_size);
1166    //     let thumb_height = (row_range.end - row_range.start) * row_height;
1167    //     if thumb_height < min_thumb_height {
1168    //         first_row_y_offset = (min_thumb_height - thumb_height) / 2.0;
1169    //         height -= min_thumb_height - thumb_height;
1170    //     }
1171
1172    //     let y_for_row = |row: f32| -> f32 { top + first_row_y_offset + row * row_height };
1173
1174    //     let thumb_top = y_for_row(row_range.start) - first_row_y_offset;
1175    //     let thumb_bottom = y_for_row(row_range.end) + first_row_y_offset;
1176    //     let track_bounds = Bounds::<Pixels>::from_points(point(left, top), point(right, bottom));
1177    //     let thumb_bounds = Bounds::<Pixels>::from_points(point(left, thumb_top), point(right, thumb_bottom));
1178
1179    //     if layout.show_scrollbars {
1180    //         cx.paint_quad(Quad {
1181    //             bounds: track_bounds,
1182    //             border: style.track.border.into(),
1183    //             background: style.track.background_color,
1184    //             ..Default::default()
1185    //         });
1186    //         let scrollbar_settings = settings::get::<EditorSettings>(cx).scrollbar;
1187    //         let theme = theme::current(cx);
1188    //         let scrollbar_theme = &theme.editor.scrollbar;
1189    //         if layout.is_singleton && scrollbar_settings.selections {
1190    //             let start_anchor = Anchor::min();
1191    //             let end_anchor = Anchor::max;
1192    //             let color = scrollbar_theme.selections;
1193    //             let border = Border {
1194    //                 width: 1.,
1195    //                 color: style.thumb.border.color,
1196    //                 overlay: false,
1197    //                 top: false,
1198    //                 right: true,
1199    //                 bottom: false,
1200    //                 left: true,
1201    //             };
1202    //             let mut push_region = |start: DisplayPoint, end: DisplayPoint| {
1203    //                 let start_y = y_for_row(start.row() as f32);
1204    //                 let mut end_y = y_for_row(end.row() as f32);
1205    //                 if end_y - start_y < 1. {
1206    //                     end_y = start_y + 1.;
1207    //                 }
1208    //                 let bounds = Bounds::<Pixels>::from_points(point(left, start_y), point(right, end_y));
1209
1210    //                 cx.paint_quad(Quad {
1211    //                     bounds,
1212    //                     background: Some(color),
1213    //                     border: border.into(),
1214    //                     corner_radii: style.thumb.corner_radii.into(),
1215    //                 })
1216    //             };
1217    //             let background_ranges = editor
1218    //                 .background_highlight_row_ranges::<crate::items::BufferSearchHighlights>(
1219    //                     start_anchor..end_anchor,
1220    //                     &layout.position_map.snapshot,
1221    //                     50000,
1222    //                 );
1223    //             for row in background_ranges {
1224    //                 let start = row.start();
1225    //                 let end = row.end();
1226    //                 push_region(*start, *end);
1227    //             }
1228    //         }
1229
1230    //         if layout.is_singleton && scrollbar_settings.git_diff {
1231    //             let diff_style = scrollbar_theme.git.clone();
1232    //             for hunk in layout
1233    //                 .position_map
1234    //                 .snapshot
1235    //                 .buffer_snapshot
1236    //                 .git_diff_hunks_in_range(0..(max_row.floor() as u32))
1237    //             {
1238    //                 let start_display = Point::new(hunk.buffer_range.start, 0)
1239    //                     .to_display_point(&layout.position_map.snapshot.display_snapshot);
1240    //                 let end_display = Point::new(hunk.buffer_range.end, 0)
1241    //                     .to_display_point(&layout.position_map.snapshot.display_snapshot);
1242    //                 let start_y = y_for_row(start_display.row() as f32);
1243    //                 let mut end_y = if hunk.buffer_range.start == hunk.buffer_range.end {
1244    //                     y_for_row((end_display.row() + 1) as f32)
1245    //                 } else {
1246    //                     y_for_row((end_display.row()) as f32)
1247    //                 };
1248
1249    //                 if end_y - start_y < 1. {
1250    //                     end_y = start_y + 1.;
1251    //                 }
1252    //                 let bounds = Bounds::<Pixels>::from_points(point(left, start_y), point(right, end_y));
1253
1254    //                 let color = match hunk.status() {
1255    //                     DiffHunkStatus::Added => diff_style.inserted,
1256    //                     DiffHunkStatus::Modified => diff_style.modified,
1257    //                     DiffHunkStatus::Removed => diff_style.deleted,
1258    //                 };
1259
1260    //                 let border = Border {
1261    //                     width: 1.,
1262    //                     color: style.thumb.border.color,
1263    //                     overlay: false,
1264    //                     top: false,
1265    //                     right: true,
1266    //                     bottom: false,
1267    //                     left: true,
1268    //                 };
1269
1270    //                 cx.paint_quad(Quad {
1271    //                     bounds,
1272    //                     background: Some(color),
1273    //                     border: border.into(),
1274    //                     corner_radii: style.thumb.corner_radii.into(),
1275    //                 })
1276    //             }
1277    //         }
1278
1279    //         cx.paint_quad(Quad {
1280    //             bounds: thumb_bounds,
1281    //             border: style.thumb.border.into(),
1282    //             background: style.thumb.background_color,
1283    //             corner_radii: style.thumb.corner_radii.into(),
1284    //         });
1285    //     }
1286
1287    //     cx.scene().push_cursor_region(CursorRegion {
1288    //         bounds: track_bounds,
1289    //         style: CursorStyle::Arrow,
1290    //     });
1291    //     let region_id = cx.view_id();
1292    //     cx.scene().push_mouse_region(
1293    //         MouseRegion::new::<ScrollbarMouseHandlers>(region_id, region_id, track_bounds)
1294    //             .on_move(move |event, editor: &mut Editor, cx| {
1295    //                 if event.pressed_button.is_none() {
1296    //                     editor.scroll_manager.show_scrollbar(cx);
1297    //                 }
1298    //             })
1299    //             .on_down(MouseButton::Left, {
1300    //                 let row_range = row_range.clone();
1301    //                 move |event, editor: &mut Editor, cx| {
1302    //                     let y = event.position.y;
1303    //                     if y < thumb_top || thumb_bottom < y {
1304    //                         let center_row = ((y - top) * max_row as f32 / height).round() as u32;
1305    //                         let top_row = center_row
1306    //                             .saturating_sub((row_range.end - row_range.start) as u32 / 2);
1307    //                         let mut position = editor.scroll_position(cx);
1308    //                         position.set_y(top_row as f32);
1309    //                         editor.set_scroll_position(position, cx);
1310    //                     } else {
1311    //                         editor.scroll_manager.show_scrollbar(cx);
1312    //                     }
1313    //                 }
1314    //             })
1315    //             .on_drag(MouseButton::Left, {
1316    //                 move |event, editor: &mut Editor, cx| {
1317    //                     if event.end {
1318    //                         return;
1319    //                     }
1320
1321    //                     let y = event.prev_mouse_position.y;
1322    //                     let new_y = event.position.y;
1323    //                     if thumb_top < y && y < thumb_bottom {
1324    //                         let mut position = editor.scroll_position(cx);
1325    //                         position.set_y(position.y + (new_y - y) * (max_row as f32) / height);
1326    //                         if position.y < 0.0 {
1327    //                             position.set_y(0.);
1328    //                         }
1329    //                         editor.set_scroll_position(position, cx);
1330    //                     }
1331    //                 }
1332    //             }),
1333    //     );
1334    // }
1335
1336    #[allow(clippy::too_many_arguments)]
1337    fn paint_highlighted_range(
1338        &self,
1339        range: Range<DisplayPoint>,
1340        color: Hsla,
1341        corner_radius: Pixels,
1342        line_end_overshoot: Pixels,
1343        layout: &LayoutState,
1344        content_origin: gpui::Point<Pixels>,
1345        bounds: Bounds<Pixels>,
1346        cx: &mut WindowContext,
1347    ) {
1348        let start_row = layout.visible_display_row_range.start;
1349        let end_row = layout.visible_display_row_range.end;
1350        if range.start != range.end {
1351            let row_range = if range.end.column() == 0 {
1352                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
1353            } else {
1354                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
1355            };
1356
1357            let highlighted_range = HighlightedRange {
1358                color,
1359                line_height: layout.position_map.line_height,
1360                corner_radius,
1361                start_y: content_origin.y
1362                    + row_range.start as f32 * layout.position_map.line_height
1363                    - layout.position_map.scroll_position.y,
1364                lines: row_range
1365                    .into_iter()
1366                    .map(|row| {
1367                        let line_layout =
1368                            &layout.position_map.line_layouts[(row - start_row) as usize].line;
1369                        HighlightedRangeLine {
1370                            start_x: if row == range.start.row() {
1371                                content_origin.x
1372                                    + line_layout.x_for_index(range.start.column() as usize)
1373                                    - layout.position_map.scroll_position.x
1374                            } else {
1375                                content_origin.x - layout.position_map.scroll_position.x
1376                            },
1377                            end_x: if row == range.end.row() {
1378                                content_origin.x
1379                                    + line_layout.x_for_index(range.end.column() as usize)
1380                                    - layout.position_map.scroll_position.x
1381                            } else {
1382                                content_origin.x + line_layout.width + line_end_overshoot
1383                                    - layout.position_map.scroll_position.x
1384                            },
1385                        }
1386                    })
1387                    .collect(),
1388            };
1389
1390            highlighted_range.paint(bounds, cx);
1391        }
1392    }
1393
1394    fn paint_blocks(
1395        &mut self,
1396        bounds: Bounds<Pixels>,
1397        layout: &mut LayoutState,
1398        cx: &mut WindowContext,
1399    ) {
1400        let scroll_position = layout.position_map.snapshot.scroll_position();
1401        let scroll_left = scroll_position.x * layout.position_map.em_width;
1402        let scroll_top = scroll_position.y * layout.position_map.line_height;
1403
1404        for block in layout.blocks.drain(..) {
1405            let mut origin = bounds.origin
1406                + point(
1407                    Pixels::ZERO,
1408                    block.row as f32 * layout.position_map.line_height - scroll_top,
1409                );
1410            if !matches!(block.style, BlockStyle::Sticky) {
1411                origin += point(-scroll_left, Pixels::ZERO);
1412            }
1413            block.element.draw(origin, block.available_space, cx);
1414        }
1415    }
1416
1417    fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
1418        let style = &self.style;
1419        let font_size = style.text.font_size.to_pixels(cx.rem_size());
1420        let layout = cx
1421            .text_system()
1422            .shape_line(
1423                SharedString::from(" ".repeat(column)),
1424                font_size,
1425                &[TextRun {
1426                    len: column,
1427                    font: style.text.font(),
1428                    color: Hsla::default(),
1429                    background_color: None,
1430                    underline: None,
1431                }],
1432            )
1433            .unwrap();
1434
1435        layout.width
1436    }
1437
1438    fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
1439        let digit_count = (snapshot.max_buffer_row() as f32 + 1.).log10().floor() as usize + 1;
1440        self.column_pixels(digit_count, cx)
1441    }
1442
1443    //Folds contained in a hunk are ignored apart from shrinking visual size
1444    //If a fold contains any hunks then that fold line is marked as modified
1445    fn layout_git_gutters(
1446        &self,
1447        display_rows: Range<u32>,
1448        snapshot: &EditorSnapshot,
1449    ) -> Vec<DisplayDiffHunk> {
1450        let buffer_snapshot = &snapshot.buffer_snapshot;
1451
1452        let buffer_start_row = DisplayPoint::new(display_rows.start, 0)
1453            .to_point(snapshot)
1454            .row;
1455        let buffer_end_row = DisplayPoint::new(display_rows.end, 0)
1456            .to_point(snapshot)
1457            .row;
1458
1459        buffer_snapshot
1460            .git_diff_hunks_in_range(buffer_start_row..buffer_end_row)
1461            .map(|hunk| diff_hunk_to_display(hunk, snapshot))
1462            .dedup()
1463            .collect()
1464    }
1465
1466    fn calculate_relative_line_numbers(
1467        &self,
1468        snapshot: &EditorSnapshot,
1469        rows: &Range<u32>,
1470        relative_to: Option<u32>,
1471    ) -> HashMap<u32, u32> {
1472        let mut relative_rows: HashMap<u32, u32> = Default::default();
1473        let Some(relative_to) = relative_to else {
1474            return relative_rows;
1475        };
1476
1477        let start = rows.start.min(relative_to);
1478        let end = rows.end.max(relative_to);
1479
1480        let buffer_rows = snapshot
1481            .buffer_rows(start)
1482            .take(1 + (end - start) as usize)
1483            .collect::<Vec<_>>();
1484
1485        let head_idx = relative_to - start;
1486        let mut delta = 1;
1487        let mut i = head_idx + 1;
1488        while i < buffer_rows.len() as u32 {
1489            if buffer_rows[i as usize].is_some() {
1490                if rows.contains(&(i + start)) {
1491                    relative_rows.insert(i + start, delta);
1492                }
1493                delta += 1;
1494            }
1495            i += 1;
1496        }
1497        delta = 1;
1498        i = head_idx.min(buffer_rows.len() as u32 - 1);
1499        while i > 0 && buffer_rows[i as usize].is_none() {
1500            i -= 1;
1501        }
1502
1503        while i > 0 {
1504            i -= 1;
1505            if buffer_rows[i as usize].is_some() {
1506                if rows.contains(&(i + start)) {
1507                    relative_rows.insert(i + start, delta);
1508                }
1509                delta += 1;
1510            }
1511        }
1512
1513        relative_rows
1514    }
1515
1516    fn shape_line_numbers(
1517        &self,
1518        rows: Range<u32>,
1519        active_rows: &BTreeMap<u32, bool>,
1520        newest_selection_head: DisplayPoint,
1521        is_singleton: bool,
1522        snapshot: &EditorSnapshot,
1523        cx: &ViewContext<Editor>,
1524    ) -> (
1525        Vec<Option<ShapedLine>>,
1526        Vec<Option<(FoldStatus, BufferRow, bool)>>,
1527    ) {
1528        let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1529        let include_line_numbers = snapshot.mode == EditorMode::Full;
1530        let mut shaped_line_numbers = Vec::with_capacity(rows.len());
1531        let mut fold_statuses = Vec::with_capacity(rows.len());
1532        let mut line_number = String::new();
1533        let is_relative = EditorSettings::get_global(cx).relative_line_numbers;
1534        let relative_to = if is_relative {
1535            Some(newest_selection_head.row())
1536        } else {
1537            None
1538        };
1539
1540        let relative_rows = self.calculate_relative_line_numbers(&snapshot, &rows, relative_to);
1541
1542        for (ix, row) in snapshot
1543            .buffer_rows(rows.start)
1544            .take((rows.end - rows.start) as usize)
1545            .enumerate()
1546        {
1547            let display_row = rows.start + ix as u32;
1548            let (active, color) = if active_rows.contains_key(&display_row) {
1549                (true, cx.theme().colors().editor_active_line_number)
1550            } else {
1551                (false, cx.theme().colors().editor_line_number)
1552            };
1553            if let Some(buffer_row) = row {
1554                if include_line_numbers {
1555                    line_number.clear();
1556                    let default_number = buffer_row + 1;
1557                    let number = relative_rows
1558                        .get(&(ix as u32 + rows.start))
1559                        .unwrap_or(&default_number);
1560                    write!(&mut line_number, "{}", number).unwrap();
1561                    let run = TextRun {
1562                        len: line_number.len(),
1563                        font: self.style.text.font(),
1564                        color,
1565                        background_color: None,
1566                        underline: None,
1567                    };
1568                    let shaped_line = cx
1569                        .text_system()
1570                        .shape_line(line_number.clone().into(), font_size, &[run])
1571                        .unwrap();
1572                    shaped_line_numbers.push(Some(shaped_line));
1573                    fold_statuses.push(
1574                        is_singleton
1575                            .then(|| {
1576                                snapshot
1577                                    .fold_for_line(buffer_row)
1578                                    .map(|fold_status| (fold_status, buffer_row, active))
1579                            })
1580                            .flatten(),
1581                    )
1582                }
1583            } else {
1584                fold_statuses.push(None);
1585                shaped_line_numbers.push(None);
1586            }
1587        }
1588
1589        (shaped_line_numbers, fold_statuses)
1590    }
1591
1592    fn layout_lines(
1593        &self,
1594        rows: Range<u32>,
1595        line_number_layouts: &[Option<ShapedLine>],
1596        snapshot: &EditorSnapshot,
1597        cx: &ViewContext<Editor>,
1598    ) -> Vec<LineWithInvisibles> {
1599        if rows.start >= rows.end {
1600            return Vec::new();
1601        }
1602
1603        // When the editor is empty and unfocused, then show the placeholder.
1604        if snapshot.is_empty() {
1605            let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1606            let placeholder_color = cx.theme().styles.colors.text_placeholder;
1607            let placeholder_text = snapshot.placeholder_text();
1608            let placeholder_lines = placeholder_text
1609                .as_ref()
1610                .map_or("", AsRef::as_ref)
1611                .split('\n')
1612                .skip(rows.start as usize)
1613                .chain(iter::repeat(""))
1614                .take(rows.len());
1615            placeholder_lines
1616                .filter_map(move |line| {
1617                    let run = TextRun {
1618                        len: line.len(),
1619                        font: self.style.text.font(),
1620                        color: placeholder_color,
1621                        background_color: None,
1622                        underline: Default::default(),
1623                    };
1624                    cx.text_system()
1625                        .shape_line(line.to_string().into(), font_size, &[run])
1626                        .log_err()
1627                })
1628                .map(|line| LineWithInvisibles {
1629                    line,
1630                    invisibles: Vec::new(),
1631                })
1632                .collect()
1633        } else {
1634            let chunks = snapshot.highlighted_chunks(rows.clone(), true, &self.style);
1635            LineWithInvisibles::from_chunks(
1636                chunks,
1637                &self.style.text,
1638                MAX_LINE_LEN,
1639                rows.len() as usize,
1640                line_number_layouts,
1641                snapshot.mode,
1642                cx,
1643            )
1644        }
1645    }
1646
1647    fn compute_layout(
1648        &mut self,
1649        mut bounds: Bounds<Pixels>,
1650        cx: &mut WindowContext,
1651    ) -> LayoutState {
1652        self.editor.update(cx, |editor, cx| {
1653            // let mut size = constraint.max;
1654            // if size.x.is_infinite() {
1655            //     unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
1656            // }
1657
1658            let snapshot = editor.snapshot(cx);
1659            let style = self.style.clone();
1660
1661            let font_id = cx.text_system().font_id(&style.text.font()).unwrap();
1662            let font_size = style.text.font_size.to_pixels(cx.rem_size());
1663            let line_height = style.text.line_height_in_pixels(cx.rem_size());
1664            let em_width = cx
1665                .text_system()
1666                .typographic_bounds(font_id, font_size, 'm')
1667                .unwrap()
1668                .size
1669                .width;
1670            let em_advance = cx
1671                .text_system()
1672                .advance(font_id, font_size, 'm')
1673                .unwrap()
1674                .width;
1675
1676            let gutter_padding;
1677            let gutter_width;
1678            let gutter_margin;
1679            if snapshot.show_gutter {
1680                let descent = cx.text_system().descent(font_id, font_size).unwrap();
1681
1682                let gutter_padding_factor = 3.5;
1683                gutter_padding = (em_width * gutter_padding_factor).round();
1684                gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
1685                gutter_margin = -descent;
1686            } else {
1687                gutter_padding = Pixels::ZERO;
1688                gutter_width = Pixels::ZERO;
1689                gutter_margin = Pixels::ZERO;
1690            };
1691
1692            editor.gutter_width = gutter_width;
1693            let text_width = bounds.size.width - gutter_width;
1694            let overscroll = size(em_width, px(0.));
1695            let snapshot = {
1696                editor.set_visible_line_count((bounds.size.height / line_height).into(), cx);
1697
1698                let editor_width = text_width - gutter_margin - overscroll.width - em_width;
1699                let wrap_width = match editor.soft_wrap_mode(cx) {
1700                    SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
1701                    SoftWrap::EditorWidth => editor_width,
1702                    SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
1703                };
1704
1705                if editor.set_wrap_width(Some(wrap_width), cx) {
1706                    editor.snapshot(cx)
1707                } else {
1708                    snapshot
1709                }
1710            };
1711
1712            let wrap_guides = editor
1713                .wrap_guides(cx)
1714                .iter()
1715                .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
1716                .collect::<SmallVec<[_; 2]>>();
1717
1718            let scroll_height = Pixels::from(snapshot.max_point().row() + 1) * line_height;
1719            // todo!("this should happen during layout")
1720            let editor_mode = snapshot.mode;
1721            if let EditorMode::AutoHeight { max_lines } = editor_mode {
1722                todo!()
1723                //     size.set_y(
1724                //         scroll_height
1725                //             .min(constraint.max_along(Axis::Vertical))
1726                //             .max(constraint.min_along(Axis::Vertical))
1727                //             .max(line_height)
1728                //             .min(line_height * max_lines as f32),
1729                //     )
1730            } else if let EditorMode::SingleLine = editor_mode {
1731                bounds.size.height = line_height.min(bounds.size.height);
1732            }
1733            // todo!()
1734            // else if size.y.is_infinite() {
1735            //     //     size.set_y(scroll_height);
1736            // }
1737            //
1738            let gutter_size = size(gutter_width, bounds.size.height);
1739            let text_size = size(text_width, bounds.size.height);
1740
1741            let autoscroll_horizontally =
1742                editor.autoscroll_vertically(bounds.size.height, line_height, cx);
1743            let mut snapshot = editor.snapshot(cx);
1744
1745            let scroll_position = snapshot.scroll_position();
1746            // The scroll position is a fractional point, the whole number of which represents
1747            // the top of the window in terms of display rows.
1748            let start_row = scroll_position.y as u32;
1749            let height_in_lines = f32::from(bounds.size.height / line_height);
1750            let max_row = snapshot.max_point().row();
1751
1752            // Add 1 to ensure selections bleed off screen
1753            let end_row = 1 + cmp::min((scroll_position.y + height_in_lines).ceil() as u32, max_row);
1754
1755            let start_anchor = if start_row == 0 {
1756                Anchor::min()
1757            } else {
1758                snapshot
1759                    .buffer_snapshot
1760                    .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
1761            };
1762            let end_anchor = if end_row > max_row {
1763                Anchor::max()
1764            } else {
1765                snapshot
1766                    .buffer_snapshot
1767                    .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
1768            };
1769
1770            let mut selections: Vec<(PlayerColor, Vec<SelectionLayout>)> = Vec::new();
1771            let mut active_rows = BTreeMap::new();
1772            let is_singleton = editor.is_singleton(cx);
1773
1774            let highlighted_rows = editor.highlighted_rows();
1775            let highlighted_ranges = editor.background_highlights_in_range(
1776                start_anchor..end_anchor,
1777                &snapshot.display_snapshot,
1778                cx.theme().colors(),
1779            );
1780
1781            let mut newest_selection_head = None;
1782
1783            if editor.show_local_selections {
1784                let mut local_selections: Vec<Selection<Point>> = editor
1785                    .selections
1786                    .disjoint_in_range(start_anchor..end_anchor, cx);
1787                local_selections.extend(editor.selections.pending(cx));
1788                let mut layouts = Vec::new();
1789                let newest = editor.selections.newest(cx);
1790                for selection in local_selections.drain(..) {
1791                    let is_empty = selection.start == selection.end;
1792                    let is_newest = selection == newest;
1793
1794                    let layout = SelectionLayout::new(
1795                        selection,
1796                        editor.selections.line_mode,
1797                        editor.cursor_shape,
1798                        &snapshot.display_snapshot,
1799                        is_newest,
1800                        true,
1801                    );
1802                    if is_newest {
1803                        newest_selection_head = Some(layout.head);
1804                    }
1805
1806                    for row in cmp::max(layout.active_rows.start, start_row)
1807                        ..=cmp::min(layout.active_rows.end, end_row)
1808                    {
1809                        let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
1810                        *contains_non_empty_selection |= !is_empty;
1811                    }
1812                    layouts.push(layout);
1813                }
1814
1815                selections.push((style.local_player, layouts));
1816            }
1817
1818            if let Some(collaboration_hub) = &editor.collaboration_hub {
1819                // When following someone, render the local selections in their color.
1820                if let Some(leader_id) = editor.leader_peer_id {
1821                    if let Some(collaborator) = collaboration_hub.collaborators(cx).get(&leader_id) {
1822                        if let Some(participant_index) = collaboration_hub
1823                            .user_participant_indices(cx)
1824                            .get(&collaborator.user_id)
1825                        {
1826                            if let Some((local_selection_style, _)) = selections.first_mut() {
1827                                *local_selection_style = cx
1828                                    .theme()
1829                                    .players()
1830                                    .color_for_participant(participant_index.0);
1831                            }
1832                        }
1833                    }
1834                }
1835
1836                let mut remote_selections = HashMap::default();
1837                for selection in snapshot.remote_selections_in_range(
1838                    &(start_anchor..end_anchor),
1839                    collaboration_hub.as_ref(),
1840                    cx,
1841                ) {
1842                    let selection_style = if let Some(participant_index) = selection.participant_index {
1843                        cx.theme()
1844                            .players()
1845                            .color_for_participant(participant_index.0)
1846                    } else {
1847                        cx.theme().players().absent()
1848                    };
1849
1850                    // Don't re-render the leader's selections, since the local selections
1851                    // match theirs.
1852                    if Some(selection.peer_id) == editor.leader_peer_id {
1853                        continue;
1854                    }
1855
1856                    remote_selections
1857                        .entry(selection.replica_id)
1858                        .or_insert((selection_style, Vec::new()))
1859                        .1
1860                        .push(SelectionLayout::new(
1861                            selection.selection,
1862                            selection.line_mode,
1863                            selection.cursor_shape,
1864                            &snapshot.display_snapshot,
1865                            false,
1866                            false,
1867                        ));
1868                }
1869
1870                selections.extend(remote_selections.into_values());
1871            }
1872
1873            let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
1874            let show_scrollbars = match scrollbar_settings.show {
1875                ShowScrollbar::Auto => {
1876                    // Git
1877                    (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_git_diffs())
1878                    ||
1879                    // Selections
1880                    (is_singleton && scrollbar_settings.selections && !highlighted_ranges.is_empty())
1881                    // Scrollmanager
1882                    || editor.scroll_manager.scrollbars_visible()
1883                }
1884                ShowScrollbar::System => editor.scroll_manager.scrollbars_visible(),
1885                ShowScrollbar::Always => true,
1886                ShowScrollbar::Never => false,
1887            };
1888
1889            let head_for_relative = newest_selection_head.unwrap_or_else(|| {
1890                let newest = editor.selections.newest::<Point>(cx);
1891                SelectionLayout::new(
1892                    newest,
1893                    editor.selections.line_mode,
1894                    editor.cursor_shape,
1895                    &snapshot.display_snapshot,
1896                    true,
1897                    true,
1898                )
1899                .head
1900            });
1901
1902            let (line_numbers, fold_statuses) = self.shape_line_numbers(
1903                start_row..end_row,
1904                &active_rows,
1905                head_for_relative,
1906                is_singleton,
1907                &snapshot,
1908                cx,
1909            );
1910
1911            let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
1912
1913            let scrollbar_row_range = scroll_position.y..(scroll_position.y + height_in_lines);
1914
1915            let mut max_visible_line_width = Pixels::ZERO;
1916            let line_layouts = self.layout_lines(start_row..end_row, &line_numbers, &snapshot, cx);
1917            for line_with_invisibles in &line_layouts {
1918                if line_with_invisibles.line.width > max_visible_line_width {
1919                    max_visible_line_width = line_with_invisibles.line.width;
1920                }
1921            }
1922
1923            let longest_line_width = layout_line(snapshot.longest_row(), &snapshot, &style, cx)
1924                .unwrap()
1925                .width;
1926            let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.width;
1927
1928            let (scroll_width, blocks) = cx.with_element_id(Some("editor_blocks"), |cx| {
1929                self.layout_blocks(
1930                    start_row..end_row,
1931                    &snapshot,
1932                    bounds.size.width,
1933                    scroll_width,
1934                    gutter_padding,
1935                    gutter_width,
1936                    em_width,
1937                    gutter_width + gutter_margin,
1938                    line_height,
1939                    &style,
1940                    &line_layouts,
1941                    editor,
1942                    cx,
1943                )
1944            });
1945
1946            let scroll_max = point(
1947                f32::from((scroll_width - text_size.width) / em_width).max(0.0),
1948                max_row as f32,
1949            );
1950
1951            let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
1952
1953            let autoscrolled = if autoscroll_horizontally {
1954                editor.autoscroll_horizontally(
1955                    start_row,
1956                    text_size.width,
1957                    scroll_width,
1958                    em_width,
1959                    &line_layouts,
1960                    cx,
1961                )
1962            } else {
1963                false
1964            };
1965
1966            if clamped || autoscrolled {
1967                snapshot = editor.snapshot(cx);
1968            }
1969
1970            let mut context_menu = None;
1971            let mut code_actions_indicator = None;
1972            if let Some(newest_selection_head) = newest_selection_head {
1973                if (start_row..end_row).contains(&newest_selection_head.row()) {
1974                    if editor.context_menu_visible() {
1975                        let max_height = (12. * line_height).min((bounds.size.height - line_height) / 2.);
1976                        context_menu =
1977                            editor.render_context_menu(newest_selection_head, &self.style, max_height, cx);
1978                    }
1979
1980                    let active = matches!(
1981                        editor.context_menu.read().as_ref(),
1982                        Some(crate::ContextMenu::CodeActions(_))
1983                    );
1984
1985                    code_actions_indicator = editor
1986                        .render_code_actions_indicator(&style, active, cx)
1987                        .map(|element| CodeActionsIndicator {
1988                            row: newest_selection_head.row(),
1989                            button: element,
1990                        });
1991                }
1992            }
1993
1994            let visible_rows = start_row..start_row + line_layouts.len() as u32;
1995            // todo!("hover")
1996            // let mut hover = editor.hover_state.render(
1997            //     &snapshot,
1998            //     &style,
1999            //     visible_rows,
2000            //     editor.workspace.as_ref().map(|(w, _)| w.clone()),
2001            //     cx,
2002            // );
2003            // let mode = editor.mode;
2004
2005            let mut fold_indicators = cx.with_element_id(Some("gutter_fold_indicators"), |cx| {
2006                editor.render_fold_indicators(
2007                    fold_statuses,
2008                    &style,
2009                    editor.gutter_hovered,
2010                    line_height,
2011                    gutter_margin,
2012                    cx,
2013                )
2014            });
2015
2016            // todo!("hover popovers")
2017            // if let Some((_, hover_popovers)) = hover.as_mut() {
2018            //     for hover_popover in hover_popovers.iter_mut() {
2019            //         hover_popover.layout(
2020            //             SizeConstraint {
2021            //                 min: gpui::Point::<Pixels>::zero(),
2022            //                 max: point(
2023            //                     (120. * em_width) // Default size
2024            //                         .min(size.x / 2.) // Shrink to half of the editor width
2025            //                         .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2026            //                     (16. * line_height) // Default size
2027            //                         .min(size.y / 2.) // Shrink to half of the editor height
2028            //                         .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2029            //                 ),
2030            //             },
2031            //             editor,
2032            //             cx,
2033            //         );
2034            //     }
2035            // }
2036
2037            let invisible_symbol_font_size = font_size / 2.;
2038            let tab_invisible = cx
2039                .text_system()
2040                .shape_line(
2041                    "".into(),
2042                    invisible_symbol_font_size,
2043                    &[TextRun {
2044                        len: "".len(),
2045                        font: self.style.text.font(),
2046                        color: cx.theme().colors().editor_invisible,
2047                        background_color: None,
2048                        underline: None,
2049                    }],
2050                )
2051                .unwrap();
2052            let space_invisible = cx
2053                .text_system()
2054                .shape_line(
2055                    "".into(),
2056                    invisible_symbol_font_size,
2057                    &[TextRun {
2058                        len: "".len(),
2059                        font: self.style.text.font(),
2060                        color: cx.theme().colors().editor_invisible,
2061                        background_color: None,
2062                        underline: None,
2063                    }],
2064                )
2065                .unwrap();
2066
2067            LayoutState {
2068                mode: editor_mode,
2069                position_map: Arc::new(PositionMap {
2070                    size: bounds.size,
2071                    scroll_position: point(
2072                        scroll_position.x * em_width,
2073                        scroll_position.y * line_height,
2074                    ),
2075                    scroll_max,
2076                    line_layouts,
2077                    line_height,
2078                    em_width,
2079                    em_advance,
2080                    snapshot,
2081                }),
2082                visible_anchor_range: start_anchor..end_anchor,
2083                visible_display_row_range: start_row..end_row,
2084                wrap_guides,
2085                gutter_size,
2086                gutter_padding,
2087                text_size,
2088                scrollbar_row_range,
2089                show_scrollbars,
2090                is_singleton,
2091                max_row,
2092                gutter_margin,
2093                active_rows,
2094                highlighted_rows,
2095                highlighted_ranges,
2096                line_numbers,
2097                display_hunks,
2098                blocks,
2099                selections,
2100                context_menu,
2101                code_actions_indicator,
2102                fold_indicators,
2103                tab_invisible,
2104                space_invisible,
2105                // hover_popovers: hover,
2106            }
2107        })
2108    }
2109
2110    #[allow(clippy::too_many_arguments)]
2111    fn layout_blocks(
2112        &self,
2113        rows: Range<u32>,
2114        snapshot: &EditorSnapshot,
2115        editor_width: Pixels,
2116        scroll_width: Pixels,
2117        gutter_padding: Pixels,
2118        gutter_width: Pixels,
2119        em_width: Pixels,
2120        text_x: Pixels,
2121        line_height: Pixels,
2122        style: &EditorStyle,
2123        line_layouts: &[LineWithInvisibles],
2124        editor: &mut Editor,
2125        cx: &mut ViewContext<Editor>,
2126    ) -> (Pixels, Vec<BlockLayout>) {
2127        let mut block_id = 0;
2128        let scroll_x = snapshot.scroll_anchor.offset.x;
2129        let (fixed_blocks, non_fixed_blocks) = snapshot
2130            .blocks_in_range(rows.clone())
2131            .partition::<Vec<_>, _>(|(_, block)| match block {
2132                TransformBlock::ExcerptHeader { .. } => false,
2133                TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
2134            });
2135
2136        let mut render_block = |block: &TransformBlock,
2137                                available_space: Size<AvailableSpace>,
2138                                block_id: usize,
2139                                editor: &mut Editor,
2140                                cx: &mut ViewContext<Editor>| {
2141            let mut element = match block {
2142                TransformBlock::Custom(block) => {
2143                    let align_to = block
2144                        .position()
2145                        .to_point(&snapshot.buffer_snapshot)
2146                        .to_display_point(snapshot);
2147                    let anchor_x = text_x
2148                        + if rows.contains(&align_to.row()) {
2149                            line_layouts[(align_to.row() - rows.start) as usize]
2150                                .line
2151                                .x_for_index(align_to.column() as usize)
2152                        } else {
2153                            layout_line(align_to.row(), snapshot, style, cx)
2154                                .unwrap()
2155                                .x_for_index(align_to.column() as usize)
2156                        };
2157
2158                    block.render(&mut BlockContext {
2159                        view_context: cx,
2160                        anchor_x,
2161                        gutter_padding,
2162                        line_height,
2163                        gutter_width,
2164                        em_width,
2165                        block_id,
2166                        editor_style: &self.style,
2167                    })
2168                }
2169
2170                TransformBlock::ExcerptHeader {
2171                    buffer,
2172                    range,
2173                    starts_new_buffer,
2174                    ..
2175                } => {
2176                    let include_root = editor
2177                        .project
2178                        .as_ref()
2179                        .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
2180                        .unwrap_or_default();
2181                    let jump_icon = project::File::from_dyn(buffer.file()).map(|file| {
2182                        let jump_path = ProjectPath {
2183                            worktree_id: file.worktree_id(cx),
2184                            path: file.path.clone(),
2185                        };
2186                        let jump_anchor = range
2187                            .primary
2188                            .as_ref()
2189                            .map_or(range.context.start, |primary| primary.start);
2190                        let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
2191
2192                        IconButton::new(block_id, ui::Icon::ArrowUpRight)
2193                            .on_click(cx.listener_for(&self.editor, move |editor, e, cx| {
2194                                editor.jump(jump_path.clone(), jump_position, jump_anchor, cx);
2195                            }))
2196                            .tooltip(|cx| Tooltip::for_action("Jump to Buffer", &OpenExcerpts, cx))
2197                    });
2198
2199                    let element = if *starts_new_buffer {
2200                        let path = buffer.resolve_file_path(cx, include_root);
2201                        let mut filename = None;
2202                        let mut parent_path = None;
2203                        // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
2204                        if let Some(path) = path {
2205                            filename = path.file_name().map(|f| f.to_string_lossy().to_string());
2206                            parent_path = path
2207                                .parent()
2208                                .map(|p| SharedString::from(p.to_string_lossy().to_string() + "/"));
2209                        }
2210
2211                        h_stack()
2212                            .id("path header block")
2213                            .size_full()
2214                            .bg(gpui::red())
2215                            .child(
2216                                filename
2217                                    .map(SharedString::from)
2218                                    .unwrap_or_else(|| "untitled".into()),
2219                            )
2220                            .children(parent_path)
2221                            .children(jump_icon) // .p_x(gutter_padding)
2222                    } else {
2223                        let text_style = style.text.clone();
2224                        h_stack()
2225                            .id("collapsed context")
2226                            .size_full()
2227                            .bg(gpui::red())
2228                            .child("")
2229                            .children(jump_icon) // .p_x(gutter_padding)
2230                    };
2231                    element.into_any()
2232                }
2233            };
2234
2235            let size = element.measure(available_space, cx);
2236            (element, size)
2237        };
2238
2239        let mut fixed_block_max_width = Pixels::ZERO;
2240        let mut blocks = Vec::new();
2241        for (row, block) in fixed_blocks {
2242            let available_space = size(
2243                AvailableSpace::MinContent,
2244                AvailableSpace::Definite(block.height() as f32 * line_height),
2245            );
2246            let (element, element_size) =
2247                render_block(block, available_space, block_id, editor, cx);
2248            block_id += 1;
2249            fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
2250            blocks.push(BlockLayout {
2251                row,
2252                element,
2253                available_space,
2254                style: BlockStyle::Fixed,
2255            });
2256        }
2257        for (row, block) in non_fixed_blocks {
2258            let style = match block {
2259                TransformBlock::Custom(block) => block.style(),
2260                TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
2261            };
2262            let width = match style {
2263                BlockStyle::Sticky => editor_width,
2264                BlockStyle::Flex => editor_width
2265                    .max(fixed_block_max_width)
2266                    .max(gutter_width + scroll_width),
2267                BlockStyle::Fixed => unreachable!(),
2268            };
2269            let available_space = size(
2270                AvailableSpace::Definite(width),
2271                AvailableSpace::Definite(block.height() as f32 * line_height),
2272            );
2273            let (element, _) = render_block(block, available_space, block_id, editor, cx);
2274            block_id += 1;
2275            blocks.push(BlockLayout {
2276                row,
2277                element,
2278                available_space,
2279                style,
2280            });
2281        }
2282        (
2283            scroll_width.max(fixed_block_max_width - gutter_width),
2284            blocks,
2285        )
2286    }
2287
2288    fn paint_mouse_listeners(
2289        &mut self,
2290        bounds: Bounds<Pixels>,
2291        gutter_bounds: Bounds<Pixels>,
2292        text_bounds: Bounds<Pixels>,
2293        layout: &LayoutState,
2294        cx: &mut WindowContext,
2295    ) {
2296        let content_origin = text_bounds.origin + point(layout.gutter_margin, Pixels::ZERO);
2297
2298        cx.on_mouse_event({
2299            let position_map = layout.position_map.clone();
2300            let editor = self.editor.clone();
2301
2302            move |event: &ScrollWheelEvent, phase, cx| {
2303                if phase != DispatchPhase::Bubble {
2304                    return;
2305                }
2306
2307                let should_cancel = editor.update(cx, |editor, cx| {
2308                    Self::scroll(editor, event, &position_map, bounds, cx)
2309                });
2310                if should_cancel {
2311                    cx.stop_propagation();
2312                }
2313            }
2314        });
2315
2316        cx.on_mouse_event({
2317            let position_map = layout.position_map.clone();
2318            let editor = self.editor.clone();
2319
2320            move |event: &MouseDownEvent, phase, cx| {
2321                if phase != DispatchPhase::Bubble {
2322                    return;
2323                }
2324
2325                let should_cancel = editor.update(cx, |editor, cx| {
2326                    Self::mouse_down(editor, event, &position_map, text_bounds, gutter_bounds, cx)
2327                });
2328
2329                if should_cancel {
2330                    cx.stop_propagation()
2331                }
2332            }
2333        });
2334
2335        cx.on_mouse_event({
2336            let position_map = layout.position_map.clone();
2337            let editor = self.editor.clone();
2338            move |event: &MouseUpEvent, phase, cx| {
2339                let should_cancel = editor.update(cx, |editor, cx| {
2340                    Self::mouse_up(editor, event, &position_map, text_bounds, cx)
2341                });
2342
2343                if should_cancel {
2344                    cx.stop_propagation()
2345                }
2346            }
2347        });
2348        //todo!()
2349        // on_down(MouseButton::Right, {
2350        //     let position_map = layout.position_map.clone();
2351        //     move |event, editor, cx| {
2352        //         if !Self::mouse_right_down(
2353        //             editor,
2354        //             event.position,
2355        //             position_map.as_ref(),
2356        //             text_bounds,
2357        //             cx,
2358        //         ) {
2359        //             cx.propagate_event();
2360        //         }
2361        //     }
2362        // });
2363        cx.on_mouse_event({
2364            let position_map = layout.position_map.clone();
2365            let editor = self.editor.clone();
2366            move |event: &MouseMoveEvent, phase, cx| {
2367                if phase != DispatchPhase::Bubble {
2368                    return;
2369                }
2370
2371                let stop_propogating = editor.update(cx, |editor, cx| {
2372                    Self::mouse_moved(editor, event, &position_map, text_bounds, gutter_bounds, cx)
2373                });
2374
2375                if stop_propogating {
2376                    cx.stop_propagation()
2377                }
2378            }
2379        });
2380    }
2381}
2382
2383#[derive(Debug)]
2384pub struct LineWithInvisibles {
2385    pub line: ShapedLine,
2386    invisibles: Vec<Invisible>,
2387}
2388
2389impl LineWithInvisibles {
2390    fn from_chunks<'a>(
2391        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
2392        text_style: &TextStyle,
2393        max_line_len: usize,
2394        max_line_count: usize,
2395        line_number_layouts: &[Option<ShapedLine>],
2396        editor_mode: EditorMode,
2397        cx: &WindowContext,
2398    ) -> Vec<Self> {
2399        let mut layouts = Vec::with_capacity(max_line_count);
2400        let mut line = String::new();
2401        let mut invisibles = Vec::new();
2402        let mut styles = Vec::new();
2403        let mut non_whitespace_added = false;
2404        let mut row = 0;
2405        let mut line_exceeded_max_len = false;
2406        let font_size = text_style.font_size.to_pixels(cx.rem_size());
2407
2408        for highlighted_chunk in chunks.chain([HighlightedChunk {
2409            chunk: "\n",
2410            style: None,
2411            is_tab: false,
2412        }]) {
2413            for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
2414                if ix > 0 {
2415                    let shaped_line = cx
2416                        .text_system()
2417                        .shape_line(line.clone().into(), font_size, &styles)
2418                        .unwrap();
2419                    layouts.push(Self {
2420                        line: shaped_line,
2421                        invisibles: invisibles.drain(..).collect(),
2422                    });
2423
2424                    line.clear();
2425                    styles.clear();
2426                    row += 1;
2427                    line_exceeded_max_len = false;
2428                    non_whitespace_added = false;
2429                    if row == max_line_count {
2430                        return layouts;
2431                    }
2432                }
2433
2434                if !line_chunk.is_empty() && !line_exceeded_max_len {
2435                    let text_style = if let Some(style) = highlighted_chunk.style {
2436                        Cow::Owned(text_style.clone().highlight(style))
2437                    } else {
2438                        Cow::Borrowed(text_style)
2439                    };
2440
2441                    if line.len() + line_chunk.len() > max_line_len {
2442                        let mut chunk_len = max_line_len - line.len();
2443                        while !line_chunk.is_char_boundary(chunk_len) {
2444                            chunk_len -= 1;
2445                        }
2446                        line_chunk = &line_chunk[..chunk_len];
2447                        line_exceeded_max_len = true;
2448                    }
2449
2450                    styles.push(TextRun {
2451                        len: line_chunk.len(),
2452                        font: text_style.font(),
2453                        color: text_style.color,
2454                        background_color: text_style.background_color,
2455                        underline: text_style.underline,
2456                    });
2457
2458                    if editor_mode == EditorMode::Full {
2459                        // Line wrap pads its contents with fake whitespaces,
2460                        // avoid printing them
2461                        let inside_wrapped_string = line_number_layouts
2462                            .get(row)
2463                            .and_then(|layout| layout.as_ref())
2464                            .is_none();
2465                        if highlighted_chunk.is_tab {
2466                            if non_whitespace_added || !inside_wrapped_string {
2467                                invisibles.push(Invisible::Tab {
2468                                    line_start_offset: line.len(),
2469                                });
2470                            }
2471                        } else {
2472                            invisibles.extend(
2473                                line_chunk
2474                                    .chars()
2475                                    .enumerate()
2476                                    .filter(|(_, line_char)| {
2477                                        let is_whitespace = line_char.is_whitespace();
2478                                        non_whitespace_added |= !is_whitespace;
2479                                        is_whitespace
2480                                            && (non_whitespace_added || !inside_wrapped_string)
2481                                    })
2482                                    .map(|(whitespace_index, _)| Invisible::Whitespace {
2483                                        line_offset: line.len() + whitespace_index,
2484                                    }),
2485                            )
2486                        }
2487                    }
2488
2489                    line.push_str(line_chunk);
2490                }
2491            }
2492        }
2493
2494        layouts
2495    }
2496
2497    fn draw(
2498        &self,
2499        layout: &LayoutState,
2500        row: u32,
2501        content_origin: gpui::Point<Pixels>,
2502        whitespace_setting: ShowWhitespaceSetting,
2503        selection_ranges: &[Range<DisplayPoint>],
2504        cx: &mut WindowContext,
2505    ) {
2506        let line_height = layout.position_map.line_height;
2507        let line_y = line_height * row as f32 - layout.position_map.scroll_position.y;
2508
2509        self.line.paint(
2510            content_origin + gpui::point(-layout.position_map.scroll_position.x, line_y),
2511            line_height,
2512            cx,
2513        );
2514
2515        self.draw_invisibles(
2516            &selection_ranges,
2517            layout,
2518            content_origin,
2519            line_y,
2520            row,
2521            line_height,
2522            whitespace_setting,
2523            cx,
2524        );
2525    }
2526
2527    fn draw_invisibles(
2528        &self,
2529        selection_ranges: &[Range<DisplayPoint>],
2530        layout: &LayoutState,
2531        content_origin: gpui::Point<Pixels>,
2532        line_y: Pixels,
2533        row: u32,
2534        line_height: Pixels,
2535        whitespace_setting: ShowWhitespaceSetting,
2536        cx: &mut WindowContext,
2537    ) {
2538        let allowed_invisibles_regions = match whitespace_setting {
2539            ShowWhitespaceSetting::None => return,
2540            ShowWhitespaceSetting::Selection => Some(selection_ranges),
2541            ShowWhitespaceSetting::All => None,
2542        };
2543
2544        for invisible in &self.invisibles {
2545            let (&token_offset, invisible_symbol) = match invisible {
2546                Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
2547                Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
2548            };
2549
2550            let x_offset = self.line.x_for_index(token_offset);
2551            let invisible_offset =
2552                (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
2553            let origin = content_origin
2554                + gpui::point(
2555                    x_offset + invisible_offset - layout.position_map.scroll_position.x,
2556                    line_y,
2557                );
2558
2559            if let Some(allowed_regions) = allowed_invisibles_regions {
2560                let invisible_point = DisplayPoint::new(row, token_offset as u32);
2561                if !allowed_regions
2562                    .iter()
2563                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
2564                {
2565                    continue;
2566                }
2567            }
2568            invisible_symbol.paint(origin, line_height, cx);
2569        }
2570    }
2571}
2572
2573#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2574enum Invisible {
2575    Tab { line_start_offset: usize },
2576    Whitespace { line_offset: usize },
2577}
2578
2579impl Element for EditorElement {
2580    type State = ();
2581
2582    fn layout(
2583        &mut self,
2584        element_state: Option<Self::State>,
2585        cx: &mut gpui::WindowContext,
2586    ) -> (gpui::LayoutId, Self::State) {
2587        self.editor.update(cx, |editor, cx| {
2588            editor.style = Some(self.style.clone()); // Long-term, we'd like to eliminate this.
2589
2590            let rem_size = cx.rem_size();
2591            let mut style = Style::default();
2592            style.size.width = relative(1.).into();
2593            style.size.height = match editor.mode {
2594                EditorMode::SingleLine => {
2595                    self.style.text.line_height_in_pixels(cx.rem_size()).into()
2596                }
2597                EditorMode::AutoHeight { .. } => todo!(),
2598                EditorMode::Full => relative(1.).into(),
2599            };
2600            let layout_id = cx.request_layout(&style, None);
2601
2602            (layout_id, ())
2603        })
2604    }
2605
2606    fn paint(
2607        mut self,
2608        bounds: Bounds<gpui::Pixels>,
2609        element_state: &mut Self::State,
2610        cx: &mut gpui::WindowContext,
2611    ) {
2612        let editor = self.editor.clone();
2613
2614        let mut layout = self.compute_layout(bounds, cx);
2615        let gutter_bounds = Bounds {
2616            origin: bounds.origin,
2617            size: layout.gutter_size,
2618        };
2619        let text_bounds = Bounds {
2620            origin: gutter_bounds.upper_right(),
2621            size: layout.text_size,
2622        };
2623
2624        let focus_handle = editor.focus_handle(cx);
2625        let dispatch_context = self.editor.read(cx).dispatch_context(cx);
2626        cx.with_key_dispatch(dispatch_context, Some(focus_handle.clone()), |_, cx| {
2627            self.register_actions(cx);
2628
2629            // We call with_z_index to establish a new stacking context.
2630            cx.with_z_index(0, |cx| {
2631                cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
2632                    // Paint mouse listeners first, so any elements we paint on top of the editor
2633                    // take precedence.
2634                    self.paint_mouse_listeners(bounds, gutter_bounds, text_bounds, &layout, cx);
2635                    let input_handler = ElementInputHandler::new(bounds, self.editor.clone(), cx);
2636                    cx.handle_input(&focus_handle, input_handler);
2637
2638                    self.paint_background(gutter_bounds, text_bounds, &layout, cx);
2639                    if layout.gutter_size.width > Pixels::ZERO {
2640                        self.paint_gutter(gutter_bounds, &mut layout, cx);
2641                    }
2642                    self.paint_text(text_bounds, &mut layout, cx);
2643
2644                    if !layout.blocks.is_empty() {
2645                        cx.with_element_id(Some("editor_blocks"), |cx| {
2646                            self.paint_blocks(bounds, &mut layout, cx);
2647                        })
2648                    }
2649                });
2650            });
2651        })
2652    }
2653}
2654
2655impl IntoElement for EditorElement {
2656    type Element = Self;
2657
2658    fn element_id(&self) -> Option<gpui::ElementId> {
2659        self.editor.element_id()
2660    }
2661
2662    fn into_element(self) -> Self::Element {
2663        self
2664    }
2665}
2666
2667// impl EditorElement {
2668//     type LayoutState = LayoutState;
2669//     type PaintState = ();
2670
2671//     fn layout(
2672//         &mut self,
2673//         constraint: SizeConstraint,
2674//         editor: &mut Editor,
2675//         cx: &mut ViewContext<Editor>,
2676//     ) -> (gpui::Point<Pixels>, Self::LayoutState) {
2677//         let mut size = constraint.max;
2678//         if size.x.is_infinite() {
2679//             unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
2680//         }
2681
2682//         let snapshot = editor.snapshot(cx);
2683//         let style = self.style.clone();
2684
2685//         let line_height = (style.text.font_size * style.line_height_scalar).round();
2686
2687//         let gutter_padding;
2688//         let gutter_width;
2689//         let gutter_margin;
2690//         if snapshot.show_gutter {
2691//             let em_width = style.text.em_width(cx.font_cache());
2692//             gutter_padding = (em_width * style.gutter_padding_factor).round();
2693//             gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
2694//             gutter_margin = -style.text.descent(cx.font_cache());
2695//         } else {
2696//             gutter_padding = 0.0;
2697//             gutter_width = 0.0;
2698//             gutter_margin = 0.0;
2699//         };
2700
2701//         let text_width = size.x - gutter_width;
2702//         let em_width = style.text.em_width(cx.font_cache());
2703//         let em_advance = style.text.em_advance(cx.font_cache());
2704//         let overscroll = point(em_width, 0.);
2705//         let snapshot = {
2706//             editor.set_visible_line_count(size.y / line_height, cx);
2707
2708//             let editor_width = text_width - gutter_margin - overscroll.x - em_width;
2709//             let wrap_width = match editor.soft_wrap_mode(cx) {
2710//                 SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
2711//                 SoftWrap::EditorWidth => editor_width,
2712//                 SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
2713//             };
2714
2715//             if editor.set_wrap_width(Some(wrap_width), cx) {
2716//                 editor.snapshot(cx)
2717//             } else {
2718//                 snapshot
2719//             }
2720//         };
2721
2722//         let wrap_guides = editor
2723//             .wrap_guides(cx)
2724//             .iter()
2725//             .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
2726//             .collect();
2727
2728//         let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
2729//         if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
2730//             size.set_y(
2731//                 scroll_height
2732//                     .min(constraint.max_along(Axis::Vertical))
2733//                     .max(constraint.min_along(Axis::Vertical))
2734//                     .max(line_height)
2735//                     .min(line_height * max_lines as f32),
2736//             )
2737//         } else if let EditorMode::SingleLine = snapshot.mode {
2738//             size.set_y(line_height.max(constraint.min_along(Axis::Vertical)))
2739//         } else if size.y.is_infinite() {
2740//             size.set_y(scroll_height);
2741//         }
2742//         let gutter_size = point(gutter_width, size.y);
2743//         let text_size = point(text_width, size.y);
2744
2745//         let autoscroll_horizontally = editor.autoscroll_vertically(size.y, line_height, cx);
2746//         let mut snapshot = editor.snapshot(cx);
2747
2748//         let scroll_position = snapshot.scroll_position();
2749//         // The scroll position is a fractional point, the whole number of which represents
2750//         // the top of the window in terms of display rows.
2751//         let start_row = scroll_position.y as u32;
2752//         let height_in_lines = size.y / line_height;
2753//         let max_row = snapshot.max_point().row();
2754
2755//         // Add 1 to ensure selections bleed off screen
2756//         let end_row = 1 + cmp::min(
2757//             (scroll_position.y + height_in_lines).ceil() as u32,
2758//             max_row,
2759//         );
2760
2761//         let start_anchor = if start_row == 0 {
2762//             Anchor::min()
2763//         } else {
2764//             snapshot
2765//                 .buffer_snapshot
2766//                 .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
2767//         };
2768//         let end_anchor = if end_row > max_row {
2769//             Anchor::max
2770//         } else {
2771//             snapshot
2772//                 .buffer_snapshot
2773//                 .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
2774//         };
2775
2776//         let mut selections: Vec<(SelectionStyle, Vec<SelectionLayout>)> = Vec::new();
2777//         let mut active_rows = BTreeMap::new();
2778//         let mut fold_ranges = Vec::new();
2779//         let is_singleton = editor.is_singleton(cx);
2780
2781//         let highlighted_rows = editor.highlighted_rows();
2782//         let theme = theme::current(cx);
2783//         let highlighted_ranges = editor.background_highlights_in_range(
2784//             start_anchor..end_anchor,
2785//             &snapshot.display_snapshot,
2786//             theme.as_ref(),
2787//         );
2788
2789//         fold_ranges.extend(
2790//             snapshot
2791//                 .folds_in_range(start_anchor..end_anchor)
2792//                 .map(|anchor| {
2793//                     let start = anchor.start.to_point(&snapshot.buffer_snapshot);
2794//                     (
2795//                         start.row,
2796//                         start.to_display_point(&snapshot.display_snapshot)
2797//                             ..anchor.end.to_display_point(&snapshot),
2798//                     )
2799//                 }),
2800//         );
2801
2802//         let mut newest_selection_head = None;
2803
2804//         if editor.show_local_selections {
2805//             let mut local_selections: Vec<Selection<Point>> = editor
2806//                 .selections
2807//                 .disjoint_in_range(start_anchor..end_anchor, cx);
2808//             local_selections.extend(editor.selections.pending(cx));
2809//             let mut layouts = Vec::new();
2810//             let newest = editor.selections.newest(cx);
2811//             for selection in local_selections.drain(..) {
2812//                 let is_empty = selection.start == selection.end;
2813//                 let is_newest = selection == newest;
2814
2815//                 let layout = SelectionLayout::new(
2816//                     selection,
2817//                     editor.selections.line_mode,
2818//                     editor.cursor_shape,
2819//                     &snapshot.display_snapshot,
2820//                     is_newest,
2821//                     true,
2822//                 );
2823//                 if is_newest {
2824//                     newest_selection_head = Some(layout.head);
2825//                 }
2826
2827//                 for row in cmp::max(layout.active_rows.start, start_row)
2828//                     ..=cmp::min(layout.active_rows.end, end_row)
2829//                 {
2830//                     let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
2831//                     *contains_non_empty_selection |= !is_empty;
2832//                 }
2833//                 layouts.push(layout);
2834//             }
2835
2836//             selections.push((style.selection, layouts));
2837//         }
2838
2839//         if let Some(collaboration_hub) = &editor.collaboration_hub {
2840//             // When following someone, render the local selections in their color.
2841//             if let Some(leader_id) = editor.leader_peer_id {
2842//                 if let Some(collaborator) = collaboration_hub.collaborators(cx).get(&leader_id) {
2843//                     if let Some(participant_index) = collaboration_hub
2844//                         .user_participant_indices(cx)
2845//                         .get(&collaborator.user_id)
2846//                     {
2847//                         if let Some((local_selection_style, _)) = selections.first_mut() {
2848//                             *local_selection_style =
2849//                                 style.selection_style_for_room_participant(participant_index.0);
2850//                         }
2851//                     }
2852//                 }
2853//             }
2854
2855//             let mut remote_selections = HashMap::default();
2856//             for selection in snapshot.remote_selections_in_range(
2857//                 &(start_anchor..end_anchor),
2858//                 collaboration_hub.as_ref(),
2859//                 cx,
2860//             ) {
2861//                 let selection_style = if let Some(participant_index) = selection.participant_index {
2862//                     style.selection_style_for_room_participant(participant_index.0)
2863//                 } else {
2864//                     style.absent_selection
2865//                 };
2866
2867//                 // Don't re-render the leader's selections, since the local selections
2868//                 // match theirs.
2869//                 if Some(selection.peer_id) == editor.leader_peer_id {
2870//                     continue;
2871//                 }
2872
2873//                 remote_selections
2874//                     .entry(selection.replica_id)
2875//                     .or_insert((selection_style, Vec::new()))
2876//                     .1
2877//                     .push(SelectionLayout::new(
2878//                         selection.selection,
2879//                         selection.line_mode,
2880//                         selection.cursor_shape,
2881//                         &snapshot.display_snapshot,
2882//                         false,
2883//                         false,
2884//                     ));
2885//             }
2886
2887//             selections.extend(remote_selections.into_values());
2888//         }
2889
2890//         let scrollbar_settings = &settings::get::<EditorSettings>(cx).scrollbar;
2891//         let show_scrollbars = match scrollbar_settings.show {
2892//             ShowScrollbar::Auto => {
2893//                 // Git
2894//                 (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_git_diffs())
2895//                 ||
2896//                 // Selections
2897//                 (is_singleton && scrollbar_settings.selections && !highlighted_ranges.is_empty)
2898//                 // Scrollmanager
2899//                 || editor.scroll_manager.scrollbars_visible()
2900//             }
2901//             ShowScrollbar::System => editor.scroll_manager.scrollbars_visible(),
2902//             ShowScrollbar::Always => true,
2903//             ShowScrollbar::Never => false,
2904//         };
2905
2906//         let fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)> = fold_ranges
2907//             .into_iter()
2908//             .map(|(id, fold)| {
2909//                 let color = self
2910//                     .style
2911//                     .folds
2912//                     .ellipses
2913//                     .background
2914//                     .style_for(&mut cx.mouse_state::<FoldMarkers>(id as usize))
2915//                     .color;
2916
2917//                 (id, fold, color)
2918//             })
2919//             .collect();
2920
2921//         let head_for_relative = newest_selection_head.unwrap_or_else(|| {
2922//             let newest = editor.selections.newest::<Point>(cx);
2923//             SelectionLayout::new(
2924//                 newest,
2925//                 editor.selections.line_mode,
2926//                 editor.cursor_shape,
2927//                 &snapshot.display_snapshot,
2928//                 true,
2929//                 true,
2930//             )
2931//             .head
2932//         });
2933
2934//         let (line_number_layouts, fold_statuses) = self.layout_line_numbers(
2935//             start_row..end_row,
2936//             &active_rows,
2937//             head_for_relative,
2938//             is_singleton,
2939//             &snapshot,
2940//             cx,
2941//         );
2942
2943//         let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
2944
2945//         let scrollbar_row_range = scroll_position.y..(scroll_position.y + height_in_lines);
2946
2947//         let mut max_visible_line_width = 0.0;
2948//         let line_layouts =
2949//             self.layout_lines(start_row..end_row, &line_number_layouts, &snapshot, cx);
2950//         for line_with_invisibles in &line_layouts {
2951//             if line_with_invisibles.line.width() > max_visible_line_width {
2952//                 max_visible_line_width = line_with_invisibles.line.width();
2953//             }
2954//         }
2955
2956//         let style = self.style.clone();
2957//         let longest_line_width = layout_line(
2958//             snapshot.longest_row(),
2959//             &snapshot,
2960//             &style,
2961//             cx.text_layout_cache(),
2962//         )
2963//         .width();
2964//         let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x;
2965//         let em_width = style.text.em_width(cx.font_cache());
2966//         let (scroll_width, blocks) = self.layout_blocks(
2967//             start_row..end_row,
2968//             &snapshot,
2969//             size.x,
2970//             scroll_width,
2971//             gutter_padding,
2972//             gutter_width,
2973//             em_width,
2974//             gutter_width + gutter_margin,
2975//             line_height,
2976//             &style,
2977//             &line_layouts,
2978//             editor,
2979//             cx,
2980//         );
2981
2982//         let scroll_max = point(
2983//             ((scroll_width - text_size.x) / em_width).max(0.0),
2984//             max_row as f32,
2985//         );
2986
2987//         let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
2988
2989//         let autoscrolled = if autoscroll_horizontally {
2990//             editor.autoscroll_horizontally(
2991//                 start_row,
2992//                 text_size.x,
2993//                 scroll_width,
2994//                 em_width,
2995//                 &line_layouts,
2996//                 cx,
2997//             )
2998//         } else {
2999//             false
3000//         };
3001
3002//         if clamped || autoscrolled {
3003//             snapshot = editor.snapshot(cx);
3004//         }
3005
3006//         let style = editor.style(cx);
3007
3008//         let mut context_menu = None;
3009//         let mut code_actions_indicator = None;
3010//         if let Some(newest_selection_head) = newest_selection_head {
3011//             if (start_row..end_row).contains(&newest_selection_head.row()) {
3012//                 if editor.context_menu_visible() {
3013//                     context_menu =
3014//                         editor.render_context_menu(newest_selection_head, style.clone(), cx);
3015//                 }
3016
3017//                 let active = matches!(
3018//                     editor.context_menu.read().as_ref(),
3019//                     Some(crate::ContextMenu::CodeActions(_))
3020//                 );
3021
3022//                 code_actions_indicator = editor
3023//                     .render_code_actions_indicator(&style, active, cx)
3024//                     .map(|indicator| (newest_selection_head.row(), indicator));
3025//             }
3026//         }
3027
3028//         let visible_rows = start_row..start_row + line_layouts.len() as u32;
3029//         let mut hover = editor.hover_state.render(
3030//             &snapshot,
3031//             &style,
3032//             visible_rows,
3033//             editor.workspace.as_ref().map(|(w, _)| w.clone()),
3034//             cx,
3035//         );
3036//         let mode = editor.mode;
3037
3038//         let mut fold_indicators = editor.render_fold_indicators(
3039//             fold_statuses,
3040//             &style,
3041//             editor.gutter_hovered,
3042//             line_height,
3043//             gutter_margin,
3044//             cx,
3045//         );
3046
3047//         if let Some((_, context_menu)) = context_menu.as_mut() {
3048//             context_menu.layout(
3049//                 SizeConstraint {
3050//                     min: gpui::Point::<Pixels>::zero(),
3051//                     max: point(
3052//                         cx.window_size().x * 0.7,
3053//                         (12. * line_height).min((size.y - line_height) / 2.),
3054//                     ),
3055//                 },
3056//                 editor,
3057//                 cx,
3058//             );
3059//         }
3060
3061//         if let Some((_, indicator)) = code_actions_indicator.as_mut() {
3062//             indicator.layout(
3063//                 SizeConstraint::strict_along(
3064//                     Axis::Vertical,
3065//                     line_height * style.code_actions.vertical_scale,
3066//                 ),
3067//                 editor,
3068//                 cx,
3069//             );
3070//         }
3071
3072//         for fold_indicator in fold_indicators.iter_mut() {
3073//             if let Some(indicator) = fold_indicator.as_mut() {
3074//                 indicator.layout(
3075//                     SizeConstraint::strict_along(
3076//                         Axis::Vertical,
3077//                         line_height * style.code_actions.vertical_scale,
3078//                     ),
3079//                     editor,
3080//                     cx,
3081//                 );
3082//             }
3083//         }
3084
3085//         if let Some((_, hover_popovers)) = hover.as_mut() {
3086//             for hover_popover in hover_popovers.iter_mut() {
3087//                 hover_popover.layout(
3088//                     SizeConstraint {
3089//                         min: gpui::Point::<Pixels>::zero(),
3090//                         max: point(
3091//                             (120. * em_width) // Default size
3092//                                 .min(size.x / 2.) // Shrink to half of the editor width
3093//                                 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
3094//                             (16. * line_height) // Default size
3095//                                 .min(size.y / 2.) // Shrink to half of the editor height
3096//                                 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
3097//                         ),
3098//                     },
3099//                     editor,
3100//                     cx,
3101//                 );
3102//             }
3103//         }
3104
3105//         let invisible_symbol_font_size = self.style.text.font_size / 2.0;
3106//         let invisible_symbol_style = RunStyle {
3107//             color: self.style.whitespace,
3108//             font_id: self.style.text.font_id,
3109//             underline: Default::default(),
3110//         };
3111
3112//         (
3113//             size,
3114//             LayoutState {
3115//                 mode,
3116//                 position_map: Arc::new(PositionMap {
3117//                     size,
3118//                     scroll_max,
3119//                     line_layouts,
3120//                     line_height,
3121//                     em_width,
3122//                     em_advance,
3123//                     snapshot,
3124//                 }),
3125//                 visible_display_row_range: start_row..end_row,
3126//                 wrap_guides,
3127//                 gutter_size,
3128//                 gutter_padding,
3129//                 text_size,
3130//                 scrollbar_row_range,
3131//                 show_scrollbars,
3132//                 is_singleton,
3133//                 max_row,
3134//                 gutter_margin,
3135//                 active_rows,
3136//                 highlighted_rows,
3137//                 highlighted_ranges,
3138//                 fold_ranges,
3139//                 line_number_layouts,
3140//                 display_hunks,
3141//                 blocks,
3142//                 selections,
3143//                 context_menu,
3144//                 code_actions_indicator,
3145//                 fold_indicators,
3146//                 tab_invisible: cx.text_layout_cache().layout_str(
3147//                     "→",
3148//                     invisible_symbol_font_size,
3149//                     &[("→".len(), invisible_symbol_style)],
3150//                 ),
3151//                 space_invisible: cx.text_layout_cache().layout_str(
3152//                     "•",
3153//                     invisible_symbol_font_size,
3154//                     &[("•".len(), invisible_symbol_style)],
3155//                 ),
3156//                 hover_popovers: hover,
3157//             },
3158//         )
3159//     }
3160
3161//     fn paint(
3162//         &mut self,
3163//         bounds: Bounds<Pixels>,
3164//         visible_bounds: Bounds<Pixels>,
3165//         layout: &mut Self::LayoutState,
3166//         editor: &mut Editor,
3167//         cx: &mut ViewContext<Editor>,
3168//     ) -> Self::PaintState {
3169//         let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
3170//         cx.scene().push_layer(Some(visible_bounds));
3171
3172//         let gutter_bounds = Bounds::<Pixels>::new(bounds.origin, layout.gutter_size);
3173//         let text_bounds = Bounds::<Pixels>::new(
3174//             bounds.origin + point(layout.gutter_size.x, 0.0),
3175//             layout.text_size,
3176//         );
3177
3178//         Self::attach_mouse_handlers(
3179//             &layout.position_map,
3180//             layout.hover_popovers.is_some(),
3181//             visible_bounds,
3182//             text_bounds,
3183//             gutter_bounds,
3184//             bounds,
3185//             cx,
3186//         );
3187
3188//         self.paint_background(gutter_bounds, text_bounds, layout, cx);
3189//         if layout.gutter_size.x > 0. {
3190//             self.paint_gutter(gutter_bounds, visible_bounds, layout, editor, cx);
3191//         }
3192//         self.paint_text(text_bounds, visible_bounds, layout, editor, cx);
3193
3194//         cx.scene().push_layer(Some(bounds));
3195//         if !layout.blocks.is_empty {
3196//             self.paint_blocks(bounds, visible_bounds, layout, editor, cx);
3197//         }
3198//         self.paint_scrollbar(bounds, layout, &editor, cx);
3199//         cx.scene().pop_layer();
3200//         cx.scene().pop_layer();
3201//     }
3202
3203//     fn rect_for_text_range(
3204//         &self,
3205//         range_utf16: Range<usize>,
3206//         bounds: Bounds<Pixels>,
3207//         _: Bounds<Pixels>,
3208//         layout: &Self::LayoutState,
3209//         _: &Self::PaintState,
3210//         _: &Editor,
3211//         _: &ViewContext<Editor>,
3212//     ) -> Option<Bounds<Pixels>> {
3213//         let text_bounds = Bounds::<Pixels>::new(
3214//             bounds.origin + point(layout.gutter_size.x, 0.0),
3215//             layout.text_size,
3216//         );
3217//         let content_origin = text_bounds.origin + point(layout.gutter_margin, 0.);
3218//         let scroll_position = layout.position_map.snapshot.scroll_position();
3219//         let start_row = scroll_position.y as u32;
3220//         let scroll_top = scroll_position.y * layout.position_map.line_height;
3221//         let scroll_left = scroll_position.x * layout.position_map.em_width;
3222
3223//         let range_start = OffsetUtf16(range_utf16.start)
3224//             .to_display_point(&layout.position_map.snapshot.display_snapshot);
3225//         if range_start.row() < start_row {
3226//             return None;
3227//         }
3228
3229//         let line = &layout
3230//             .position_map
3231//             .line_layouts
3232//             .get((range_start.row() - start_row) as usize)?
3233//             .line;
3234//         let range_start_x = line.x_for_index(range_start.column() as usize);
3235//         let range_start_y = range_start.row() as f32 * layout.position_map.line_height;
3236//         Some(Bounds::<Pixels>::new(
3237//             content_origin
3238//                 + point(
3239//                     range_start_x,
3240//                     range_start_y + layout.position_map.line_height,
3241//                 )
3242//                 - point(scroll_left, scroll_top),
3243//             point(
3244//                 layout.position_map.em_width,
3245//                 layout.position_map.line_height,
3246//             ),
3247//         ))
3248//     }
3249
3250//     fn debug(
3251//         &self,
3252//         bounds: Bounds<Pixels>,
3253//         _: &Self::LayoutState,
3254//         _: &Self::PaintState,
3255//         _: &Editor,
3256//         _: &ViewContext<Editor>,
3257//     ) -> json::Value {
3258//         json!({
3259//             "type": "BufferElement",
3260//             "bounds": bounds.to_json()
3261//         })
3262//     }
3263// }
3264
3265type BufferRow = u32;
3266
3267pub struct LayoutState {
3268    position_map: Arc<PositionMap>,
3269    gutter_size: Size<Pixels>,
3270    gutter_padding: Pixels,
3271    gutter_margin: Pixels,
3272    text_size: gpui::Size<Pixels>,
3273    mode: EditorMode,
3274    wrap_guides: SmallVec<[(Pixels, bool); 2]>,
3275    visible_anchor_range: Range<Anchor>,
3276    visible_display_row_range: Range<u32>,
3277    active_rows: BTreeMap<u32, bool>,
3278    highlighted_rows: Option<Range<u32>>,
3279    line_numbers: Vec<Option<ShapedLine>>,
3280    display_hunks: Vec<DisplayDiffHunk>,
3281    blocks: Vec<BlockLayout>,
3282    highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
3283    selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
3284    scrollbar_row_range: Range<f32>,
3285    show_scrollbars: bool,
3286    is_singleton: bool,
3287    max_row: u32,
3288    context_menu: Option<(DisplayPoint, AnyElement)>,
3289    code_actions_indicator: Option<CodeActionsIndicator>,
3290    // hover_popovers: Option<(DisplayPoint, Vec<AnyElement>)>,
3291    fold_indicators: Vec<Option<IconButton>>,
3292    tab_invisible: ShapedLine,
3293    space_invisible: ShapedLine,
3294}
3295
3296struct CodeActionsIndicator {
3297    row: u32,
3298    button: IconButton,
3299}
3300
3301struct PositionMap {
3302    size: Size<Pixels>,
3303    line_height: Pixels,
3304    scroll_position: gpui::Point<Pixels>,
3305    scroll_max: gpui::Point<f32>,
3306    em_width: Pixels,
3307    em_advance: Pixels,
3308    line_layouts: Vec<LineWithInvisibles>,
3309    snapshot: EditorSnapshot,
3310}
3311
3312#[derive(Debug, Copy, Clone)]
3313pub struct PointForPosition {
3314    pub previous_valid: DisplayPoint,
3315    pub next_valid: DisplayPoint,
3316    pub exact_unclipped: DisplayPoint,
3317    pub column_overshoot_after_line_end: u32,
3318}
3319
3320impl PointForPosition {
3321    #[cfg(test)]
3322    pub fn valid(valid: DisplayPoint) -> Self {
3323        Self {
3324            previous_valid: valid,
3325            next_valid: valid,
3326            exact_unclipped: valid,
3327            column_overshoot_after_line_end: 0,
3328        }
3329    }
3330
3331    pub fn as_valid(&self) -> Option<DisplayPoint> {
3332        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
3333            Some(self.previous_valid)
3334        } else {
3335            None
3336        }
3337    }
3338}
3339
3340impl PositionMap {
3341    fn point_for_position(
3342        &self,
3343        text_bounds: Bounds<Pixels>,
3344        position: gpui::Point<Pixels>,
3345    ) -> PointForPosition {
3346        let scroll_position = self.snapshot.scroll_position();
3347        let position = position - text_bounds.origin;
3348        let y = position.y.max(px(0.)).min(self.size.width);
3349        let x = position.x + (scroll_position.x * self.em_width);
3350        let row = (f32::from(y / self.line_height) + scroll_position.y) as u32;
3351
3352        let (column, x_overshoot_after_line_end) = if let Some(line) = self
3353            .line_layouts
3354            .get(row as usize - scroll_position.y as usize)
3355            .map(|&LineWithInvisibles { ref line, .. }| line)
3356        {
3357            if let Some(ix) = line.index_for_x(x) {
3358                (ix as u32, px(0.))
3359            } else {
3360                (line.len as u32, px(0.).max(x - line.width))
3361            }
3362        } else {
3363            (0, x)
3364        };
3365
3366        let mut exact_unclipped = DisplayPoint::new(row, column);
3367        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
3368        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
3369
3370        let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
3371        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
3372        PointForPosition {
3373            previous_valid,
3374            next_valid,
3375            exact_unclipped,
3376            column_overshoot_after_line_end,
3377        }
3378    }
3379}
3380
3381struct BlockLayout {
3382    row: u32,
3383    element: AnyElement,
3384    available_space: Size<AvailableSpace>,
3385    style: BlockStyle,
3386}
3387
3388fn layout_line(
3389    row: u32,
3390    snapshot: &EditorSnapshot,
3391    style: &EditorStyle,
3392    cx: &WindowContext,
3393) -> Result<ShapedLine> {
3394    let mut line = snapshot.line(row);
3395
3396    if line.len() > MAX_LINE_LEN {
3397        let mut len = MAX_LINE_LEN;
3398        while !line.is_char_boundary(len) {
3399            len -= 1;
3400        }
3401
3402        line.truncate(len);
3403    }
3404
3405    cx.text_system().shape_line(
3406        line.into(),
3407        style.text.font_size.to_pixels(cx.rem_size()),
3408        &[TextRun {
3409            len: snapshot.line_len(row) as usize,
3410            font: style.text.font(),
3411            color: Hsla::default(),
3412            background_color: None,
3413            underline: None,
3414        }],
3415    )
3416}
3417
3418#[derive(Debug)]
3419pub struct Cursor {
3420    origin: gpui::Point<Pixels>,
3421    block_width: Pixels,
3422    line_height: Pixels,
3423    color: Hsla,
3424    shape: CursorShape,
3425    block_text: Option<ShapedLine>,
3426}
3427
3428impl Cursor {
3429    pub fn new(
3430        origin: gpui::Point<Pixels>,
3431        block_width: Pixels,
3432        line_height: Pixels,
3433        color: Hsla,
3434        shape: CursorShape,
3435        block_text: Option<ShapedLine>,
3436    ) -> Cursor {
3437        Cursor {
3438            origin,
3439            block_width,
3440            line_height,
3441            color,
3442            shape,
3443            block_text,
3444        }
3445    }
3446
3447    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
3448        Bounds {
3449            origin: self.origin + origin,
3450            size: size(self.block_width, self.line_height),
3451        }
3452    }
3453
3454    pub fn paint(&self, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
3455        let bounds = match self.shape {
3456            CursorShape::Bar => Bounds {
3457                origin: self.origin + origin,
3458                size: size(px(2.0), self.line_height),
3459            },
3460            CursorShape::Block | CursorShape::Hollow => Bounds {
3461                origin: self.origin + origin,
3462                size: size(self.block_width, self.line_height),
3463            },
3464            CursorShape::Underscore => Bounds {
3465                origin: self.origin
3466                    + origin
3467                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
3468                size: size(self.block_width, px(2.0)),
3469            },
3470        };
3471
3472        //Draw background or border quad
3473        if matches!(self.shape, CursorShape::Hollow) {
3474            cx.paint_quad(
3475                bounds,
3476                Corners::default(),
3477                transparent_black(),
3478                Edges::all(px(1.)),
3479                self.color,
3480            );
3481        } else {
3482            cx.paint_quad(
3483                bounds,
3484                Corners::default(),
3485                self.color,
3486                Edges::default(),
3487                transparent_black(),
3488            );
3489        }
3490
3491        if let Some(block_text) = &self.block_text {
3492            block_text.paint(self.origin + origin, self.line_height, cx);
3493        }
3494    }
3495
3496    pub fn shape(&self) -> CursorShape {
3497        self.shape
3498    }
3499}
3500
3501#[derive(Debug)]
3502pub struct HighlightedRange {
3503    pub start_y: Pixels,
3504    pub line_height: Pixels,
3505    pub lines: Vec<HighlightedRangeLine>,
3506    pub color: Hsla,
3507    pub corner_radius: Pixels,
3508}
3509
3510#[derive(Debug)]
3511pub struct HighlightedRangeLine {
3512    pub start_x: Pixels,
3513    pub end_x: Pixels,
3514}
3515
3516impl HighlightedRange {
3517    pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut WindowContext) {
3518        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
3519            self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
3520            self.paint_lines(
3521                self.start_y + self.line_height,
3522                &self.lines[1..],
3523                bounds,
3524                cx,
3525            );
3526        } else {
3527            self.paint_lines(self.start_y, &self.lines, bounds, cx);
3528        }
3529    }
3530
3531    fn paint_lines(
3532        &self,
3533        start_y: Pixels,
3534        lines: &[HighlightedRangeLine],
3535        bounds: Bounds<Pixels>,
3536        cx: &mut WindowContext,
3537    ) {
3538        if lines.is_empty() {
3539            return;
3540        }
3541
3542        let first_line = lines.first().unwrap();
3543        let last_line = lines.last().unwrap();
3544
3545        let first_top_left = point(first_line.start_x, start_y);
3546        let first_top_right = point(first_line.end_x, start_y);
3547
3548        let curve_height = point(Pixels::ZERO, self.corner_radius);
3549        let curve_width = |start_x: Pixels, end_x: Pixels| {
3550            let max = (end_x - start_x) / 2.;
3551            let width = if max < self.corner_radius {
3552                max
3553            } else {
3554                self.corner_radius
3555            };
3556
3557            point(width, Pixels::ZERO)
3558        };
3559
3560        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
3561        let mut path = gpui::Path::new(first_top_right - top_curve_width);
3562        path.curve_to(first_top_right + curve_height, first_top_right);
3563
3564        let mut iter = lines.iter().enumerate().peekable();
3565        while let Some((ix, line)) = iter.next() {
3566            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
3567
3568            if let Some((_, next_line)) = iter.peek() {
3569                let next_top_right = point(next_line.end_x, bottom_right.y);
3570
3571                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
3572                    Ordering::Equal => {
3573                        path.line_to(bottom_right);
3574                    }
3575                    Ordering::Less => {
3576                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
3577                        path.line_to(bottom_right - curve_height);
3578                        if self.corner_radius > Pixels::ZERO {
3579                            path.curve_to(bottom_right - curve_width, bottom_right);
3580                        }
3581                        path.line_to(next_top_right + curve_width);
3582                        if self.corner_radius > Pixels::ZERO {
3583                            path.curve_to(next_top_right + curve_height, next_top_right);
3584                        }
3585                    }
3586                    Ordering::Greater => {
3587                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
3588                        path.line_to(bottom_right - curve_height);
3589                        if self.corner_radius > Pixels::ZERO {
3590                            path.curve_to(bottom_right + curve_width, bottom_right);
3591                        }
3592                        path.line_to(next_top_right - curve_width);
3593                        if self.corner_radius > Pixels::ZERO {
3594                            path.curve_to(next_top_right + curve_height, next_top_right);
3595                        }
3596                    }
3597                }
3598            } else {
3599                let curve_width = curve_width(line.start_x, line.end_x);
3600                path.line_to(bottom_right - curve_height);
3601                if self.corner_radius > Pixels::ZERO {
3602                    path.curve_to(bottom_right - curve_width, bottom_right);
3603                }
3604
3605                let bottom_left = point(line.start_x, bottom_right.y);
3606                path.line_to(bottom_left + curve_width);
3607                if self.corner_radius > Pixels::ZERO {
3608                    path.curve_to(bottom_left - curve_height, bottom_left);
3609                }
3610            }
3611        }
3612
3613        if first_line.start_x > last_line.start_x {
3614            let curve_width = curve_width(last_line.start_x, first_line.start_x);
3615            let second_top_left = point(last_line.start_x, start_y + self.line_height);
3616            path.line_to(second_top_left + curve_height);
3617            if self.corner_radius > Pixels::ZERO {
3618                path.curve_to(second_top_left + curve_width, second_top_left);
3619            }
3620            let first_bottom_left = point(first_line.start_x, second_top_left.y);
3621            path.line_to(first_bottom_left - curve_width);
3622            if self.corner_radius > Pixels::ZERO {
3623                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
3624            }
3625        }
3626
3627        path.line_to(first_top_left + curve_height);
3628        if self.corner_radius > Pixels::ZERO {
3629            path.curve_to(first_top_left + top_curve_width, first_top_left);
3630        }
3631        path.line_to(first_top_right - top_curve_width);
3632
3633        cx.paint_path(path, self.color);
3634    }
3635}
3636
3637pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
3638    (delta.pow(1.5) / 100.0).into()
3639}
3640
3641fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
3642    (delta.pow(1.2) / 300.0).into()
3643}
3644
3645// #[cfg(test)]
3646// mod tests {
3647//     use super::*;
3648//     use crate::{
3649//         display_map::{BlockDisposition, BlockProperties},
3650//         editor_tests::{init_test, update_test_language_settings},
3651//         Editor, MultiBuffer,
3652//     };
3653//     use gpui::TestAppContext;
3654//     use language::language_settings;
3655//     use log::info;
3656//     use std::{num::NonZeroU32, sync::Arc};
3657//     use util::test::sample_text;
3658
3659//     #[gpui::test]
3660//     fn test_layout_line_numbers(cx: &mut TestAppContext) {
3661//         init_test(cx, |_| {});
3662//         let editor = cx
3663//             .add_window(|cx| {
3664//                 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
3665//                 Editor::new(EditorMode::Full, buffer, None, None, cx)
3666//             })
3667//             .root(cx);
3668//         let element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3669
3670//         let layouts = editor.update(cx, |editor, cx| {
3671//             let snapshot = editor.snapshot(cx);
3672//             element
3673//                 .layout_line_numbers(
3674//                     0..6,
3675//                     &Default::default(),
3676//                     DisplayPoint::new(0, 0),
3677//                     false,
3678//                     &snapshot,
3679//                     cx,
3680//                 )
3681//                 .0
3682//         });
3683//         assert_eq!(layouts.len(), 6);
3684
3685//         let relative_rows = editor.update(cx, |editor, cx| {
3686//             let snapshot = editor.snapshot(cx);
3687//             element.calculate_relative_line_numbers(&snapshot, &(0..6), Some(3))
3688//         });
3689//         assert_eq!(relative_rows[&0], 3);
3690//         assert_eq!(relative_rows[&1], 2);
3691//         assert_eq!(relative_rows[&2], 1);
3692//         // current line has no relative number
3693//         assert_eq!(relative_rows[&4], 1);
3694//         assert_eq!(relative_rows[&5], 2);
3695
3696//         // works if cursor is before screen
3697//         let relative_rows = editor.update(cx, |editor, cx| {
3698//             let snapshot = editor.snapshot(cx);
3699
3700//             element.calculate_relative_line_numbers(&snapshot, &(3..6), Some(1))
3701//         });
3702//         assert_eq!(relative_rows.len(), 3);
3703//         assert_eq!(relative_rows[&3], 2);
3704//         assert_eq!(relative_rows[&4], 3);
3705//         assert_eq!(relative_rows[&5], 4);
3706
3707//         // works if cursor is after screen
3708//         let relative_rows = editor.update(cx, |editor, cx| {
3709//             let snapshot = editor.snapshot(cx);
3710
3711//             element.calculate_relative_line_numbers(&snapshot, &(0..3), Some(6))
3712//         });
3713//         assert_eq!(relative_rows.len(), 3);
3714//         assert_eq!(relative_rows[&0], 5);
3715//         assert_eq!(relative_rows[&1], 4);
3716//         assert_eq!(relative_rows[&2], 3);
3717//     }
3718
3719//     #[gpui::test]
3720//     async fn test_vim_visual_selections(cx: &mut TestAppContext) {
3721//         init_test(cx, |_| {});
3722
3723//         let editor = cx
3724//             .add_window(|cx| {
3725//                 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
3726//                 Editor::new(EditorMode::Full, buffer, None, None, cx)
3727//             })
3728//             .root(cx);
3729//         let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3730//         let (_, state) = editor.update(cx, |editor, cx| {
3731//             editor.cursor_shape = CursorShape::Block;
3732//             editor.change_selections(None, cx, |s| {
3733//                 s.select_ranges([
3734//                     Point::new(0, 0)..Point::new(1, 0),
3735//                     Point::new(3, 2)..Point::new(3, 3),
3736//                     Point::new(5, 6)..Point::new(6, 0),
3737//                 ]);
3738//             });
3739//             element.layout(
3740//                 SizeConstraint::new(point(500., 500.), point(500., 500.)),
3741//                 editor,
3742//                 cx,
3743//             )
3744//         });
3745//         assert_eq!(state.selections.len(), 1);
3746//         let local_selections = &state.selections[0].1;
3747//         assert_eq!(local_selections.len(), 3);
3748//         // moves cursor back one line
3749//         assert_eq!(local_selections[0].head, DisplayPoint::new(0, 6));
3750//         assert_eq!(
3751//             local_selections[0].range,
3752//             DisplayPoint::new(0, 0)..DisplayPoint::new(1, 0)
3753//         );
3754
3755//         // moves cursor back one column
3756//         assert_eq!(
3757//             local_selections[1].range,
3758//             DisplayPoint::new(3, 2)..DisplayPoint::new(3, 3)
3759//         );
3760//         assert_eq!(local_selections[1].head, DisplayPoint::new(3, 2));
3761
3762//         // leaves cursor on the max point
3763//         assert_eq!(
3764//             local_selections[2].range,
3765//             DisplayPoint::new(5, 6)..DisplayPoint::new(6, 0)
3766//         );
3767//         assert_eq!(local_selections[2].head, DisplayPoint::new(6, 0));
3768
3769//         // active lines does not include 1 (even though the range of the selection does)
3770//         assert_eq!(
3771//             state.active_rows.keys().cloned().collect::<Vec<u32>>(),
3772//             vec![0, 3, 5, 6]
3773//         );
3774
3775//         // multi-buffer support
3776//         // in DisplayPoint co-ordinates, this is what we're dealing with:
3777//         //  0: [[file
3778//         //  1:   header]]
3779//         //  2: aaaaaa
3780//         //  3: bbbbbb
3781//         //  4: cccccc
3782//         //  5:
3783//         //  6: ...
3784//         //  7: ffffff
3785//         //  8: gggggg
3786//         //  9: hhhhhh
3787//         // 10:
3788//         // 11: [[file
3789//         // 12:   header]]
3790//         // 13: bbbbbb
3791//         // 14: cccccc
3792//         // 15: dddddd
3793//         let editor = cx
3794//             .add_window(|cx| {
3795//                 let buffer = MultiBuffer::build_multi(
3796//                     [
3797//                         (
3798//                             &(sample_text(8, 6, 'a') + "\n"),
3799//                             vec![
3800//                                 Point::new(0, 0)..Point::new(3, 0),
3801//                                 Point::new(4, 0)..Point::new(7, 0),
3802//                             ],
3803//                         ),
3804//                         (
3805//                             &(sample_text(8, 6, 'a') + "\n"),
3806//                             vec![Point::new(1, 0)..Point::new(3, 0)],
3807//                         ),
3808//                     ],
3809//                     cx,
3810//                 );
3811//                 Editor::new(EditorMode::Full, buffer, None, None, cx)
3812//             })
3813//             .root(cx);
3814//         let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3815//         let (_, state) = editor.update(cx, |editor, cx| {
3816//             editor.cursor_shape = CursorShape::Block;
3817//             editor.change_selections(None, cx, |s| {
3818//                 s.select_display_ranges([
3819//                     DisplayPoint::new(4, 0)..DisplayPoint::new(7, 0),
3820//                     DisplayPoint::new(10, 0)..DisplayPoint::new(13, 0),
3821//                 ]);
3822//             });
3823//             element.layout(
3824//                 SizeConstraint::new(point(500., 500.), point(500., 500.)),
3825//                 editor,
3826//                 cx,
3827//             )
3828//         });
3829
3830//         assert_eq!(state.selections.len(), 1);
3831//         let local_selections = &state.selections[0].1;
3832//         assert_eq!(local_selections.len(), 2);
3833
3834//         // moves cursor on excerpt boundary back a line
3835//         // and doesn't allow selection to bleed through
3836//         assert_eq!(
3837//             local_selections[0].range,
3838//             DisplayPoint::new(4, 0)..DisplayPoint::new(6, 0)
3839//         );
3840//         assert_eq!(local_selections[0].head, DisplayPoint::new(5, 0));
3841
3842//         // moves cursor on buffer boundary back two lines
3843//         // and doesn't allow selection to bleed through
3844//         assert_eq!(
3845//             local_selections[1].range,
3846//             DisplayPoint::new(10, 0)..DisplayPoint::new(11, 0)
3847//         );
3848//         assert_eq!(local_selections[1].head, DisplayPoint::new(10, 0));
3849//     }
3850
3851//     #[gpui::test]
3852//     fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
3853//         init_test(cx, |_| {});
3854
3855//         let editor = cx
3856//             .add_window(|cx| {
3857//                 let buffer = MultiBuffer::build_simple("", cx);
3858//                 Editor::new(EditorMode::Full, buffer, None, None, cx)
3859//             })
3860//             .root(cx);
3861
3862//         editor.update(cx, |editor, cx| {
3863//             editor.set_placeholder_text("hello", cx);
3864//             editor.insert_blocks(
3865//                 [BlockProperties {
3866//                     style: BlockStyle::Fixed,
3867//                     disposition: BlockDisposition::Above,
3868//                     height: 3,
3869//                     position: Anchor::min(),
3870//                     render: Arc::new(|_| Empty::new().into_any),
3871//                 }],
3872//                 None,
3873//                 cx,
3874//             );
3875
3876//             // Blur the editor so that it displays placeholder text.
3877//             cx.blur();
3878//         });
3879
3880//         let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3881//         let (size, mut state) = editor.update(cx, |editor, cx| {
3882//             element.layout(
3883//                 SizeConstraint::new(point(500., 500.), point(500., 500.)),
3884//                 editor,
3885//                 cx,
3886//             )
3887//         });
3888
3889//         assert_eq!(state.position_map.line_layouts.len(), 4);
3890//         assert_eq!(
3891//             state
3892//                 .line_number_layouts
3893//                 .iter()
3894//                 .map(Option::is_some)
3895//                 .collect::<Vec<_>>(),
3896//             &[false, false, false, true]
3897//         );
3898
3899//         // Don't panic.
3900//         let bounds = Bounds::<Pixels>::new(Default::default(), size);
3901//         editor.update(cx, |editor, cx| {
3902//             element.paint(bounds, bounds, &mut state, editor, cx);
3903//         });
3904//     }
3905
3906//     #[gpui::test]
3907//     fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
3908//         const TAB_SIZE: u32 = 4;
3909
3910//         let input_text = "\t \t|\t| a b";
3911//         let expected_invisibles = vec![
3912//             Invisible::Tab {
3913//                 line_start_offset: 0,
3914//             },
3915//             Invisible::Whitespace {
3916//                 line_offset: TAB_SIZE as usize,
3917//             },
3918//             Invisible::Tab {
3919//                 line_start_offset: TAB_SIZE as usize + 1,
3920//             },
3921//             Invisible::Tab {
3922//                 line_start_offset: TAB_SIZE as usize * 2 + 1,
3923//             },
3924//             Invisible::Whitespace {
3925//                 line_offset: TAB_SIZE as usize * 3 + 1,
3926//             },
3927//             Invisible::Whitespace {
3928//                 line_offset: TAB_SIZE as usize * 3 + 3,
3929//             },
3930//         ];
3931//         assert_eq!(
3932//             expected_invisibles.len(),
3933//             input_text
3934//                 .chars()
3935//                 .filter(|initial_char| initial_char.is_whitespace())
3936//                 .count(),
3937//             "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
3938//         );
3939
3940//         init_test(cx, |s| {
3941//             s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3942//             s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
3943//         });
3944
3945//         let actual_invisibles =
3946//             collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, 500.0);
3947
3948//         assert_eq!(expected_invisibles, actual_invisibles);
3949//     }
3950
3951//     #[gpui::test]
3952//     fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
3953//         init_test(cx, |s| {
3954//             s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3955//             s.defaults.tab_size = NonZeroU32::new(4);
3956//         });
3957
3958//         for editor_mode_without_invisibles in [
3959//             EditorMode::SingleLine,
3960//             EditorMode::AutoHeight { max_lines: 100 },
3961//         ] {
3962//             let invisibles = collect_invisibles_from_new_editor(
3963//                 cx,
3964//                 editor_mode_without_invisibles,
3965//                 "\t\t\t| | a b",
3966//                 500.0,
3967//             );
3968//             assert!(invisibles.is_empty,
3969//                 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
3970//         }
3971//     }
3972
3973//     #[gpui::test]
3974//     fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
3975//         let tab_size = 4;
3976//         let input_text = "a\tbcd   ".repeat(9);
3977//         let repeated_invisibles = [
3978//             Invisible::Tab {
3979//                 line_start_offset: 1,
3980//             },
3981//             Invisible::Whitespace {
3982//                 line_offset: tab_size as usize + 3,
3983//             },
3984//             Invisible::Whitespace {
3985//                 line_offset: tab_size as usize + 4,
3986//             },
3987//             Invisible::Whitespace {
3988//                 line_offset: tab_size as usize + 5,
3989//             },
3990//         ];
3991//         let expected_invisibles = std::iter::once(repeated_invisibles)
3992//             .cycle()
3993//             .take(9)
3994//             .flatten()
3995//             .collect::<Vec<_>>();
3996//         assert_eq!(
3997//             expected_invisibles.len(),
3998//             input_text
3999//                 .chars()
4000//                 .filter(|initial_char| initial_char.is_whitespace())
4001//                 .count(),
4002//             "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
4003//         );
4004//         info!("Expected invisibles: {expected_invisibles:?}");
4005
4006//         init_test(cx, |_| {});
4007
4008//         // Put the same string with repeating whitespace pattern into editors of various size,
4009//         // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
4010//         let resize_step = 10.0;
4011//         let mut editor_width = 200.0;
4012//         while editor_width <= 1000.0 {
4013//             update_test_language_settings(cx, |s| {
4014//                 s.defaults.tab_size = NonZeroU32::new(tab_size);
4015//                 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4016//                 s.defaults.preferred_line_length = Some(editor_width as u32);
4017//                 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
4018//             });
4019
4020//             let actual_invisibles =
4021//                 collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, editor_width);
4022
4023//             // Whatever the editor size is, ensure it has the same invisible kinds in the same order
4024//             // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
4025//             let mut i = 0;
4026//             for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
4027//                 i = actual_index;
4028//                 match expected_invisibles.get(i) {
4029//                     Some(expected_invisible) => match (expected_invisible, actual_invisible) {
4030//                         (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
4031//                         | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
4032//                         _ => {
4033//                             panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
4034//                         }
4035//                     },
4036//                     None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
4037//                 }
4038//             }
4039//             let missing_expected_invisibles = &expected_invisibles[i + 1..];
4040//             assert!(
4041//                 missing_expected_invisibles.is_empty,
4042//                 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
4043//             );
4044
4045//             editor_width += resize_step;
4046//         }
4047//     }
4048
4049//     fn collect_invisibles_from_new_editor(
4050//         cx: &mut TestAppContext,
4051//         editor_mode: EditorMode,
4052//         input_text: &str,
4053//         editor_width: f32,
4054//     ) -> Vec<Invisible> {
4055//         info!(
4056//             "Creating editor with mode {editor_mode:?}, width {editor_width} and text '{input_text}'"
4057//         );
4058//         let editor = cx
4059//             .add_window(|cx| {
4060//                 let buffer = MultiBuffer::build_simple(&input_text, cx);
4061//                 Editor::new(editor_mode, buffer, None, None, cx)
4062//             })
4063//             .root(cx);
4064
4065//         let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
4066//         let (_, layout_state) = editor.update(cx, |editor, cx| {
4067//             editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
4068//             editor.set_wrap_width(Some(editor_width), cx);
4069
4070//             element.layout(
4071//                 SizeConstraint::new(point(editor_width, 500.), point(editor_width, 500.)),
4072//                 editor,
4073//                 cx,
4074//             )
4075//         });
4076
4077//         layout_state
4078//             .position_map
4079//             .line_layouts
4080//             .iter()
4081//             .map(|line_with_invisibles| &line_with_invisibles.invisibles)
4082//             .flatten()
4083//             .cloned()
4084//             .collect()
4085//     }
4086// }
4087
4088fn register_action<T: Action>(
4089    view: &View<Editor>,
4090    cx: &mut WindowContext,
4091    listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
4092) {
4093    let view = view.clone();
4094    cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
4095        let action = action.downcast_ref().unwrap();
4096        if phase == DispatchPhase::Bubble {
4097            view.update(cx, |editor, cx| {
4098                listener(editor, action, cx);
4099            })
4100        }
4101    })
4102}