element.rs

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