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                if editor.set_wrap_width(Some(wrap_width), cx) {
1714                    editor.snapshot(cx)
1715                } else {
1716                    snapshot
1717                }
1718            };
1719
1720            let wrap_guides = editor
1721                .wrap_guides(cx)
1722                .iter()
1723                .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
1724                .collect::<SmallVec<[_; 2]>>();
1725
1726            let scroll_height = Pixels::from(snapshot.max_point().row() + 1) * line_height;
1727            let gutter_size = size(gutter_width, bounds.size.height);
1728            let text_size = size(text_width, bounds.size.height);
1729
1730            let autoscroll_horizontally =
1731                editor.autoscroll_vertically(bounds.size.height, line_height, cx);
1732            let mut snapshot = editor.snapshot(cx);
1733
1734            let scroll_position = snapshot.scroll_position();
1735            // The scroll position is a fractional point, the whole number of which represents
1736            // the top of the window in terms of display rows.
1737            let start_row = scroll_position.y as u32;
1738            let height_in_lines = f32::from(bounds.size.height / line_height);
1739            let max_row = snapshot.max_point().row();
1740
1741            // Add 1 to ensure selections bleed off screen
1742            let end_row = 1 + cmp::min((scroll_position.y + height_in_lines).ceil() as u32, max_row);
1743
1744            let start_anchor = if start_row == 0 {
1745                Anchor::min()
1746            } else {
1747                snapshot
1748                    .buffer_snapshot
1749                    .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
1750            };
1751            let end_anchor = if end_row > max_row {
1752                Anchor::max()
1753            } else {
1754                snapshot
1755                    .buffer_snapshot
1756                    .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
1757            };
1758
1759            let mut selections: Vec<(PlayerColor, Vec<SelectionLayout>)> = Vec::new();
1760            let mut active_rows = BTreeMap::new();
1761            let is_singleton = editor.is_singleton(cx);
1762
1763            let highlighted_rows = editor.highlighted_rows();
1764            let highlighted_ranges = editor.background_highlights_in_range(
1765                start_anchor..end_anchor,
1766                &snapshot.display_snapshot,
1767                cx.theme().colors(),
1768            );
1769
1770            let mut newest_selection_head = None;
1771
1772            if editor.show_local_selections {
1773                let mut local_selections: Vec<Selection<Point>> = editor
1774                    .selections
1775                    .disjoint_in_range(start_anchor..end_anchor, cx);
1776                local_selections.extend(editor.selections.pending(cx));
1777                let mut layouts = Vec::new();
1778                let newest = editor.selections.newest(cx);
1779                for selection in local_selections.drain(..) {
1780                    let is_empty = selection.start == selection.end;
1781                    let is_newest = selection == newest;
1782
1783                    let layout = SelectionLayout::new(
1784                        selection,
1785                        editor.selections.line_mode,
1786                        editor.cursor_shape,
1787                        &snapshot.display_snapshot,
1788                        is_newest,
1789                        true,
1790                    );
1791                    if is_newest {
1792                        newest_selection_head = Some(layout.head);
1793                    }
1794
1795                    for row in cmp::max(layout.active_rows.start, start_row)
1796                        ..=cmp::min(layout.active_rows.end, end_row)
1797                    {
1798                        let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
1799                        *contains_non_empty_selection |= !is_empty;
1800                    }
1801                    layouts.push(layout);
1802                }
1803
1804                selections.push((style.local_player, layouts));
1805            }
1806
1807            if let Some(collaboration_hub) = &editor.collaboration_hub {
1808                // When following someone, render the local selections in their color.
1809                if let Some(leader_id) = editor.leader_peer_id {
1810                    if let Some(collaborator) = collaboration_hub.collaborators(cx).get(&leader_id) {
1811                        if let Some(participant_index) = collaboration_hub
1812                            .user_participant_indices(cx)
1813                            .get(&collaborator.user_id)
1814                        {
1815                            if let Some((local_selection_style, _)) = selections.first_mut() {
1816                                *local_selection_style = cx
1817                                    .theme()
1818                                    .players()
1819                                    .color_for_participant(participant_index.0);
1820                            }
1821                        }
1822                    }
1823                }
1824
1825                let mut remote_selections = HashMap::default();
1826                for selection in snapshot.remote_selections_in_range(
1827                    &(start_anchor..end_anchor),
1828                    collaboration_hub.as_ref(),
1829                    cx,
1830                ) {
1831                    let selection_style = if let Some(participant_index) = selection.participant_index {
1832                        cx.theme()
1833                            .players()
1834                            .color_for_participant(participant_index.0)
1835                    } else {
1836                        cx.theme().players().absent()
1837                    };
1838
1839                    // Don't re-render the leader's selections, since the local selections
1840                    // match theirs.
1841                    if Some(selection.peer_id) == editor.leader_peer_id {
1842                        continue;
1843                    }
1844
1845                    remote_selections
1846                        .entry(selection.replica_id)
1847                        .or_insert((selection_style, Vec::new()))
1848                        .1
1849                        .push(SelectionLayout::new(
1850                            selection.selection,
1851                            selection.line_mode,
1852                            selection.cursor_shape,
1853                            &snapshot.display_snapshot,
1854                            false,
1855                            false,
1856                        ));
1857                }
1858
1859                selections.extend(remote_selections.into_values());
1860            }
1861
1862            let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
1863            let show_scrollbars = match scrollbar_settings.show {
1864                ShowScrollbar::Auto => {
1865                    // Git
1866                    (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_git_diffs())
1867                    ||
1868                    // Selections
1869                    (is_singleton && scrollbar_settings.selections && !highlighted_ranges.is_empty())
1870                    // Scrollmanager
1871                    || editor.scroll_manager.scrollbars_visible()
1872                }
1873                ShowScrollbar::System => editor.scroll_manager.scrollbars_visible(),
1874                ShowScrollbar::Always => true,
1875                ShowScrollbar::Never => false,
1876            };
1877
1878            let head_for_relative = newest_selection_head.unwrap_or_else(|| {
1879                let newest = editor.selections.newest::<Point>(cx);
1880                SelectionLayout::new(
1881                    newest,
1882                    editor.selections.line_mode,
1883                    editor.cursor_shape,
1884                    &snapshot.display_snapshot,
1885                    true,
1886                    true,
1887                )
1888                .head
1889            });
1890
1891            let (line_numbers, fold_statuses) = self.shape_line_numbers(
1892                start_row..end_row,
1893                &active_rows,
1894                head_for_relative,
1895                is_singleton,
1896                &snapshot,
1897                cx,
1898            );
1899
1900            let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
1901
1902            let scrollbar_row_range = scroll_position.y..(scroll_position.y + height_in_lines);
1903
1904            let mut max_visible_line_width = Pixels::ZERO;
1905            let line_layouts = self.layout_lines(start_row..end_row, &line_numbers, &snapshot, cx);
1906            for line_with_invisibles in &line_layouts {
1907                if line_with_invisibles.line.width > max_visible_line_width {
1908                    max_visible_line_width = line_with_invisibles.line.width;
1909                }
1910            }
1911
1912            let longest_line_width = layout_line(snapshot.longest_row(), &snapshot, &style, cx)
1913                .unwrap()
1914                .width;
1915            let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.width;
1916
1917            let (scroll_width, blocks) = cx.with_element_id(Some("editor_blocks"), |cx| {
1918                self.layout_blocks(
1919                    start_row..end_row,
1920                    &snapshot,
1921                    bounds.size.width,
1922                    scroll_width,
1923                    gutter_padding,
1924                    gutter_width,
1925                    em_width,
1926                    gutter_width + gutter_margin,
1927                    line_height,
1928                    &style,
1929                    &line_layouts,
1930                    editor,
1931                    cx,
1932                )
1933            });
1934
1935            let scroll_max = point(
1936                f32::from((scroll_width - text_size.width) / em_width).max(0.0),
1937                max_row as f32,
1938            );
1939
1940            let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
1941
1942            let autoscrolled = if autoscroll_horizontally {
1943                editor.autoscroll_horizontally(
1944                    start_row,
1945                    text_size.width,
1946                    scroll_width,
1947                    em_width,
1948                    &line_layouts,
1949                    cx,
1950                )
1951            } else {
1952                false
1953            };
1954
1955            if clamped || autoscrolled {
1956                snapshot = editor.snapshot(cx);
1957            }
1958
1959            let mut context_menu = None;
1960            let mut code_actions_indicator = None;
1961            if let Some(newest_selection_head) = newest_selection_head {
1962                if (start_row..end_row).contains(&newest_selection_head.row()) {
1963                    if editor.context_menu_visible() {
1964                        let max_height = (12. * line_height).min((bounds.size.height - line_height) / 2.);
1965                        context_menu =
1966                            editor.render_context_menu(newest_selection_head, &self.style, max_height, cx);
1967                    }
1968
1969                    let active = matches!(
1970                        editor.context_menu.read().as_ref(),
1971                        Some(crate::ContextMenu::CodeActions(_))
1972                    );
1973
1974                    code_actions_indicator = editor
1975                        .render_code_actions_indicator(&style, active, cx)
1976                        .map(|element| CodeActionsIndicator {
1977                            row: newest_selection_head.row(),
1978                            button: element,
1979                        });
1980                }
1981            }
1982
1983            let visible_rows = start_row..start_row + line_layouts.len() as u32;
1984            let max_size = size(
1985                (120. * em_width) // Default size
1986                    .min(bounds.size.width / 2.) // Shrink to half of the editor width
1987                    .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
1988                (16. * line_height) // Default size
1989                    .min(bounds.size.height / 2.) // Shrink to half of the editor height
1990                    .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
1991            );
1992
1993            let mut hover = editor.hover_state.render(
1994                &snapshot,
1995                &style,
1996                visible_rows,
1997                max_size,
1998                editor.workspace.as_ref().map(|(w, _)| w.clone()),
1999                cx,
2000            );
2001
2002            let mut fold_indicators = cx.with_element_id(Some("gutter_fold_indicators"), |cx| {
2003                editor.render_fold_indicators(
2004                    fold_statuses,
2005                    &style,
2006                    editor.gutter_hovered,
2007                    line_height,
2008                    gutter_margin,
2009                    cx,
2010                )
2011            });
2012
2013            let invisible_symbol_font_size = font_size / 2.;
2014            let tab_invisible = cx
2015                .text_system()
2016                .shape_line(
2017                    "".into(),
2018                    invisible_symbol_font_size,
2019                    &[TextRun {
2020                        len: "".len(),
2021                        font: self.style.text.font(),
2022                        color: cx.theme().colors().editor_invisible,
2023                        background_color: None,
2024                        underline: None,
2025                    }],
2026                )
2027                .unwrap();
2028            let space_invisible = cx
2029                .text_system()
2030                .shape_line(
2031                    "".into(),
2032                    invisible_symbol_font_size,
2033                    &[TextRun {
2034                        len: "".len(),
2035                        font: self.style.text.font(),
2036                        color: cx.theme().colors().editor_invisible,
2037                        background_color: None,
2038                        underline: None,
2039                    }],
2040                )
2041                .unwrap();
2042
2043            LayoutState {
2044                mode: snapshot.mode,
2045                position_map: Arc::new(PositionMap {
2046                    size: bounds.size,
2047                    scroll_position: point(
2048                        scroll_position.x * em_width,
2049                        scroll_position.y * line_height,
2050                    ),
2051                    scroll_max,
2052                    line_layouts,
2053                    line_height,
2054                    em_width,
2055                    em_advance,
2056                    snapshot,
2057                }),
2058                visible_anchor_range: start_anchor..end_anchor,
2059                visible_display_row_range: start_row..end_row,
2060                wrap_guides,
2061                gutter_size,
2062                gutter_padding,
2063                text_size,
2064                scrollbar_row_range,
2065                show_scrollbars,
2066                is_singleton,
2067                max_row,
2068                gutter_margin,
2069                active_rows,
2070                highlighted_rows,
2071                highlighted_ranges,
2072                line_numbers,
2073                display_hunks,
2074                blocks,
2075                selections,
2076                context_menu,
2077                code_actions_indicator,
2078                fold_indicators,
2079                tab_invisible,
2080                space_invisible,
2081                hover_popovers: hover,
2082            }
2083        })
2084    }
2085
2086    #[allow(clippy::too_many_arguments)]
2087    fn layout_blocks(
2088        &self,
2089        rows: Range<u32>,
2090        snapshot: &EditorSnapshot,
2091        editor_width: Pixels,
2092        scroll_width: Pixels,
2093        gutter_padding: Pixels,
2094        gutter_width: Pixels,
2095        em_width: Pixels,
2096        text_x: Pixels,
2097        line_height: Pixels,
2098        style: &EditorStyle,
2099        line_layouts: &[LineWithInvisibles],
2100        editor: &mut Editor,
2101        cx: &mut ViewContext<Editor>,
2102    ) -> (Pixels, Vec<BlockLayout>) {
2103        let mut block_id = 0;
2104        let scroll_x = snapshot.scroll_anchor.offset.x;
2105        let (fixed_blocks, non_fixed_blocks) = snapshot
2106            .blocks_in_range(rows.clone())
2107            .partition::<Vec<_>, _>(|(_, block)| match block {
2108                TransformBlock::ExcerptHeader { .. } => false,
2109                TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
2110            });
2111
2112        let mut render_block = |block: &TransformBlock,
2113                                available_space: Size<AvailableSpace>,
2114                                block_id: usize,
2115                                editor: &mut Editor,
2116                                cx: &mut ViewContext<Editor>| {
2117            let mut element = match block {
2118                TransformBlock::Custom(block) => {
2119                    let align_to = block
2120                        .position()
2121                        .to_point(&snapshot.buffer_snapshot)
2122                        .to_display_point(snapshot);
2123                    let anchor_x = text_x
2124                        + if rows.contains(&align_to.row()) {
2125                            line_layouts[(align_to.row() - rows.start) as usize]
2126                                .line
2127                                .x_for_index(align_to.column() as usize)
2128                        } else {
2129                            layout_line(align_to.row(), snapshot, style, cx)
2130                                .unwrap()
2131                                .x_for_index(align_to.column() as usize)
2132                        };
2133
2134                    block.render(&mut BlockContext {
2135                        view_context: cx,
2136                        anchor_x,
2137                        gutter_padding,
2138                        line_height,
2139                        gutter_width,
2140                        em_width,
2141                        block_id,
2142                        editor_style: &self.style,
2143                    })
2144                }
2145
2146                TransformBlock::ExcerptHeader {
2147                    buffer,
2148                    range,
2149                    starts_new_buffer,
2150                    ..
2151                } => {
2152                    let include_root = editor
2153                        .project
2154                        .as_ref()
2155                        .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
2156                        .unwrap_or_default();
2157                    let jump_icon = project::File::from_dyn(buffer.file()).map(|file| {
2158                        let jump_path = ProjectPath {
2159                            worktree_id: file.worktree_id(cx),
2160                            path: file.path.clone(),
2161                        };
2162                        let jump_anchor = range
2163                            .primary
2164                            .as_ref()
2165                            .map_or(range.context.start, |primary| primary.start);
2166                        let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
2167
2168                        IconButton::new(block_id, ui::Icon::ArrowUpRight)
2169                            .on_click(cx.listener_for(&self.editor, move |editor, e, cx| {
2170                                editor.jump(jump_path.clone(), jump_position, jump_anchor, cx);
2171                            }))
2172                            .tooltip(|cx| Tooltip::for_action("Jump to Buffer", &OpenExcerpts, cx))
2173                    });
2174
2175                    let element = if *starts_new_buffer {
2176                        let path = buffer.resolve_file_path(cx, include_root);
2177                        let mut filename = None;
2178                        let mut parent_path = None;
2179                        // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
2180                        if let Some(path) = path {
2181                            filename = path.file_name().map(|f| f.to_string_lossy().to_string());
2182                            parent_path = path
2183                                .parent()
2184                                .map(|p| SharedString::from(p.to_string_lossy().to_string() + "/"));
2185                        }
2186
2187                        h_stack()
2188                            .id("path header block")
2189                            .size_full()
2190                            .bg(gpui::red())
2191                            .child(
2192                                filename
2193                                    .map(SharedString::from)
2194                                    .unwrap_or_else(|| "untitled".into()),
2195                            )
2196                            .children(parent_path)
2197                            .children(jump_icon) // .p_x(gutter_padding)
2198                    } else {
2199                        let text_style = style.text.clone();
2200                        h_stack()
2201                            .id("collapsed context")
2202                            .size_full()
2203                            .bg(gpui::red())
2204                            .child("")
2205                            .children(jump_icon) // .p_x(gutter_padding)
2206                    };
2207                    element.into_any()
2208                }
2209            };
2210
2211            let size = element.measure(available_space, cx);
2212            (element, size)
2213        };
2214
2215        let mut fixed_block_max_width = Pixels::ZERO;
2216        let mut blocks = Vec::new();
2217        for (row, block) in fixed_blocks {
2218            let available_space = size(
2219                AvailableSpace::MinContent,
2220                AvailableSpace::Definite(block.height() as f32 * line_height),
2221            );
2222            let (element, element_size) =
2223                render_block(block, available_space, block_id, editor, cx);
2224            block_id += 1;
2225            fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
2226            blocks.push(BlockLayout {
2227                row,
2228                element,
2229                available_space,
2230                style: BlockStyle::Fixed,
2231            });
2232        }
2233        for (row, block) in non_fixed_blocks {
2234            let style = match block {
2235                TransformBlock::Custom(block) => block.style(),
2236                TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
2237            };
2238            let width = match style {
2239                BlockStyle::Sticky => editor_width,
2240                BlockStyle::Flex => editor_width
2241                    .max(fixed_block_max_width)
2242                    .max(gutter_width + scroll_width),
2243                BlockStyle::Fixed => unreachable!(),
2244            };
2245            let available_space = size(
2246                AvailableSpace::Definite(width),
2247                AvailableSpace::Definite(block.height() as f32 * line_height),
2248            );
2249            let (element, _) = render_block(block, available_space, block_id, editor, cx);
2250            block_id += 1;
2251            blocks.push(BlockLayout {
2252                row,
2253                element,
2254                available_space,
2255                style,
2256            });
2257        }
2258        (
2259            scroll_width.max(fixed_block_max_width - gutter_width),
2260            blocks,
2261        )
2262    }
2263
2264    fn paint_mouse_listeners(
2265        &mut self,
2266        bounds: Bounds<Pixels>,
2267        gutter_bounds: Bounds<Pixels>,
2268        text_bounds: Bounds<Pixels>,
2269        layout: &LayoutState,
2270        cx: &mut WindowContext,
2271    ) {
2272        let content_origin = text_bounds.origin + point(layout.gutter_margin, Pixels::ZERO);
2273        let interactive_bounds = InteractiveBounds {
2274            bounds: bounds.intersect(&cx.content_mask().bounds),
2275            stacking_order: cx.stacking_order().clone(),
2276        };
2277
2278        cx.on_mouse_event({
2279            let position_map = layout.position_map.clone();
2280            let editor = self.editor.clone();
2281            let interactive_bounds = interactive_bounds.clone();
2282
2283            move |event: &ScrollWheelEvent, phase, cx| {
2284                if phase != DispatchPhase::Bubble {
2285                    return;
2286                }
2287
2288                let should_cancel = editor.update(cx, |editor, cx| {
2289                    Self::scroll(editor, event, &position_map, &interactive_bounds, cx)
2290                });
2291                if should_cancel {
2292                    cx.stop_propagation();
2293                }
2294            }
2295        });
2296
2297        cx.on_mouse_event({
2298            let position_map = layout.position_map.clone();
2299            let editor = self.editor.clone();
2300            let stacking_order = cx.stacking_order().clone();
2301
2302            move |event: &MouseDownEvent, phase, cx| {
2303                if phase != DispatchPhase::Bubble {
2304                    return;
2305                }
2306
2307                let should_cancel = editor.update(cx, |editor, cx| {
2308                    Self::mouse_down(
2309                        editor,
2310                        event,
2311                        &position_map,
2312                        text_bounds,
2313                        gutter_bounds,
2314                        &stacking_order,
2315                        cx,
2316                    )
2317                });
2318
2319                if should_cancel {
2320                    cx.stop_propagation()
2321                }
2322            }
2323        });
2324
2325        cx.on_mouse_event({
2326            let position_map = layout.position_map.clone();
2327            let editor = self.editor.clone();
2328            let stacking_order = cx.stacking_order().clone();
2329
2330            move |event: &MouseUpEvent, phase, cx| {
2331                let should_cancel = editor.update(cx, |editor, cx| {
2332                    Self::mouse_up(
2333                        editor,
2334                        event,
2335                        &position_map,
2336                        text_bounds,
2337                        &stacking_order,
2338                        cx,
2339                    )
2340                });
2341
2342                if should_cancel {
2343                    cx.stop_propagation()
2344                }
2345            }
2346        });
2347        //todo!()
2348        // on_down(MouseButton::Right, {
2349        //     let position_map = layout.position_map.clone();
2350        //     move |event, editor, cx| {
2351        //         if !Self::mouse_right_down(
2352        //             editor,
2353        //             event.position,
2354        //             position_map.as_ref(),
2355        //             text_bounds,
2356        //             cx,
2357        //         ) {
2358        //             cx.propagate_event();
2359        //         }
2360        //     }
2361        // });
2362        cx.on_mouse_event({
2363            let position_map = layout.position_map.clone();
2364            let editor = self.editor.clone();
2365            let stacking_order = cx.stacking_order().clone();
2366
2367            move |event: &MouseMoveEvent, phase, cx| {
2368                if phase != DispatchPhase::Bubble {
2369                    return;
2370                }
2371
2372                let stop_propogating = editor.update(cx, |editor, cx| {
2373                    Self::mouse_moved(
2374                        editor,
2375                        event,
2376                        &position_map,
2377                        text_bounds,
2378                        gutter_bounds,
2379                        &stacking_order,
2380                        cx,
2381                    )
2382                });
2383
2384                if stop_propogating {
2385                    cx.stop_propagation()
2386                }
2387            }
2388        });
2389    }
2390}
2391
2392#[derive(Debug)]
2393pub struct LineWithInvisibles {
2394    pub line: ShapedLine,
2395    invisibles: Vec<Invisible>,
2396}
2397
2398impl LineWithInvisibles {
2399    fn from_chunks<'a>(
2400        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
2401        text_style: &TextStyle,
2402        max_line_len: usize,
2403        max_line_count: usize,
2404        line_number_layouts: &[Option<ShapedLine>],
2405        editor_mode: EditorMode,
2406        cx: &WindowContext,
2407    ) -> Vec<Self> {
2408        let mut layouts = Vec::with_capacity(max_line_count);
2409        let mut line = String::new();
2410        let mut invisibles = Vec::new();
2411        let mut styles = Vec::new();
2412        let mut non_whitespace_added = false;
2413        let mut row = 0;
2414        let mut line_exceeded_max_len = false;
2415        let font_size = text_style.font_size.to_pixels(cx.rem_size());
2416
2417        for highlighted_chunk in chunks.chain([HighlightedChunk {
2418            chunk: "\n",
2419            style: None,
2420            is_tab: false,
2421        }]) {
2422            for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
2423                if ix > 0 {
2424                    let shaped_line = cx
2425                        .text_system()
2426                        .shape_line(line.clone().into(), font_size, &styles)
2427                        .unwrap();
2428                    layouts.push(Self {
2429                        line: shaped_line,
2430                        invisibles: invisibles.drain(..).collect(),
2431                    });
2432
2433                    line.clear();
2434                    styles.clear();
2435                    row += 1;
2436                    line_exceeded_max_len = false;
2437                    non_whitespace_added = false;
2438                    if row == max_line_count {
2439                        return layouts;
2440                    }
2441                }
2442
2443                if !line_chunk.is_empty() && !line_exceeded_max_len {
2444                    let text_style = if let Some(style) = highlighted_chunk.style {
2445                        Cow::Owned(text_style.clone().highlight(style))
2446                    } else {
2447                        Cow::Borrowed(text_style)
2448                    };
2449
2450                    if line.len() + line_chunk.len() > max_line_len {
2451                        let mut chunk_len = max_line_len - line.len();
2452                        while !line_chunk.is_char_boundary(chunk_len) {
2453                            chunk_len -= 1;
2454                        }
2455                        line_chunk = &line_chunk[..chunk_len];
2456                        line_exceeded_max_len = true;
2457                    }
2458
2459                    styles.push(TextRun {
2460                        len: line_chunk.len(),
2461                        font: text_style.font(),
2462                        color: text_style.color,
2463                        background_color: text_style.background_color,
2464                        underline: text_style.underline,
2465                    });
2466
2467                    if editor_mode == EditorMode::Full {
2468                        // Line wrap pads its contents with fake whitespaces,
2469                        // avoid printing them
2470                        let inside_wrapped_string = line_number_layouts
2471                            .get(row)
2472                            .and_then(|layout| layout.as_ref())
2473                            .is_none();
2474                        if highlighted_chunk.is_tab {
2475                            if non_whitespace_added || !inside_wrapped_string {
2476                                invisibles.push(Invisible::Tab {
2477                                    line_start_offset: line.len(),
2478                                });
2479                            }
2480                        } else {
2481                            invisibles.extend(
2482                                line_chunk
2483                                    .chars()
2484                                    .enumerate()
2485                                    .filter(|(_, line_char)| {
2486                                        let is_whitespace = line_char.is_whitespace();
2487                                        non_whitespace_added |= !is_whitespace;
2488                                        is_whitespace
2489                                            && (non_whitespace_added || !inside_wrapped_string)
2490                                    })
2491                                    .map(|(whitespace_index, _)| Invisible::Whitespace {
2492                                        line_offset: line.len() + whitespace_index,
2493                                    }),
2494                            )
2495                        }
2496                    }
2497
2498                    line.push_str(line_chunk);
2499                }
2500            }
2501        }
2502
2503        layouts
2504    }
2505
2506    fn draw(
2507        &self,
2508        layout: &LayoutState,
2509        row: u32,
2510        content_origin: gpui::Point<Pixels>,
2511        whitespace_setting: ShowWhitespaceSetting,
2512        selection_ranges: &[Range<DisplayPoint>],
2513        cx: &mut WindowContext,
2514    ) {
2515        let line_height = layout.position_map.line_height;
2516        let line_y = line_height * row as f32 - layout.position_map.scroll_position.y;
2517
2518        self.line.paint(
2519            content_origin + gpui::point(-layout.position_map.scroll_position.x, line_y),
2520            line_height,
2521            cx,
2522        );
2523
2524        self.draw_invisibles(
2525            &selection_ranges,
2526            layout,
2527            content_origin,
2528            line_y,
2529            row,
2530            line_height,
2531            whitespace_setting,
2532            cx,
2533        );
2534    }
2535
2536    fn draw_invisibles(
2537        &self,
2538        selection_ranges: &[Range<DisplayPoint>],
2539        layout: &LayoutState,
2540        content_origin: gpui::Point<Pixels>,
2541        line_y: Pixels,
2542        row: u32,
2543        line_height: Pixels,
2544        whitespace_setting: ShowWhitespaceSetting,
2545        cx: &mut WindowContext,
2546    ) {
2547        let allowed_invisibles_regions = match whitespace_setting {
2548            ShowWhitespaceSetting::None => return,
2549            ShowWhitespaceSetting::Selection => Some(selection_ranges),
2550            ShowWhitespaceSetting::All => None,
2551        };
2552
2553        for invisible in &self.invisibles {
2554            let (&token_offset, invisible_symbol) = match invisible {
2555                Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
2556                Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
2557            };
2558
2559            let x_offset = self.line.x_for_index(token_offset);
2560            let invisible_offset =
2561                (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
2562            let origin = content_origin
2563                + gpui::point(
2564                    x_offset + invisible_offset - layout.position_map.scroll_position.x,
2565                    line_y,
2566                );
2567
2568            if let Some(allowed_regions) = allowed_invisibles_regions {
2569                let invisible_point = DisplayPoint::new(row, token_offset as u32);
2570                if !allowed_regions
2571                    .iter()
2572                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
2573                {
2574                    continue;
2575                }
2576            }
2577            invisible_symbol.paint(origin, line_height, cx);
2578        }
2579    }
2580}
2581
2582#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2583enum Invisible {
2584    Tab { line_start_offset: usize },
2585    Whitespace { line_offset: usize },
2586}
2587
2588impl Element for EditorElement {
2589    type State = ();
2590
2591    fn layout(
2592        &mut self,
2593        element_state: Option<Self::State>,
2594        cx: &mut gpui::WindowContext,
2595    ) -> (gpui::LayoutId, Self::State) {
2596        self.editor.update(cx, |editor, cx| {
2597            editor.set_style(self.style.clone(), cx);
2598
2599            let layout_id = match editor.mode {
2600                EditorMode::SingleLine => {
2601                    let rem_size = cx.rem_size();
2602                    let mut style = Style::default();
2603                    style.size.width = relative(1.).into();
2604                    style.size.height = self.style.text.line_height_in_pixels(rem_size).into();
2605                    cx.request_layout(&style, None)
2606                }
2607                EditorMode::AutoHeight { max_lines } => {
2608                    let editor_handle = cx.view().clone();
2609                    let max_line_number_width =
2610                        self.max_line_number_width(&editor.snapshot(cx), cx);
2611                    cx.request_measured_layout(
2612                        Style::default(),
2613                        move |known_dimensions, available_space, cx| {
2614                            editor_handle
2615                                .update(cx, |editor, cx| {
2616                                    dbg!(compute_auto_height_layout(
2617                                        editor,
2618                                        max_lines,
2619                                        max_line_number_width,
2620                                        known_dimensions,
2621                                        cx,
2622                                    ))
2623                                })
2624                                .unwrap_or_default()
2625                        },
2626                    )
2627                }
2628                EditorMode::Full => {
2629                    let mut style = Style::default();
2630                    style.size.width = relative(1.).into();
2631                    style.size.height = relative(1.).into();
2632                    cx.request_layout(&style, None)
2633                }
2634            };
2635
2636            (layout_id, ())
2637        })
2638    }
2639
2640    fn paint(
2641        mut self,
2642        bounds: Bounds<gpui::Pixels>,
2643        element_state: &mut Self::State,
2644        cx: &mut gpui::WindowContext,
2645    ) {
2646        let editor = self.editor.clone();
2647
2648        let mut layout = self.compute_layout(bounds, cx);
2649        let gutter_bounds = Bounds {
2650            origin: bounds.origin,
2651            size: layout.gutter_size,
2652        };
2653        let text_bounds = Bounds {
2654            origin: gutter_bounds.upper_right(),
2655            size: layout.text_size,
2656        };
2657
2658        let focus_handle = editor.focus_handle(cx);
2659        let dispatch_context = self.editor.read(cx).dispatch_context(cx);
2660        cx.with_key_dispatch(dispatch_context, Some(focus_handle.clone()), |_, cx| {
2661            self.register_actions(cx);
2662
2663            // We call with_z_index to establish a new stacking context.
2664            cx.with_z_index(0, |cx| {
2665                cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
2666                    // Paint mouse listeners at z-index 0 so any elements we paint on top of the editor
2667                    // take precedence.
2668                    cx.with_z_index(0, |cx| {
2669                        self.paint_mouse_listeners(bounds, gutter_bounds, text_bounds, &layout, cx);
2670                    });
2671                    let input_handler = ElementInputHandler::new(bounds, self.editor.clone(), cx);
2672                    cx.handle_input(&focus_handle, input_handler);
2673
2674                    self.paint_background(gutter_bounds, text_bounds, &layout, cx);
2675                    if layout.gutter_size.width > Pixels::ZERO {
2676                        self.paint_gutter(gutter_bounds, &mut layout, cx);
2677                    }
2678                    self.paint_text(text_bounds, &mut layout, cx);
2679
2680                    if !layout.blocks.is_empty() {
2681                        cx.with_element_id(Some("editor_blocks"), |cx| {
2682                            self.paint_blocks(bounds, &mut layout, cx);
2683                        })
2684                    }
2685                });
2686            });
2687        })
2688    }
2689}
2690
2691impl IntoElement for EditorElement {
2692    type Element = Self;
2693
2694    fn element_id(&self) -> Option<gpui::ElementId> {
2695        self.editor.element_id()
2696    }
2697
2698    fn into_element(self) -> Self::Element {
2699        self
2700    }
2701}
2702
2703// impl EditorElement {
2704//     type LayoutState = LayoutState;
2705//     type PaintState = ();
2706
2707//     fn layout(
2708//         &mut self,
2709//         constraint: SizeConstraint,
2710//         editor: &mut Editor,
2711//         cx: &mut ViewContext<Editor>,
2712//     ) -> (gpui::Point<Pixels>, Self::LayoutState) {
2713//         let mut size = constraint.max;
2714//         if size.x.is_infinite() {
2715//             unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
2716//         }
2717
2718//         let snapshot = editor.snapshot(cx);
2719//         let style = self.style.clone();
2720
2721//         let line_height = (style.text.font_size * style.line_height_scalar).round();
2722
2723//         let gutter_padding;
2724//         let gutter_width;
2725//         let gutter_margin;
2726//         if snapshot.show_gutter {
2727//             let em_width = style.text.em_width(cx.font_cache());
2728//             gutter_padding = (em_width * style.gutter_padding_factor).round();
2729//             gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
2730//             gutter_margin = -style.text.descent(cx.font_cache());
2731//         } else {
2732//             gutter_padding = 0.0;
2733//             gutter_width = 0.0;
2734//             gutter_margin = 0.0;
2735//         };
2736
2737//         let text_width = size.x - gutter_width;
2738//         let em_width = style.text.em_width(cx.font_cache());
2739//         let em_advance = style.text.em_advance(cx.font_cache());
2740//         let overscroll = point(em_width, 0.);
2741//         let snapshot = {
2742//             editor.set_visible_line_count(size.y / line_height, cx);
2743
2744//             let editor_width = text_width - gutter_margin - overscroll.x - em_width;
2745//             let wrap_width = match editor.soft_wrap_mode(cx) {
2746//                 SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
2747//                 SoftWrap::EditorWidth => editor_width,
2748//                 SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
2749//             };
2750
2751//             if editor.set_wrap_width(Some(wrap_width), cx) {
2752//                 editor.snapshot(cx)
2753//             } else {
2754//                 snapshot
2755//             }
2756//         };
2757
2758//         let wrap_guides = editor
2759//             .wrap_guides(cx)
2760//             .iter()
2761//             .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
2762//             .collect();
2763
2764//         let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
2765//         if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
2766//             size.set_y(
2767//                 scroll_height
2768//                     .min(constraint.max_along(Axis::Vertical))
2769//                     .max(constraint.min_along(Axis::Vertical))
2770//                     .max(line_height)
2771//                     .min(line_height * max_lines as f32),
2772//             )
2773//         } else if let EditorMode::SingleLine = snapshot.mode {
2774//             size.set_y(line_height.max(constraint.min_along(Axis::Vertical)))
2775//         } else if size.y.is_infinite() {
2776//             size.set_y(scroll_height);
2777//         }
2778//         let gutter_size = point(gutter_width, size.y);
2779//         let text_size = point(text_width, size.y);
2780
2781//         let autoscroll_horizontally = editor.autoscroll_vertically(size.y, line_height, cx);
2782//         let mut snapshot = editor.snapshot(cx);
2783
2784//         let scroll_position = snapshot.scroll_position();
2785//         // The scroll position is a fractional point, the whole number of which represents
2786//         // the top of the window in terms of display rows.
2787//         let start_row = scroll_position.y as u32;
2788//         let height_in_lines = size.y / line_height;
2789//         let max_row = snapshot.max_point().row();
2790
2791//         // Add 1 to ensure selections bleed off screen
2792//         let end_row = 1 + cmp::min(
2793//             (scroll_position.y + height_in_lines).ceil() as u32,
2794//             max_row,
2795//         );
2796
2797//         let start_anchor = if start_row == 0 {
2798//             Anchor::min()
2799//         } else {
2800//             snapshot
2801//                 .buffer_snapshot
2802//                 .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
2803//         };
2804//         let end_anchor = if end_row > max_row {
2805//             Anchor::max
2806//         } else {
2807//             snapshot
2808//                 .buffer_snapshot
2809//                 .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
2810//         };
2811
2812//         let mut selections: Vec<(SelectionStyle, Vec<SelectionLayout>)> = Vec::new();
2813//         let mut active_rows = BTreeMap::new();
2814//         let mut fold_ranges = Vec::new();
2815//         let is_singleton = editor.is_singleton(cx);
2816
2817//         let highlighted_rows = editor.highlighted_rows();
2818//         let theme = theme::current(cx);
2819//         let highlighted_ranges = editor.background_highlights_in_range(
2820//             start_anchor..end_anchor,
2821//             &snapshot.display_snapshot,
2822//             theme.as_ref(),
2823//         );
2824
2825//         fold_ranges.extend(
2826//             snapshot
2827//                 .folds_in_range(start_anchor..end_anchor)
2828//                 .map(|anchor| {
2829//                     let start = anchor.start.to_point(&snapshot.buffer_snapshot);
2830//                     (
2831//                         start.row,
2832//                         start.to_display_point(&snapshot.display_snapshot)
2833//                             ..anchor.end.to_display_point(&snapshot),
2834//                     )
2835//                 }),
2836//         );
2837
2838//         let mut newest_selection_head = None;
2839
2840//         if editor.show_local_selections {
2841//             let mut local_selections: Vec<Selection<Point>> = editor
2842//                 .selections
2843//                 .disjoint_in_range(start_anchor..end_anchor, cx);
2844//             local_selections.extend(editor.selections.pending(cx));
2845//             let mut layouts = Vec::new();
2846//             let newest = editor.selections.newest(cx);
2847//             for selection in local_selections.drain(..) {
2848//                 let is_empty = selection.start == selection.end;
2849//                 let is_newest = selection == newest;
2850
2851//                 let layout = SelectionLayout::new(
2852//                     selection,
2853//                     editor.selections.line_mode,
2854//                     editor.cursor_shape,
2855//                     &snapshot.display_snapshot,
2856//                     is_newest,
2857//                     true,
2858//                 );
2859//                 if is_newest {
2860//                     newest_selection_head = Some(layout.head);
2861//                 }
2862
2863//                 for row in cmp::max(layout.active_rows.start, start_row)
2864//                     ..=cmp::min(layout.active_rows.end, end_row)
2865//                 {
2866//                     let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
2867//                     *contains_non_empty_selection |= !is_empty;
2868//                 }
2869//                 layouts.push(layout);
2870//             }
2871
2872//             selections.push((style.selection, layouts));
2873//         }
2874
2875//         if let Some(collaboration_hub) = &editor.collaboration_hub {
2876//             // When following someone, render the local selections in their color.
2877//             if let Some(leader_id) = editor.leader_peer_id {
2878//                 if let Some(collaborator) = collaboration_hub.collaborators(cx).get(&leader_id) {
2879//                     if let Some(participant_index) = collaboration_hub
2880//                         .user_participant_indices(cx)
2881//                         .get(&collaborator.user_id)
2882//                     {
2883//                         if let Some((local_selection_style, _)) = selections.first_mut() {
2884//                             *local_selection_style =
2885//                                 style.selection_style_for_room_participant(participant_index.0);
2886//                         }
2887//                     }
2888//                 }
2889//             }
2890
2891//             let mut remote_selections = HashMap::default();
2892//             for selection in snapshot.remote_selections_in_range(
2893//                 &(start_anchor..end_anchor),
2894//                 collaboration_hub.as_ref(),
2895//                 cx,
2896//             ) {
2897//                 let selection_style = if let Some(participant_index) = selection.participant_index {
2898//                     style.selection_style_for_room_participant(participant_index.0)
2899//                 } else {
2900//                     style.absent_selection
2901//                 };
2902
2903//                 // Don't re-render the leader's selections, since the local selections
2904//                 // match theirs.
2905//                 if Some(selection.peer_id) == editor.leader_peer_id {
2906//                     continue;
2907//                 }
2908
2909//                 remote_selections
2910//                     .entry(selection.replica_id)
2911//                     .or_insert((selection_style, Vec::new()))
2912//                     .1
2913//                     .push(SelectionLayout::new(
2914//                         selection.selection,
2915//                         selection.line_mode,
2916//                         selection.cursor_shape,
2917//                         &snapshot.display_snapshot,
2918//                         false,
2919//                         false,
2920//                     ));
2921//             }
2922
2923//             selections.extend(remote_selections.into_values());
2924//         }
2925
2926//         let scrollbar_settings = &settings::get::<EditorSettings>(cx).scrollbar;
2927//         let show_scrollbars = match scrollbar_settings.show {
2928//             ShowScrollbar::Auto => {
2929//                 // Git
2930//                 (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_git_diffs())
2931//                 ||
2932//                 // Selections
2933//                 (is_singleton && scrollbar_settings.selections && !highlighted_ranges.is_empty)
2934//                 // Scrollmanager
2935//                 || editor.scroll_manager.scrollbars_visible()
2936//             }
2937//             ShowScrollbar::System => editor.scroll_manager.scrollbars_visible(),
2938//             ShowScrollbar::Always => true,
2939//             ShowScrollbar::Never => false,
2940//         };
2941
2942//         let fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)> = fold_ranges
2943//             .into_iter()
2944//             .map(|(id, fold)| {
2945//                 let color = self
2946//                     .style
2947//                     .folds
2948//                     .ellipses
2949//                     .background
2950//                     .style_for(&mut cx.mouse_state::<FoldMarkers>(id as usize))
2951//                     .color;
2952
2953//                 (id, fold, color)
2954//             })
2955//             .collect();
2956
2957//         let head_for_relative = newest_selection_head.unwrap_or_else(|| {
2958//             let newest = editor.selections.newest::<Point>(cx);
2959//             SelectionLayout::new(
2960//                 newest,
2961//                 editor.selections.line_mode,
2962//                 editor.cursor_shape,
2963//                 &snapshot.display_snapshot,
2964//                 true,
2965//                 true,
2966//             )
2967//             .head
2968//         });
2969
2970//         let (line_number_layouts, fold_statuses) = self.layout_line_numbers(
2971//             start_row..end_row,
2972//             &active_rows,
2973//             head_for_relative,
2974//             is_singleton,
2975//             &snapshot,
2976//             cx,
2977//         );
2978
2979//         let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
2980
2981//         let scrollbar_row_range = scroll_position.y..(scroll_position.y + height_in_lines);
2982
2983//         let mut max_visible_line_width = 0.0;
2984//         let line_layouts =
2985//             self.layout_lines(start_row..end_row, &line_number_layouts, &snapshot, cx);
2986//         for line_with_invisibles in &line_layouts {
2987//             if line_with_invisibles.line.width() > max_visible_line_width {
2988//                 max_visible_line_width = line_with_invisibles.line.width();
2989//             }
2990//         }
2991
2992//         let style = self.style.clone();
2993//         let longest_line_width = layout_line(
2994//             snapshot.longest_row(),
2995//             &snapshot,
2996//             &style,
2997//             cx.text_layout_cache(),
2998//         )
2999//         .width();
3000//         let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x;
3001//         let em_width = style.text.em_width(cx.font_cache());
3002//         let (scroll_width, blocks) = self.layout_blocks(
3003//             start_row..end_row,
3004//             &snapshot,
3005//             size.x,
3006//             scroll_width,
3007//             gutter_padding,
3008//             gutter_width,
3009//             em_width,
3010//             gutter_width + gutter_margin,
3011//             line_height,
3012//             &style,
3013//             &line_layouts,
3014//             editor,
3015//             cx,
3016//         );
3017
3018//         let scroll_max = point(
3019//             ((scroll_width - text_size.x) / em_width).max(0.0),
3020//             max_row as f32,
3021//         );
3022
3023//         let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
3024
3025//         let autoscrolled = if autoscroll_horizontally {
3026//             editor.autoscroll_horizontally(
3027//                 start_row,
3028//                 text_size.x,
3029//                 scroll_width,
3030//                 em_width,
3031//                 &line_layouts,
3032//                 cx,
3033//             )
3034//         } else {
3035//             false
3036//         };
3037
3038//         if clamped || autoscrolled {
3039//             snapshot = editor.snapshot(cx);
3040//         }
3041
3042//         let style = editor.style(cx);
3043
3044//         let mut context_menu = None;
3045//         let mut code_actions_indicator = None;
3046//         if let Some(newest_selection_head) = newest_selection_head {
3047//             if (start_row..end_row).contains(&newest_selection_head.row()) {
3048//                 if editor.context_menu_visible() {
3049//                     context_menu =
3050//                         editor.render_context_menu(newest_selection_head, style.clone(), cx);
3051//                 }
3052
3053//                 let active = matches!(
3054//                     editor.context_menu.read().as_ref(),
3055//                     Some(crate::ContextMenu::CodeActions(_))
3056//                 );
3057
3058//                 code_actions_indicator = editor
3059//                     .render_code_actions_indicator(&style, active, cx)
3060//                     .map(|indicator| (newest_selection_head.row(), indicator));
3061//             }
3062//         }
3063
3064//         let visible_rows = start_row..start_row + line_layouts.len() as u32;
3065//         let mut hover = editor.hover_state.render(
3066//             &snapshot,
3067//             &style,
3068//             visible_rows,
3069//             editor.workspace.as_ref().map(|(w, _)| w.clone()),
3070//             cx,
3071//         );
3072//         let mode = editor.mode;
3073
3074//         let mut fold_indicators = editor.render_fold_indicators(
3075//             fold_statuses,
3076//             &style,
3077//             editor.gutter_hovered,
3078//             line_height,
3079//             gutter_margin,
3080//             cx,
3081//         );
3082
3083//         if let Some((_, context_menu)) = context_menu.as_mut() {
3084//             context_menu.layout(
3085//                 SizeConstraint {
3086//                     min: gpui::Point::<Pixels>::zero(),
3087//                     max: point(
3088//                         cx.window_size().x * 0.7,
3089//                         (12. * line_height).min((size.y - line_height) / 2.),
3090//                     ),
3091//                 },
3092//                 editor,
3093//                 cx,
3094//             );
3095//         }
3096
3097//         if let Some((_, indicator)) = code_actions_indicator.as_mut() {
3098//             indicator.layout(
3099//                 SizeConstraint::strict_along(
3100//                     Axis::Vertical,
3101//                     line_height * style.code_actions.vertical_scale,
3102//                 ),
3103//                 editor,
3104//                 cx,
3105//             );
3106//         }
3107
3108//         for fold_indicator in fold_indicators.iter_mut() {
3109//             if let Some(indicator) = fold_indicator.as_mut() {
3110//                 indicator.layout(
3111//                     SizeConstraint::strict_along(
3112//                         Axis::Vertical,
3113//                         line_height * style.code_actions.vertical_scale,
3114//                     ),
3115//                     editor,
3116//                     cx,
3117//                 );
3118//             }
3119//         }
3120
3121//         if let Some((_, hover_popovers)) = hover.as_mut() {
3122//             for hover_popover in hover_popovers.iter_mut() {
3123//                 hover_popover.layout(
3124//                     SizeConstraint {
3125//                         min: gpui::Point::<Pixels>::zero(),
3126//                         max: point(
3127//                             (120. * em_width) // Default size
3128//                                 .min(size.x / 2.) // Shrink to half of the editor width
3129//                                 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
3130//                             (16. * line_height) // Default size
3131//                                 .min(size.y / 2.) // Shrink to half of the editor height
3132//                                 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
3133//                         ),
3134//                     },
3135//                     editor,
3136//                     cx,
3137//                 );
3138//             }
3139//         }
3140
3141//         let invisible_symbol_font_size = self.style.text.font_size / 2.0;
3142//         let invisible_symbol_style = RunStyle {
3143//             color: self.style.whitespace,
3144//             font_id: self.style.text.font_id,
3145//             underline: Default::default(),
3146//         };
3147
3148//         (
3149//             size,
3150//             LayoutState {
3151//                 mode,
3152//                 position_map: Arc::new(PositionMap {
3153//                     size,
3154//                     scroll_max,
3155//                     line_layouts,
3156//                     line_height,
3157//                     em_width,
3158//                     em_advance,
3159//                     snapshot,
3160//                 }),
3161//                 visible_display_row_range: start_row..end_row,
3162//                 wrap_guides,
3163//                 gutter_size,
3164//                 gutter_padding,
3165//                 text_size,
3166//                 scrollbar_row_range,
3167//                 show_scrollbars,
3168//                 is_singleton,
3169//                 max_row,
3170//                 gutter_margin,
3171//                 active_rows,
3172//                 highlighted_rows,
3173//                 highlighted_ranges,
3174//                 fold_ranges,
3175//                 line_number_layouts,
3176//                 display_hunks,
3177//                 blocks,
3178//                 selections,
3179//                 context_menu,
3180//                 code_actions_indicator,
3181//                 fold_indicators,
3182//                 tab_invisible: cx.text_layout_cache().layout_str(
3183//                     "→",
3184//                     invisible_symbol_font_size,
3185//                     &[("→".len(), invisible_symbol_style)],
3186//                 ),
3187//                 space_invisible: cx.text_layout_cache().layout_str(
3188//                     "•",
3189//                     invisible_symbol_font_size,
3190//                     &[("•".len(), invisible_symbol_style)],
3191//                 ),
3192//                 hover_popovers: hover,
3193//             },
3194//         )
3195//     }
3196
3197//     fn paint(
3198//         &mut self,
3199//         bounds: Bounds<Pixels>,
3200//         visible_bounds: Bounds<Pixels>,
3201//         layout: &mut Self::LayoutState,
3202//         editor: &mut Editor,
3203//         cx: &mut ViewContext<Editor>,
3204//     ) -> Self::PaintState {
3205//         let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
3206//         cx.scene().push_layer(Some(visible_bounds));
3207
3208//         let gutter_bounds = Bounds::<Pixels>::new(bounds.origin, layout.gutter_size);
3209//         let text_bounds = Bounds::<Pixels>::new(
3210//             bounds.origin + point(layout.gutter_size.x, 0.0),
3211//             layout.text_size,
3212//         );
3213
3214//         Self::attach_mouse_handlers(
3215//             &layout.position_map,
3216//             layout.hover_popovers.is_some(),
3217//             visible_bounds,
3218//             text_bounds,
3219//             gutter_bounds,
3220//             bounds,
3221//             cx,
3222//         );
3223
3224//         self.paint_background(gutter_bounds, text_bounds, layout, cx);
3225//         if layout.gutter_size.x > 0. {
3226//             self.paint_gutter(gutter_bounds, visible_bounds, layout, editor, cx);
3227//         }
3228//         self.paint_text(text_bounds, visible_bounds, layout, editor, cx);
3229
3230//         cx.scene().push_layer(Some(bounds));
3231//         if !layout.blocks.is_empty {
3232//             self.paint_blocks(bounds, visible_bounds, layout, editor, cx);
3233//         }
3234//         self.paint_scrollbar(bounds, layout, &editor, cx);
3235//         cx.scene().pop_layer();
3236//         cx.scene().pop_layer();
3237//     }
3238
3239//     fn rect_for_text_range(
3240//         &self,
3241//         range_utf16: Range<usize>,
3242//         bounds: Bounds<Pixels>,
3243//         _: Bounds<Pixels>,
3244//         layout: &Self::LayoutState,
3245//         _: &Self::PaintState,
3246//         _: &Editor,
3247//         _: &ViewContext<Editor>,
3248//     ) -> Option<Bounds<Pixels>> {
3249//         let text_bounds = Bounds::<Pixels>::new(
3250//             bounds.origin + point(layout.gutter_size.x, 0.0),
3251//             layout.text_size,
3252//         );
3253//         let content_origin = text_bounds.origin + point(layout.gutter_margin, 0.);
3254//         let scroll_position = layout.position_map.snapshot.scroll_position();
3255//         let start_row = scroll_position.y as u32;
3256//         let scroll_top = scroll_position.y * layout.position_map.line_height;
3257//         let scroll_left = scroll_position.x * layout.position_map.em_width;
3258
3259//         let range_start = OffsetUtf16(range_utf16.start)
3260//             .to_display_point(&layout.position_map.snapshot.display_snapshot);
3261//         if range_start.row() < start_row {
3262//             return None;
3263//         }
3264
3265//         let line = &layout
3266//             .position_map
3267//             .line_layouts
3268//             .get((range_start.row() - start_row) as usize)?
3269//             .line;
3270//         let range_start_x = line.x_for_index(range_start.column() as usize);
3271//         let range_start_y = range_start.row() as f32 * layout.position_map.line_height;
3272//         Some(Bounds::<Pixels>::new(
3273//             content_origin
3274//                 + point(
3275//                     range_start_x,
3276//                     range_start_y + layout.position_map.line_height,
3277//                 )
3278//                 - point(scroll_left, scroll_top),
3279//             point(
3280//                 layout.position_map.em_width,
3281//                 layout.position_map.line_height,
3282//             ),
3283//         ))
3284//     }
3285
3286//     fn debug(
3287//         &self,
3288//         bounds: Bounds<Pixels>,
3289//         _: &Self::LayoutState,
3290//         _: &Self::PaintState,
3291//         _: &Editor,
3292//         _: &ViewContext<Editor>,
3293//     ) -> json::Value {
3294//         json!({
3295//             "type": "BufferElement",
3296//             "bounds": bounds.to_json()
3297//         })
3298//     }
3299// }
3300
3301type BufferRow = u32;
3302
3303pub struct LayoutState {
3304    position_map: Arc<PositionMap>,
3305    gutter_size: Size<Pixels>,
3306    gutter_padding: Pixels,
3307    gutter_margin: Pixels,
3308    text_size: gpui::Size<Pixels>,
3309    mode: EditorMode,
3310    wrap_guides: SmallVec<[(Pixels, bool); 2]>,
3311    visible_anchor_range: Range<Anchor>,
3312    visible_display_row_range: Range<u32>,
3313    active_rows: BTreeMap<u32, bool>,
3314    highlighted_rows: Option<Range<u32>>,
3315    line_numbers: Vec<Option<ShapedLine>>,
3316    display_hunks: Vec<DisplayDiffHunk>,
3317    blocks: Vec<BlockLayout>,
3318    highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
3319    selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
3320    scrollbar_row_range: Range<f32>,
3321    show_scrollbars: bool,
3322    is_singleton: bool,
3323    max_row: u32,
3324    context_menu: Option<(DisplayPoint, AnyElement)>,
3325    code_actions_indicator: Option<CodeActionsIndicator>,
3326    hover_popovers: Option<(DisplayPoint, Vec<AnyElement>)>,
3327    fold_indicators: Vec<Option<IconButton>>,
3328    tab_invisible: ShapedLine,
3329    space_invisible: ShapedLine,
3330}
3331
3332struct CodeActionsIndicator {
3333    row: u32,
3334    button: IconButton,
3335}
3336
3337struct PositionMap {
3338    size: Size<Pixels>,
3339    line_height: Pixels,
3340    scroll_position: gpui::Point<Pixels>,
3341    scroll_max: gpui::Point<f32>,
3342    em_width: Pixels,
3343    em_advance: Pixels,
3344    line_layouts: Vec<LineWithInvisibles>,
3345    snapshot: EditorSnapshot,
3346}
3347
3348#[derive(Debug, Copy, Clone)]
3349pub struct PointForPosition {
3350    pub previous_valid: DisplayPoint,
3351    pub next_valid: DisplayPoint,
3352    pub exact_unclipped: DisplayPoint,
3353    pub column_overshoot_after_line_end: u32,
3354}
3355
3356impl PointForPosition {
3357    #[cfg(test)]
3358    pub fn valid(valid: DisplayPoint) -> Self {
3359        Self {
3360            previous_valid: valid,
3361            next_valid: valid,
3362            exact_unclipped: valid,
3363            column_overshoot_after_line_end: 0,
3364        }
3365    }
3366
3367    pub fn as_valid(&self) -> Option<DisplayPoint> {
3368        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
3369            Some(self.previous_valid)
3370        } else {
3371            None
3372        }
3373    }
3374}
3375
3376impl PositionMap {
3377    fn point_for_position(
3378        &self,
3379        text_bounds: Bounds<Pixels>,
3380        position: gpui::Point<Pixels>,
3381    ) -> PointForPosition {
3382        let scroll_position = self.snapshot.scroll_position();
3383        let position = position - text_bounds.origin;
3384        let y = position.y.max(px(0.)).min(self.size.width);
3385        let x = position.x + (scroll_position.x * self.em_width);
3386        let row = (f32::from(y / self.line_height) + scroll_position.y) as u32;
3387
3388        let (column, x_overshoot_after_line_end) = if let Some(line) = self
3389            .line_layouts
3390            .get(row as usize - scroll_position.y as usize)
3391            .map(|&LineWithInvisibles { ref line, .. }| line)
3392        {
3393            if let Some(ix) = line.index_for_x(x) {
3394                (ix as u32, px(0.))
3395            } else {
3396                (line.len as u32, px(0.).max(x - line.width))
3397            }
3398        } else {
3399            (0, x)
3400        };
3401
3402        let mut exact_unclipped = DisplayPoint::new(row, column);
3403        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
3404        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
3405
3406        let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
3407        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
3408        PointForPosition {
3409            previous_valid,
3410            next_valid,
3411            exact_unclipped,
3412            column_overshoot_after_line_end,
3413        }
3414    }
3415}
3416
3417struct BlockLayout {
3418    row: u32,
3419    element: AnyElement,
3420    available_space: Size<AvailableSpace>,
3421    style: BlockStyle,
3422}
3423
3424fn layout_line(
3425    row: u32,
3426    snapshot: &EditorSnapshot,
3427    style: &EditorStyle,
3428    cx: &WindowContext,
3429) -> Result<ShapedLine> {
3430    let mut line = snapshot.line(row);
3431
3432    if line.len() > MAX_LINE_LEN {
3433        let mut len = MAX_LINE_LEN;
3434        while !line.is_char_boundary(len) {
3435            len -= 1;
3436        }
3437
3438        line.truncate(len);
3439    }
3440
3441    cx.text_system().shape_line(
3442        line.into(),
3443        style.text.font_size.to_pixels(cx.rem_size()),
3444        &[TextRun {
3445            len: snapshot.line_len(row) as usize,
3446            font: style.text.font(),
3447            color: Hsla::default(),
3448            background_color: None,
3449            underline: None,
3450        }],
3451    )
3452}
3453
3454#[derive(Debug)]
3455pub struct Cursor {
3456    origin: gpui::Point<Pixels>,
3457    block_width: Pixels,
3458    line_height: Pixels,
3459    color: Hsla,
3460    shape: CursorShape,
3461    block_text: Option<ShapedLine>,
3462}
3463
3464impl Cursor {
3465    pub fn new(
3466        origin: gpui::Point<Pixels>,
3467        block_width: Pixels,
3468        line_height: Pixels,
3469        color: Hsla,
3470        shape: CursorShape,
3471        block_text: Option<ShapedLine>,
3472    ) -> Cursor {
3473        Cursor {
3474            origin,
3475            block_width,
3476            line_height,
3477            color,
3478            shape,
3479            block_text,
3480        }
3481    }
3482
3483    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
3484        Bounds {
3485            origin: self.origin + origin,
3486            size: size(self.block_width, self.line_height),
3487        }
3488    }
3489
3490    pub fn paint(&self, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
3491        let bounds = match self.shape {
3492            CursorShape::Bar => Bounds {
3493                origin: self.origin + origin,
3494                size: size(px(2.0), self.line_height),
3495            },
3496            CursorShape::Block | CursorShape::Hollow => Bounds {
3497                origin: self.origin + origin,
3498                size: size(self.block_width, self.line_height),
3499            },
3500            CursorShape::Underscore => Bounds {
3501                origin: self.origin
3502                    + origin
3503                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
3504                size: size(self.block_width, px(2.0)),
3505            },
3506        };
3507
3508        //Draw background or border quad
3509        if matches!(self.shape, CursorShape::Hollow) {
3510            cx.paint_quad(
3511                bounds,
3512                Corners::default(),
3513                transparent_black(),
3514                Edges::all(px(1.)),
3515                self.color,
3516            );
3517        } else {
3518            cx.paint_quad(
3519                bounds,
3520                Corners::default(),
3521                self.color,
3522                Edges::default(),
3523                transparent_black(),
3524            );
3525        }
3526
3527        if let Some(block_text) = &self.block_text {
3528            block_text.paint(self.origin + origin, self.line_height, cx);
3529        }
3530    }
3531
3532    pub fn shape(&self) -> CursorShape {
3533        self.shape
3534    }
3535}
3536
3537#[derive(Debug)]
3538pub struct HighlightedRange {
3539    pub start_y: Pixels,
3540    pub line_height: Pixels,
3541    pub lines: Vec<HighlightedRangeLine>,
3542    pub color: Hsla,
3543    pub corner_radius: Pixels,
3544}
3545
3546#[derive(Debug)]
3547pub struct HighlightedRangeLine {
3548    pub start_x: Pixels,
3549    pub end_x: Pixels,
3550}
3551
3552impl HighlightedRange {
3553    pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut WindowContext) {
3554        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
3555            self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
3556            self.paint_lines(
3557                self.start_y + self.line_height,
3558                &self.lines[1..],
3559                bounds,
3560                cx,
3561            );
3562        } else {
3563            self.paint_lines(self.start_y, &self.lines, bounds, cx);
3564        }
3565    }
3566
3567    fn paint_lines(
3568        &self,
3569        start_y: Pixels,
3570        lines: &[HighlightedRangeLine],
3571        bounds: Bounds<Pixels>,
3572        cx: &mut WindowContext,
3573    ) {
3574        if lines.is_empty() {
3575            return;
3576        }
3577
3578        let first_line = lines.first().unwrap();
3579        let last_line = lines.last().unwrap();
3580
3581        let first_top_left = point(first_line.start_x, start_y);
3582        let first_top_right = point(first_line.end_x, start_y);
3583
3584        let curve_height = point(Pixels::ZERO, self.corner_radius);
3585        let curve_width = |start_x: Pixels, end_x: Pixels| {
3586            let max = (end_x - start_x) / 2.;
3587            let width = if max < self.corner_radius {
3588                max
3589            } else {
3590                self.corner_radius
3591            };
3592
3593            point(width, Pixels::ZERO)
3594        };
3595
3596        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
3597        let mut path = gpui::Path::new(first_top_right - top_curve_width);
3598        path.curve_to(first_top_right + curve_height, first_top_right);
3599
3600        let mut iter = lines.iter().enumerate().peekable();
3601        while let Some((ix, line)) = iter.next() {
3602            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
3603
3604            if let Some((_, next_line)) = iter.peek() {
3605                let next_top_right = point(next_line.end_x, bottom_right.y);
3606
3607                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
3608                    Ordering::Equal => {
3609                        path.line_to(bottom_right);
3610                    }
3611                    Ordering::Less => {
3612                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
3613                        path.line_to(bottom_right - curve_height);
3614                        if self.corner_radius > Pixels::ZERO {
3615                            path.curve_to(bottom_right - curve_width, bottom_right);
3616                        }
3617                        path.line_to(next_top_right + curve_width);
3618                        if self.corner_radius > Pixels::ZERO {
3619                            path.curve_to(next_top_right + curve_height, next_top_right);
3620                        }
3621                    }
3622                    Ordering::Greater => {
3623                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
3624                        path.line_to(bottom_right - curve_height);
3625                        if self.corner_radius > Pixels::ZERO {
3626                            path.curve_to(bottom_right + curve_width, bottom_right);
3627                        }
3628                        path.line_to(next_top_right - curve_width);
3629                        if self.corner_radius > Pixels::ZERO {
3630                            path.curve_to(next_top_right + curve_height, next_top_right);
3631                        }
3632                    }
3633                }
3634            } else {
3635                let curve_width = curve_width(line.start_x, line.end_x);
3636                path.line_to(bottom_right - curve_height);
3637                if self.corner_radius > Pixels::ZERO {
3638                    path.curve_to(bottom_right - curve_width, bottom_right);
3639                }
3640
3641                let bottom_left = point(line.start_x, bottom_right.y);
3642                path.line_to(bottom_left + curve_width);
3643                if self.corner_radius > Pixels::ZERO {
3644                    path.curve_to(bottom_left - curve_height, bottom_left);
3645                }
3646            }
3647        }
3648
3649        if first_line.start_x > last_line.start_x {
3650            let curve_width = curve_width(last_line.start_x, first_line.start_x);
3651            let second_top_left = point(last_line.start_x, start_y + self.line_height);
3652            path.line_to(second_top_left + curve_height);
3653            if self.corner_radius > Pixels::ZERO {
3654                path.curve_to(second_top_left + curve_width, second_top_left);
3655            }
3656            let first_bottom_left = point(first_line.start_x, second_top_left.y);
3657            path.line_to(first_bottom_left - curve_width);
3658            if self.corner_radius > Pixels::ZERO {
3659                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
3660            }
3661        }
3662
3663        path.line_to(first_top_left + curve_height);
3664        if self.corner_radius > Pixels::ZERO {
3665            path.curve_to(first_top_left + top_curve_width, first_top_left);
3666        }
3667        path.line_to(first_top_right - top_curve_width);
3668
3669        cx.paint_path(path, self.color);
3670    }
3671}
3672
3673pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
3674    (delta.pow(1.5) / 100.0).into()
3675}
3676
3677fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
3678    (delta.pow(1.2) / 300.0).into()
3679}
3680
3681// #[cfg(test)]
3682// mod tests {
3683//     use super::*;
3684//     use crate::{
3685//         display_map::{BlockDisposition, BlockProperties},
3686//         editor_tests::{init_test, update_test_language_settings},
3687//         Editor, MultiBuffer,
3688//     };
3689//     use gpui::TestAppContext;
3690//     use language::language_settings;
3691//     use log::info;
3692//     use std::{num::NonZeroU32, sync::Arc};
3693//     use util::test::sample_text;
3694
3695//     #[gpui::test]
3696//     fn test_layout_line_numbers(cx: &mut TestAppContext) {
3697//         init_test(cx, |_| {});
3698//         let editor = cx
3699//             .add_window(|cx| {
3700//                 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
3701//                 Editor::new(EditorMode::Full, buffer, None, None, cx)
3702//             })
3703//             .root(cx);
3704//         let element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3705
3706//         let layouts = editor.update(cx, |editor, cx| {
3707//             let snapshot = editor.snapshot(cx);
3708//             element
3709//                 .layout_line_numbers(
3710//                     0..6,
3711//                     &Default::default(),
3712//                     DisplayPoint::new(0, 0),
3713//                     false,
3714//                     &snapshot,
3715//                     cx,
3716//                 )
3717//                 .0
3718//         });
3719//         assert_eq!(layouts.len(), 6);
3720
3721//         let relative_rows = editor.update(cx, |editor, cx| {
3722//             let snapshot = editor.snapshot(cx);
3723//             element.calculate_relative_line_numbers(&snapshot, &(0..6), Some(3))
3724//         });
3725//         assert_eq!(relative_rows[&0], 3);
3726//         assert_eq!(relative_rows[&1], 2);
3727//         assert_eq!(relative_rows[&2], 1);
3728//         // current line has no relative number
3729//         assert_eq!(relative_rows[&4], 1);
3730//         assert_eq!(relative_rows[&5], 2);
3731
3732//         // works if cursor is before screen
3733//         let relative_rows = editor.update(cx, |editor, cx| {
3734//             let snapshot = editor.snapshot(cx);
3735
3736//             element.calculate_relative_line_numbers(&snapshot, &(3..6), Some(1))
3737//         });
3738//         assert_eq!(relative_rows.len(), 3);
3739//         assert_eq!(relative_rows[&3], 2);
3740//         assert_eq!(relative_rows[&4], 3);
3741//         assert_eq!(relative_rows[&5], 4);
3742
3743//         // works if cursor is after screen
3744//         let relative_rows = editor.update(cx, |editor, cx| {
3745//             let snapshot = editor.snapshot(cx);
3746
3747//             element.calculate_relative_line_numbers(&snapshot, &(0..3), Some(6))
3748//         });
3749//         assert_eq!(relative_rows.len(), 3);
3750//         assert_eq!(relative_rows[&0], 5);
3751//         assert_eq!(relative_rows[&1], 4);
3752//         assert_eq!(relative_rows[&2], 3);
3753//     }
3754
3755//     #[gpui::test]
3756//     async fn test_vim_visual_selections(cx: &mut TestAppContext) {
3757//         init_test(cx, |_| {});
3758
3759//         let editor = cx
3760//             .add_window(|cx| {
3761//                 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
3762//                 Editor::new(EditorMode::Full, buffer, None, None, cx)
3763//             })
3764//             .root(cx);
3765//         let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3766//         let (_, state) = editor.update(cx, |editor, cx| {
3767//             editor.cursor_shape = CursorShape::Block;
3768//             editor.change_selections(None, cx, |s| {
3769//                 s.select_ranges([
3770//                     Point::new(0, 0)..Point::new(1, 0),
3771//                     Point::new(3, 2)..Point::new(3, 3),
3772//                     Point::new(5, 6)..Point::new(6, 0),
3773//                 ]);
3774//             });
3775//             element.layout(
3776//                 SizeConstraint::new(point(500., 500.), point(500., 500.)),
3777//                 editor,
3778//                 cx,
3779//             )
3780//         });
3781//         assert_eq!(state.selections.len(), 1);
3782//         let local_selections = &state.selections[0].1;
3783//         assert_eq!(local_selections.len(), 3);
3784//         // moves cursor back one line
3785//         assert_eq!(local_selections[0].head, DisplayPoint::new(0, 6));
3786//         assert_eq!(
3787//             local_selections[0].range,
3788//             DisplayPoint::new(0, 0)..DisplayPoint::new(1, 0)
3789//         );
3790
3791//         // moves cursor back one column
3792//         assert_eq!(
3793//             local_selections[1].range,
3794//             DisplayPoint::new(3, 2)..DisplayPoint::new(3, 3)
3795//         );
3796//         assert_eq!(local_selections[1].head, DisplayPoint::new(3, 2));
3797
3798//         // leaves cursor on the max point
3799//         assert_eq!(
3800//             local_selections[2].range,
3801//             DisplayPoint::new(5, 6)..DisplayPoint::new(6, 0)
3802//         );
3803//         assert_eq!(local_selections[2].head, DisplayPoint::new(6, 0));
3804
3805//         // active lines does not include 1 (even though the range of the selection does)
3806//         assert_eq!(
3807//             state.active_rows.keys().cloned().collect::<Vec<u32>>(),
3808//             vec![0, 3, 5, 6]
3809//         );
3810
3811//         // multi-buffer support
3812//         // in DisplayPoint co-ordinates, this is what we're dealing with:
3813//         //  0: [[file
3814//         //  1:   header]]
3815//         //  2: aaaaaa
3816//         //  3: bbbbbb
3817//         //  4: cccccc
3818//         //  5:
3819//         //  6: ...
3820//         //  7: ffffff
3821//         //  8: gggggg
3822//         //  9: hhhhhh
3823//         // 10:
3824//         // 11: [[file
3825//         // 12:   header]]
3826//         // 13: bbbbbb
3827//         // 14: cccccc
3828//         // 15: dddddd
3829//         let editor = cx
3830//             .add_window(|cx| {
3831//                 let buffer = MultiBuffer::build_multi(
3832//                     [
3833//                         (
3834//                             &(sample_text(8, 6, 'a') + "\n"),
3835//                             vec![
3836//                                 Point::new(0, 0)..Point::new(3, 0),
3837//                                 Point::new(4, 0)..Point::new(7, 0),
3838//                             ],
3839//                         ),
3840//                         (
3841//                             &(sample_text(8, 6, 'a') + "\n"),
3842//                             vec![Point::new(1, 0)..Point::new(3, 0)],
3843//                         ),
3844//                     ],
3845//                     cx,
3846//                 );
3847//                 Editor::new(EditorMode::Full, buffer, None, None, cx)
3848//             })
3849//             .root(cx);
3850//         let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3851//         let (_, state) = editor.update(cx, |editor, cx| {
3852//             editor.cursor_shape = CursorShape::Block;
3853//             editor.change_selections(None, cx, |s| {
3854//                 s.select_display_ranges([
3855//                     DisplayPoint::new(4, 0)..DisplayPoint::new(7, 0),
3856//                     DisplayPoint::new(10, 0)..DisplayPoint::new(13, 0),
3857//                 ]);
3858//             });
3859//             element.layout(
3860//                 SizeConstraint::new(point(500., 500.), point(500., 500.)),
3861//                 editor,
3862//                 cx,
3863//             )
3864//         });
3865
3866//         assert_eq!(state.selections.len(), 1);
3867//         let local_selections = &state.selections[0].1;
3868//         assert_eq!(local_selections.len(), 2);
3869
3870//         // moves cursor on excerpt boundary back a line
3871//         // and doesn't allow selection to bleed through
3872//         assert_eq!(
3873//             local_selections[0].range,
3874//             DisplayPoint::new(4, 0)..DisplayPoint::new(6, 0)
3875//         );
3876//         assert_eq!(local_selections[0].head, DisplayPoint::new(5, 0));
3877
3878//         // moves cursor on buffer boundary back two lines
3879//         // and doesn't allow selection to bleed through
3880//         assert_eq!(
3881//             local_selections[1].range,
3882//             DisplayPoint::new(10, 0)..DisplayPoint::new(11, 0)
3883//         );
3884//         assert_eq!(local_selections[1].head, DisplayPoint::new(10, 0));
3885//     }
3886
3887//     #[gpui::test]
3888//     fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
3889//         init_test(cx, |_| {});
3890
3891//         let editor = cx
3892//             .add_window(|cx| {
3893//                 let buffer = MultiBuffer::build_simple("", cx);
3894//                 Editor::new(EditorMode::Full, buffer, None, None, cx)
3895//             })
3896//             .root(cx);
3897
3898//         editor.update(cx, |editor, cx| {
3899//             editor.set_placeholder_text("hello", cx);
3900//             editor.insert_blocks(
3901//                 [BlockProperties {
3902//                     style: BlockStyle::Fixed,
3903//                     disposition: BlockDisposition::Above,
3904//                     height: 3,
3905//                     position: Anchor::min(),
3906//                     render: Arc::new(|_| Empty::new().into_any),
3907//                 }],
3908//                 None,
3909//                 cx,
3910//             );
3911
3912//             // Blur the editor so that it displays placeholder text.
3913//             cx.blur();
3914//         });
3915
3916//         let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3917//         let (size, mut state) = editor.update(cx, |editor, cx| {
3918//             element.layout(
3919//                 SizeConstraint::new(point(500., 500.), point(500., 500.)),
3920//                 editor,
3921//                 cx,
3922//             )
3923//         });
3924
3925//         assert_eq!(state.position_map.line_layouts.len(), 4);
3926//         assert_eq!(
3927//             state
3928//                 .line_number_layouts
3929//                 .iter()
3930//                 .map(Option::is_some)
3931//                 .collect::<Vec<_>>(),
3932//             &[false, false, false, true]
3933//         );
3934
3935//         // Don't panic.
3936//         let bounds = Bounds::<Pixels>::new(Default::default(), size);
3937//         editor.update(cx, |editor, cx| {
3938//             element.paint(bounds, bounds, &mut state, editor, cx);
3939//         });
3940//     }
3941
3942//     #[gpui::test]
3943//     fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
3944//         const TAB_SIZE: u32 = 4;
3945
3946//         let input_text = "\t \t|\t| a b";
3947//         let expected_invisibles = vec![
3948//             Invisible::Tab {
3949//                 line_start_offset: 0,
3950//             },
3951//             Invisible::Whitespace {
3952//                 line_offset: TAB_SIZE as usize,
3953//             },
3954//             Invisible::Tab {
3955//                 line_start_offset: TAB_SIZE as usize + 1,
3956//             },
3957//             Invisible::Tab {
3958//                 line_start_offset: TAB_SIZE as usize * 2 + 1,
3959//             },
3960//             Invisible::Whitespace {
3961//                 line_offset: TAB_SIZE as usize * 3 + 1,
3962//             },
3963//             Invisible::Whitespace {
3964//                 line_offset: TAB_SIZE as usize * 3 + 3,
3965//             },
3966//         ];
3967//         assert_eq!(
3968//             expected_invisibles.len(),
3969//             input_text
3970//                 .chars()
3971//                 .filter(|initial_char| initial_char.is_whitespace())
3972//                 .count(),
3973//             "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
3974//         );
3975
3976//         init_test(cx, |s| {
3977//             s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3978//             s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
3979//         });
3980
3981//         let actual_invisibles =
3982//             collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, 500.0);
3983
3984//         assert_eq!(expected_invisibles, actual_invisibles);
3985//     }
3986
3987//     #[gpui::test]
3988//     fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
3989//         init_test(cx, |s| {
3990//             s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3991//             s.defaults.tab_size = NonZeroU32::new(4);
3992//         });
3993
3994//         for editor_mode_without_invisibles in [
3995//             EditorMode::SingleLine,
3996//             EditorMode::AutoHeight { max_lines: 100 },
3997//         ] {
3998//             let invisibles = collect_invisibles_from_new_editor(
3999//                 cx,
4000//                 editor_mode_without_invisibles,
4001//                 "\t\t\t| | a b",
4002//                 500.0,
4003//             );
4004//             assert!(invisibles.is_empty,
4005//                 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
4006//         }
4007//     }
4008
4009//     #[gpui::test]
4010//     fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
4011//         let tab_size = 4;
4012//         let input_text = "a\tbcd   ".repeat(9);
4013//         let repeated_invisibles = [
4014//             Invisible::Tab {
4015//                 line_start_offset: 1,
4016//             },
4017//             Invisible::Whitespace {
4018//                 line_offset: tab_size as usize + 3,
4019//             },
4020//             Invisible::Whitespace {
4021//                 line_offset: tab_size as usize + 4,
4022//             },
4023//             Invisible::Whitespace {
4024//                 line_offset: tab_size as usize + 5,
4025//             },
4026//         ];
4027//         let expected_invisibles = std::iter::once(repeated_invisibles)
4028//             .cycle()
4029//             .take(9)
4030//             .flatten()
4031//             .collect::<Vec<_>>();
4032//         assert_eq!(
4033//             expected_invisibles.len(),
4034//             input_text
4035//                 .chars()
4036//                 .filter(|initial_char| initial_char.is_whitespace())
4037//                 .count(),
4038//             "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
4039//         );
4040//         info!("Expected invisibles: {expected_invisibles:?}");
4041
4042//         init_test(cx, |_| {});
4043
4044//         // Put the same string with repeating whitespace pattern into editors of various size,
4045//         // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
4046//         let resize_step = 10.0;
4047//         let mut editor_width = 200.0;
4048//         while editor_width <= 1000.0 {
4049//             update_test_language_settings(cx, |s| {
4050//                 s.defaults.tab_size = NonZeroU32::new(tab_size);
4051//                 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4052//                 s.defaults.preferred_line_length = Some(editor_width as u32);
4053//                 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
4054//             });
4055
4056//             let actual_invisibles =
4057//                 collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, editor_width);
4058
4059//             // Whatever the editor size is, ensure it has the same invisible kinds in the same order
4060//             // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
4061//             let mut i = 0;
4062//             for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
4063//                 i = actual_index;
4064//                 match expected_invisibles.get(i) {
4065//                     Some(expected_invisible) => match (expected_invisible, actual_invisible) {
4066//                         (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
4067//                         | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
4068//                         _ => {
4069//                             panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
4070//                         }
4071//                     },
4072//                     None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
4073//                 }
4074//             }
4075//             let missing_expected_invisibles = &expected_invisibles[i + 1..];
4076//             assert!(
4077//                 missing_expected_invisibles.is_empty,
4078//                 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
4079//             );
4080
4081//             editor_width += resize_step;
4082//         }
4083//     }
4084
4085//     fn collect_invisibles_from_new_editor(
4086//         cx: &mut TestAppContext,
4087//         editor_mode: EditorMode,
4088//         input_text: &str,
4089//         editor_width: f32,
4090//     ) -> Vec<Invisible> {
4091//         info!(
4092//             "Creating editor with mode {editor_mode:?}, width {editor_width} and text '{input_text}'"
4093//         );
4094//         let editor = cx
4095//             .add_window(|cx| {
4096//                 let buffer = MultiBuffer::build_simple(&input_text, cx);
4097//                 Editor::new(editor_mode, buffer, None, None, cx)
4098//             })
4099//             .root(cx);
4100
4101//         let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
4102//         let (_, layout_state) = editor.update(cx, |editor, cx| {
4103//             editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
4104//             editor.set_wrap_width(Some(editor_width), cx);
4105
4106//             element.layout(
4107//                 SizeConstraint::new(point(editor_width, 500.), point(editor_width, 500.)),
4108//                 editor,
4109//                 cx,
4110//             )
4111//         });
4112
4113//         layout_state
4114//             .position_map
4115//             .line_layouts
4116//             .iter()
4117//             .map(|line_with_invisibles| &line_with_invisibles.invisibles)
4118//             .flatten()
4119//             .cloned()
4120//             .collect()
4121//     }
4122// }
4123
4124pub fn register_action<T: Action>(
4125    view: &View<Editor>,
4126    cx: &mut WindowContext,
4127    listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
4128) {
4129    let view = view.clone();
4130    cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
4131        let action = action.downcast_ref().unwrap();
4132        if phase == DispatchPhase::Bubble {
4133            view.update(cx, |editor, cx| {
4134                listener(editor, action, cx);
4135            })
4136        }
4137    })
4138}
4139
4140fn compute_auto_height_layout(
4141    editor: &mut Editor,
4142    max_lines: usize,
4143    max_line_number_width: Pixels,
4144    known_dimensions: Size<Option<Pixels>>,
4145    cx: &mut ViewContext<Editor>,
4146) -> Option<Size<Pixels>> {
4147    let mut width = known_dimensions.width?;
4148    if let Some(height) = known_dimensions.height {
4149        return Some(size(width, height));
4150    }
4151
4152    let style = editor.style.as_ref().unwrap();
4153    let font_id = cx.text_system().font_id(&style.text.font()).unwrap();
4154    let font_size = style.text.font_size.to_pixels(cx.rem_size());
4155    let line_height = style.text.line_height_in_pixels(cx.rem_size());
4156    let em_width = cx
4157        .text_system()
4158        .typographic_bounds(font_id, font_size, 'm')
4159        .unwrap()
4160        .size
4161        .width;
4162
4163    let mut snapshot = editor.snapshot(cx);
4164    let gutter_padding;
4165    let gutter_width;
4166    let gutter_margin;
4167    if snapshot.show_gutter {
4168        let descent = cx.text_system().descent(font_id, font_size).unwrap();
4169        let gutter_padding_factor = 3.5;
4170        gutter_padding = (em_width * gutter_padding_factor).round();
4171        gutter_width = max_line_number_width + gutter_padding * 2.0;
4172        gutter_margin = -descent;
4173    } else {
4174        gutter_padding = Pixels::ZERO;
4175        gutter_width = Pixels::ZERO;
4176        gutter_margin = Pixels::ZERO;
4177    };
4178
4179    editor.gutter_width = gutter_width;
4180    let text_width = width - gutter_width;
4181    let overscroll = size(em_width, px(0.));
4182
4183    let editor_width = text_width - gutter_margin - overscroll.width - em_width;
4184    if editor.set_wrap_width(Some(editor_width), cx) {
4185        snapshot = editor.snapshot(cx);
4186    }
4187
4188    let scroll_height = Pixels::from(snapshot.max_point().row() + 1) * line_height;
4189    let height = scroll_height
4190        .max(line_height)
4191        .min(line_height * max_lines as f32);
4192
4193    Some(size(width, height))
4194}