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