element.rs

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