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