element.rs

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