element.rs

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