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    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, AnyElement, BorrowWindow, Bounds,
  12    ContentMask, Corners, DispatchPhase, Edges, Element, ElementId, Hsla, Line, Pixels,
  13    ScrollWheelEvent, ShapedGlyph, Size, StatefulInteraction, Style, TextRun, TextStyle,
  14    TextSystem, ViewContext, WindowContext,
  15};
  16use itertools::Itertools;
  17use language::language_settings::ShowWhitespaceSetting;
  18use multi_buffer::Anchor;
  19use project::project_settings::{GitGutterSetting, ProjectSettings};
  20use settings::Settings;
  21use smallvec::SmallVec;
  22use std::{
  23    borrow::Cow,
  24    cmp::{self, Ordering},
  25    fmt::Write,
  26    iter,
  27    ops::Range,
  28    sync::Arc,
  29};
  30use sum_tree::Bias;
  31use theme::{ActiveTheme, PlayerColor};
  32use workspace::item::Item;
  33
  34enum FoldMarkers {}
  35
  36struct SelectionLayout {
  37    head: DisplayPoint,
  38    cursor_shape: CursorShape,
  39    is_newest: bool,
  40    is_local: bool,
  41    range: Range<DisplayPoint>,
  42    active_rows: Range<u32>,
  43}
  44
  45impl SelectionLayout {
  46    fn new<T: ToPoint + ToDisplayPoint + Clone>(
  47        selection: Selection<T>,
  48        line_mode: bool,
  49        cursor_shape: CursorShape,
  50        map: &DisplaySnapshot,
  51        is_newest: bool,
  52        is_local: bool,
  53    ) -> Self {
  54        let point_selection = selection.map(|p| p.to_point(&map.buffer_snapshot));
  55        let display_selection = point_selection.map(|p| p.to_display_point(map));
  56        let mut range = display_selection.range();
  57        let mut head = display_selection.head();
  58        let mut active_rows = map.prev_line_boundary(point_selection.start).1.row()
  59            ..map.next_line_boundary(point_selection.end).1.row();
  60
  61        // vim visual line mode
  62        if line_mode {
  63            let point_range = map.expand_to_line(point_selection.range());
  64            range = point_range.start.to_display_point(map)..point_range.end.to_display_point(map);
  65        }
  66
  67        // any vim visual mode (including line mode)
  68        if cursor_shape == CursorShape::Block && !range.is_empty() && !selection.reversed {
  69            if head.column() > 0 {
  70                head = map.clip_point(DisplayPoint::new(head.row(), head.column() - 1), Bias::Left)
  71            } else if head.row() > 0 && head != map.max_point() {
  72                head = map.clip_point(
  73                    DisplayPoint::new(head.row() - 1, map.line_len(head.row() - 1)),
  74                    Bias::Left,
  75                );
  76                // updating range.end is a no-op unless you're cursor is
  77                // on the newline containing a multi-buffer divider
  78                // in which case the clip_point may have moved the head up
  79                // an additional row.
  80                range.end = DisplayPoint::new(head.row() + 1, 0);
  81                active_rows.end = head.row();
  82            }
  83        }
  84
  85        Self {
  86            head,
  87            cursor_shape,
  88            is_newest,
  89            is_local,
  90            range,
  91            active_rows,
  92        }
  93    }
  94}
  95
  96pub struct EditorElement {
  97    style: Arc<EditorStyle>,
  98}
  99
 100impl EditorElement {
 101    pub fn new(style: EditorStyle) -> Self {
 102        Self {
 103            style: Arc::new(style),
 104        }
 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 style = &self.style;
1582            let chunks = snapshot.highlighted_chunks(rows.clone(), true, cx.theme());
1583
1584            LineWithInvisibles::from_chunks(
1585                chunks,
1586                &style.text,
1587                MAX_LINE_LEN,
1588                rows.len() as usize,
1589                line_number_layouts,
1590                snapshot.mode,
1591                cx,
1592            )
1593        }
1594    }
1595
1596    fn compute_layout(
1597        &mut self,
1598        editor: &mut Editor,
1599        cx: &mut ViewContext<'_, Editor>,
1600        bounds: Bounds<Pixels>,
1601    ) -> LayoutState {
1602        // let mut size = constraint.max;
1603        // if size.x.is_infinite() {
1604        //     unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
1605        // }
1606
1607        let snapshot = editor.snapshot(cx);
1608        let style = self.style.clone();
1609        let font_id = cx.text_system().font_id(&style.text.font()).unwrap();
1610        let font_size = style.text.font_size.to_pixels(cx.rem_size());
1611        let line_height = (font_size * style.line_height_scalar).round();
1612        let em_width = cx
1613            .text_system()
1614            .typographic_bounds(font_id, font_size, 'm')
1615            .unwrap()
1616            .size
1617            .width;
1618        let em_advance = cx
1619            .text_system()
1620            .advance(font_id, font_size, 'm')
1621            .unwrap()
1622            .width;
1623
1624        let gutter_padding;
1625        let gutter_width;
1626        let gutter_margin;
1627        if snapshot.show_gutter {
1628            let descent = cx.text_system().descent(font_id, font_size).unwrap();
1629
1630            let gutter_padding_factor = 3.5;
1631            gutter_padding = (em_width * gutter_padding_factor).round();
1632            gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
1633            gutter_margin = -descent;
1634        } else {
1635            gutter_padding = Pixels::ZERO;
1636            gutter_width = Pixels::ZERO;
1637            gutter_margin = Pixels::ZERO;
1638        };
1639
1640        let text_width = bounds.size.width - gutter_width;
1641        let overscroll = size(em_width, px(0.));
1642        let snapshot = {
1643            editor.set_visible_line_count((bounds.size.height / line_height).into(), cx);
1644
1645            let editor_width = text_width - gutter_margin - overscroll.width - em_width;
1646            let wrap_width = match editor.soft_wrap_mode(cx) {
1647                SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
1648                SoftWrap::EditorWidth => editor_width,
1649                SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
1650            };
1651
1652            if editor.set_wrap_width(Some(wrap_width), cx) {
1653                editor.snapshot(cx)
1654            } else {
1655                snapshot
1656            }
1657        };
1658
1659        let wrap_guides = editor
1660            .wrap_guides(cx)
1661            .iter()
1662            .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
1663            .collect::<SmallVec<[_; 2]>>();
1664
1665        let scroll_height = Pixels::from(snapshot.max_point().row() + 1) * line_height;
1666        // todo!("this should happen during layout")
1667        let editor_mode = snapshot.mode;
1668        if let EditorMode::AutoHeight { max_lines } = editor_mode {
1669            todo!()
1670            //     size.set_y(
1671            //         scroll_height
1672            //             .min(constraint.max_along(Axis::Vertical))
1673            //             .max(constraint.min_along(Axis::Vertical))
1674            //             .max(line_height)
1675            //             .min(line_height * max_lines as f32),
1676            //     )
1677        } else if let EditorMode::SingleLine = editor_mode {
1678            todo!()
1679            //     size.set_y(line_height.max(constraint.min_along(Axis::Vertical)))
1680        }
1681        // todo!()
1682        // else if size.y.is_infinite() {
1683        //     //     size.set_y(scroll_height);
1684        // }
1685        //
1686        let gutter_size = size(gutter_width, bounds.size.height);
1687        let text_size = size(text_width, bounds.size.height);
1688
1689        let autoscroll_horizontally =
1690            editor.autoscroll_vertically(bounds.size.height, line_height, cx);
1691        let mut snapshot = editor.snapshot(cx);
1692
1693        let scroll_position = snapshot.scroll_position();
1694        // The scroll position is a fractional point, the whole number of which represents
1695        // the top of the window in terms of display rows.
1696        let start_row = scroll_position.y as u32;
1697        let height_in_lines = f32::from(bounds.size.height / line_height);
1698        let max_row = snapshot.max_point().row();
1699
1700        // Add 1 to ensure selections bleed off screen
1701        let end_row = 1 + cmp::min((scroll_position.y + height_in_lines).ceil() as u32, max_row);
1702
1703        let start_anchor = if start_row == 0 {
1704            Anchor::min()
1705        } else {
1706            snapshot
1707                .buffer_snapshot
1708                .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
1709        };
1710        let end_anchor = if end_row > max_row {
1711            Anchor::max()
1712        } else {
1713            snapshot
1714                .buffer_snapshot
1715                .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
1716        };
1717
1718        let mut selections: Vec<(PlayerColor, Vec<SelectionLayout>)> = Vec::new();
1719        let mut active_rows = BTreeMap::new();
1720        let mut fold_ranges = Vec::new();
1721        let is_singleton = editor.is_singleton(cx);
1722
1723        let highlighted_rows = editor.highlighted_rows();
1724        let highlighted_ranges = editor.background_highlights_in_range(
1725            start_anchor..end_anchor,
1726            &snapshot.display_snapshot,
1727            cx.theme().colors(),
1728        );
1729
1730        fold_ranges.extend(
1731            snapshot
1732                .folds_in_range(start_anchor..end_anchor)
1733                .map(|anchor| {
1734                    let start = anchor.start.to_point(&snapshot.buffer_snapshot);
1735                    (
1736                        start.row,
1737                        start.to_display_point(&snapshot.display_snapshot)
1738                            ..anchor.end.to_display_point(&snapshot),
1739                    )
1740                }),
1741        );
1742
1743        let mut newest_selection_head = None;
1744
1745        if editor.show_local_selections {
1746            let mut local_selections: Vec<Selection<Point>> = editor
1747                .selections
1748                .disjoint_in_range(start_anchor..end_anchor, cx);
1749            local_selections.extend(editor.selections.pending(cx));
1750            let mut layouts = Vec::new();
1751            let newest = editor.selections.newest(cx);
1752            for selection in local_selections.drain(..) {
1753                let is_empty = selection.start == selection.end;
1754                let is_newest = selection == newest;
1755
1756                let layout = SelectionLayout::new(
1757                    selection,
1758                    editor.selections.line_mode,
1759                    editor.cursor_shape,
1760                    &snapshot.display_snapshot,
1761                    is_newest,
1762                    true,
1763                );
1764                if is_newest {
1765                    newest_selection_head = Some(layout.head);
1766                }
1767
1768                for row in cmp::max(layout.active_rows.start, start_row)
1769                    ..=cmp::min(layout.active_rows.end, end_row)
1770                {
1771                    let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
1772                    *contains_non_empty_selection |= !is_empty;
1773                }
1774                layouts.push(layout);
1775            }
1776
1777            selections.push((style.local_player, layouts));
1778        }
1779
1780        if let Some(collaboration_hub) = &editor.collaboration_hub {
1781            // When following someone, render the local selections in their color.
1782            if let Some(leader_id) = editor.leader_peer_id {
1783                if let Some(collaborator) = collaboration_hub.collaborators(cx).get(&leader_id) {
1784                    if let Some(participant_index) = collaboration_hub
1785                        .user_participant_indices(cx)
1786                        .get(&collaborator.user_id)
1787                    {
1788                        if let Some((local_selection_style, _)) = selections.first_mut() {
1789                            *local_selection_style = cx
1790                                .theme()
1791                                .players()
1792                                .color_for_participant(participant_index.0);
1793                        }
1794                    }
1795                }
1796            }
1797
1798            let mut remote_selections = HashMap::default();
1799            for selection in snapshot.remote_selections_in_range(
1800                &(start_anchor..end_anchor),
1801                collaboration_hub.as_ref(),
1802                cx,
1803            ) {
1804                let selection_style = if let Some(participant_index) = selection.participant_index {
1805                    cx.theme()
1806                        .players()
1807                        .color_for_participant(participant_index.0)
1808                } else {
1809                    cx.theme().players().absent()
1810                };
1811
1812                // Don't re-render the leader's selections, since the local selections
1813                // match theirs.
1814                if Some(selection.peer_id) == editor.leader_peer_id {
1815                    continue;
1816                }
1817
1818                remote_selections
1819                    .entry(selection.replica_id)
1820                    .or_insert((selection_style, Vec::new()))
1821                    .1
1822                    .push(SelectionLayout::new(
1823                        selection.selection,
1824                        selection.line_mode,
1825                        selection.cursor_shape,
1826                        &snapshot.display_snapshot,
1827                        false,
1828                        false,
1829                    ));
1830            }
1831
1832            selections.extend(remote_selections.into_values());
1833        }
1834
1835        let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
1836        let show_scrollbars = match scrollbar_settings.show {
1837            ShowScrollbar::Auto => {
1838                // Git
1839                (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_git_diffs())
1840                        ||
1841                        // Selections
1842                        (is_singleton && scrollbar_settings.selections && !highlighted_ranges.is_empty())
1843                        // Scrollmanager
1844                        || editor.scroll_manager.scrollbars_visible()
1845            }
1846            ShowScrollbar::System => editor.scroll_manager.scrollbars_visible(),
1847            ShowScrollbar::Always => true,
1848            ShowScrollbar::Never => false,
1849        };
1850
1851        let fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Hsla)> = fold_ranges
1852            .into_iter()
1853            .map(|(id, fold)| {
1854                todo!("folds!")
1855                // let color = self
1856                //     .style
1857                //     .folds
1858                //     .ellipses
1859                //     .background
1860                //     .style_for(&mut cx.mouse_state::<FoldMarkers>(id as usize))
1861                //     .color;
1862
1863                // (id, fold, color)
1864            })
1865            .collect();
1866
1867        let head_for_relative = newest_selection_head.unwrap_or_else(|| {
1868            let newest = editor.selections.newest::<Point>(cx);
1869            SelectionLayout::new(
1870                newest,
1871                editor.selections.line_mode,
1872                editor.cursor_shape,
1873                &snapshot.display_snapshot,
1874                true,
1875                true,
1876            )
1877            .head
1878        });
1879
1880        let (line_number_layouts, fold_statuses) = self.layout_line_numbers(
1881            start_row..end_row,
1882            &active_rows,
1883            head_for_relative,
1884            is_singleton,
1885            &snapshot,
1886            cx,
1887        );
1888
1889        let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
1890
1891        let scrollbar_row_range = scroll_position.y..(scroll_position.y + height_in_lines);
1892
1893        let mut max_visible_line_width = Pixels::ZERO;
1894        let line_layouts =
1895            self.layout_lines(start_row..end_row, &line_number_layouts, &snapshot, cx);
1896        for line_with_invisibles in &line_layouts {
1897            if line_with_invisibles.line.width > max_visible_line_width {
1898                max_visible_line_width = line_with_invisibles.line.width;
1899            }
1900        }
1901
1902        let longest_line_width = layout_line(snapshot.longest_row(), &snapshot, &style, cx)
1903            .unwrap()
1904            .width;
1905        let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.width;
1906        // todo!("blocks")
1907        // let (scroll_width, blocks) = self.layout_blocks(
1908        //     start_row..end_row,
1909        //     &snapshot,
1910        //     size.x,
1911        //     scroll_width,
1912        //     gutter_padding,
1913        //     gutter_width,
1914        //     em_width,
1915        //     gutter_width + gutter_margin,
1916        //     line_height,
1917        //     &style,
1918        //     &line_layouts,
1919        //     editor,
1920        //     cx,
1921        // );
1922
1923        let scroll_max = point(
1924            f32::from((scroll_width - text_size.width) / em_width).max(0.0),
1925            max_row as f32,
1926        );
1927
1928        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
1929
1930        let autoscrolled = if autoscroll_horizontally {
1931            editor.autoscroll_horizontally(
1932                start_row,
1933                text_size.width,
1934                scroll_width,
1935                em_width,
1936                &line_layouts,
1937                cx,
1938            )
1939        } else {
1940            false
1941        };
1942
1943        if clamped || autoscrolled {
1944            snapshot = editor.snapshot(cx);
1945        }
1946
1947        // todo!("context menu")
1948        // let mut context_menu = None;
1949        // let mut code_actions_indicator = None;
1950        // if let Some(newest_selection_head) = newest_selection_head {
1951        //     if (start_row..end_row).contains(&newest_selection_head.row()) {
1952        //         if editor.context_menu_visible() {
1953        //             context_menu =
1954        //                 editor.render_context_menu(newest_selection_head, style.clone(), cx);
1955        //         }
1956
1957        //         let active = matches!(
1958        //             editor.context_menu.read().as_ref(),
1959        //             Some(crate::ContextMenu::CodeActions(_))
1960        //         );
1961
1962        //         code_actions_indicator = editor
1963        //             .render_code_actions_indicator(&style, active, cx)
1964        //             .map(|indicator| (newest_selection_head.row(), indicator));
1965        //     }
1966        // }
1967
1968        let visible_rows = start_row..start_row + line_layouts.len() as u32;
1969        // todo!("hover")
1970        // let mut hover = editor.hover_state.render(
1971        //     &snapshot,
1972        //     &style,
1973        //     visible_rows,
1974        //     editor.workspace.as_ref().map(|(w, _)| w.clone()),
1975        //     cx,
1976        // );
1977        // let mode = editor.mode;
1978
1979        // todo!("fold_indicators")
1980        // let mut fold_indicators = editor.render_fold_indicators(
1981        //     fold_statuses,
1982        //     &style,
1983        //     editor.gutter_hovered,
1984        //     line_height,
1985        //     gutter_margin,
1986        //     cx,
1987        // );
1988
1989        // todo!("context_menu")
1990        // if let Some((_, context_menu)) = context_menu.as_mut() {
1991        //     context_menu.layout(
1992        //         SizeConstraint {
1993        //             min: gpui::Point::<Pixels>::zero(),
1994        //             max: point(
1995        //                 cx.window_size().x * 0.7,
1996        //                 (12. * line_height).min((size.y - line_height) / 2.),
1997        //             ),
1998        //         },
1999        //         editor,
2000        //         cx,
2001        //     );
2002        // }
2003
2004        // todo!("code actions")
2005        // if let Some((_, indicator)) = code_actions_indicator.as_mut() {
2006        //     indicator.layout(
2007        //         SizeConstraint::strict_along(
2008        //             Axis::Vertical,
2009        //             line_height * style.code_actions.vertical_scale,
2010        //         ),
2011        //         editor,
2012        //         cx,
2013        //     );
2014        // }
2015
2016        // todo!("fold indicators")
2017        // for fold_indicator in fold_indicators.iter_mut() {
2018        //     if let Some(indicator) = fold_indicator.as_mut() {
2019        //         indicator.layout(
2020        //             SizeConstraint::strict_along(
2021        //                 Axis::Vertical,
2022        //                 line_height * style.code_actions.vertical_scale,
2023        //             ),
2024        //             editor,
2025        //             cx,
2026        //         );
2027        //     }
2028        // }
2029
2030        // todo!("hover popovers")
2031        // if let Some((_, hover_popovers)) = hover.as_mut() {
2032        //     for hover_popover in hover_popovers.iter_mut() {
2033        //         hover_popover.layout(
2034        //             SizeConstraint {
2035        //                 min: gpui::Point::<Pixels>::zero(),
2036        //                 max: point(
2037        //                     (120. * em_width) // Default size
2038        //                         .min(size.x / 2.) // Shrink to half of the editor width
2039        //                         .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2040        //                     (16. * line_height) // Default size
2041        //                         .min(size.y / 2.) // Shrink to half of the editor height
2042        //                         .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2043        //                 ),
2044        //             },
2045        //             editor,
2046        //             cx,
2047        //         );
2048        //     }
2049        // }
2050
2051        let invisible_symbol_font_size = font_size / 2.;
2052        let tab_invisible = cx
2053            .text_system()
2054            .layout_text(
2055                "",
2056                invisible_symbol_font_size,
2057                &[TextRun {
2058                    len: "".len(),
2059                    font: self.style.text.font(),
2060                    color: cx.theme().colors().editor_invisible,
2061                    underline: None,
2062                }],
2063                None,
2064            )
2065            .unwrap()
2066            .pop()
2067            .unwrap();
2068        let space_invisible = cx
2069            .text_system()
2070            .layout_text(
2071                "",
2072                invisible_symbol_font_size,
2073                &[TextRun {
2074                    len: "".len(),
2075                    font: self.style.text.font(),
2076                    color: cx.theme().colors().editor_invisible,
2077                    underline: None,
2078                }],
2079                None,
2080            )
2081            .unwrap()
2082            .pop()
2083            .unwrap();
2084
2085        LayoutState {
2086            mode: editor_mode,
2087            position_map: Arc::new(PositionMap {
2088                size: bounds.size,
2089                scroll_max,
2090                line_layouts,
2091                line_height,
2092                em_width,
2093                em_advance,
2094                snapshot,
2095            }),
2096            visible_display_row_range: start_row..end_row,
2097            wrap_guides,
2098            gutter_size,
2099            gutter_padding,
2100            text_size,
2101            scrollbar_row_range,
2102            show_scrollbars,
2103            is_singleton,
2104            max_row,
2105            gutter_margin,
2106            active_rows,
2107            highlighted_rows,
2108            highlighted_ranges,
2109            fold_ranges,
2110            line_number_layouts,
2111            display_hunks,
2112            // blocks,
2113            selections,
2114            // context_menu,
2115            // code_actions_indicator,
2116            // fold_indicators,
2117            tab_invisible,
2118            space_invisible,
2119            // hover_popovers: hover,
2120        }
2121    }
2122
2123    // #[allow(clippy::too_many_arguments)]
2124    // fn layout_blocks(
2125    //     &mut self,
2126    //     rows: Range<u32>,
2127    //     snapshot: &EditorSnapshot,
2128    //     editor_width: f32,
2129    //     scroll_width: f32,
2130    //     gutter_padding: f32,
2131    //     gutter_width: f32,
2132    //     em_width: f32,
2133    //     text_x: f32,
2134    //     line_height: f32,
2135    //     style: &EditorStyle,
2136    //     line_layouts: &[LineWithInvisibles],
2137    //     editor: &mut Editor,
2138    //     cx: &mut ViewContext<Editor>,
2139    // ) -> (f32, Vec<BlockLayout>) {
2140    //     let mut block_id = 0;
2141    //     let scroll_x = snapshot.scroll_anchor.offset.x;
2142    //     let (fixed_blocks, non_fixed_blocks) = snapshot
2143    //         .blocks_in_range(rows.clone())
2144    //         .partition::<Vec<_>, _>(|(_, block)| match block {
2145    //             TransformBlock::ExcerptHeader { .. } => false,
2146    //             TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
2147    //         });
2148    //     let mut render_block = |block: &TransformBlock, width: f32, block_id: usize| {
2149    //         let mut element = match block {
2150    //             TransformBlock::Custom(block) => {
2151    //                 let align_to = block
2152    //                     .position()
2153    //                     .to_point(&snapshot.buffer_snapshot)
2154    //                     .to_display_point(snapshot);
2155    //                 let anchor_x = text_x
2156    //                     + if rows.contains(&align_to.row()) {
2157    //                         line_layouts[(align_to.row() - rows.start) as usize]
2158    //                             .line
2159    //                             .x_for_index(align_to.column() as usize)
2160    //                     } else {
2161    //                         layout_line(align_to.row(), snapshot, style, cx.text_layout_cache())
2162    //                             .x_for_index(align_to.column() as usize)
2163    //                     };
2164
2165    //                 block.render(&mut BlockContext {
2166    //                     view_context: cx,
2167    //                     anchor_x,
2168    //                     gutter_padding,
2169    //                     line_height,
2170    //                     scroll_x,
2171    //                     gutter_width,
2172    //                     em_width,
2173    //                     block_id,
2174    //                 })
2175    //             }
2176    //             TransformBlock::ExcerptHeader {
2177    //                 id,
2178    //                 buffer,
2179    //                 range,
2180    //                 starts_new_buffer,
2181    //                 ..
2182    //             } => {
2183    //                 let tooltip_style = theme::current(cx).tooltip.clone();
2184    //                 let include_root = editor
2185    //                     .project
2186    //                     .as_ref()
2187    //                     .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
2188    //                     .unwrap_or_default();
2189    //                 let jump_icon = project::File::from_dyn(buffer.file()).map(|file| {
2190    //                     let jump_path = ProjectPath {
2191    //                         worktree_id: file.worktree_id(cx),
2192    //                         path: file.path.clone(),
2193    //                     };
2194    //                     let jump_anchor = range
2195    //                         .primary
2196    //                         .as_ref()
2197    //                         .map_or(range.context.start, |primary| primary.start);
2198    //                     let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
2199
2200    //                     enum JumpIcon {}
2201    //                     MouseEventHandler::new::<JumpIcon, _>((*id).into(), cx, |state, _| {
2202    //                         let style = style.jump_icon.style_for(state);
2203    //                         Svg::new("icons/arrow_up_right.svg")
2204    //                             .with_color(style.color)
2205    //                             .constrained()
2206    //                             .with_width(style.icon_width)
2207    //                             .aligned()
2208    //                             .contained()
2209    //                             .with_style(style.container)
2210    //                             .constrained()
2211    //                             .with_width(style.button_width)
2212    //                             .with_height(style.button_width)
2213    //                     })
2214    //                     .with_cursor_style(CursorStyle::PointingHand)
2215    //                     .on_click(MouseButton::Left, move |_, editor, cx| {
2216    //                         if let Some(workspace) = editor
2217    //                             .workspace
2218    //                             .as_ref()
2219    //                             .and_then(|(workspace, _)| workspace.upgrade(cx))
2220    //                         {
2221    //                             workspace.update(cx, |workspace, cx| {
2222    //                                 Editor::jump(
2223    //                                     workspace,
2224    //                                     jump_path.clone(),
2225    //                                     jump_position,
2226    //                                     jump_anchor,
2227    //                                     cx,
2228    //                                 );
2229    //                             });
2230    //                         }
2231    //                     })
2232    //                     .with_tooltip::<JumpIcon>(
2233    //                         (*id).into(),
2234    //                         "Jump to Buffer".to_string(),
2235    //                         Some(Box::new(crate::OpenExcerpts)),
2236    //                         tooltip_style.clone(),
2237    //                         cx,
2238    //                     )
2239    //                     .aligned()
2240    //                     .flex_float()
2241    //                 });
2242
2243    //                 if *starts_new_buffer {
2244    //                     let editor_font_size = style.text.font_size;
2245    //                     let style = &style.diagnostic_path_header;
2246    //                     let font_size = (style.text_scale_factor * editor_font_size).round();
2247
2248    //                     let path = buffer.resolve_file_path(cx, include_root);
2249    //                     let mut filename = None;
2250    //                     let mut parent_path = None;
2251    //                     // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
2252    //                     if let Some(path) = path {
2253    //                         filename = path.file_name().map(|f| f.to_string_lossy.to_string());
2254    //                         parent_path =
2255    //                             path.parent().map(|p| p.to_string_lossy.to_string() + "/");
2256    //                     }
2257
2258    //                     Flex::row()
2259    //                         .with_child(
2260    //                             Label::new(
2261    //                                 filename.unwrap_or_else(|| "untitled".to_string()),
2262    //                                 style.filename.text.clone().with_font_size(font_size),
2263    //                             )
2264    //                             .contained()
2265    //                             .with_style(style.filename.container)
2266    //                             .aligned(),
2267    //                         )
2268    //                         .with_children(parent_path.map(|path| {
2269    //                             Label::new(path, style.path.text.clone().with_font_size(font_size))
2270    //                                 .contained()
2271    //                                 .with_style(style.path.container)
2272    //                                 .aligned()
2273    //                         }))
2274    //                         .with_children(jump_icon)
2275    //                         .contained()
2276    //                         .with_style(style.container)
2277    //                         .with_padding_left(gutter_padding)
2278    //                         .with_padding_right(gutter_padding)
2279    //                         .expanded()
2280    //                         .into_any_named("path header block")
2281    //                 } else {
2282    //                     let text_style = style.text.clone();
2283    //                     Flex::row()
2284    //                         .with_child(Label::new("⋯", text_style))
2285    //                         .with_children(jump_icon)
2286    //                         .contained()
2287    //                         .with_padding_left(gutter_padding)
2288    //                         .with_padding_right(gutter_padding)
2289    //                         .expanded()
2290    //                         .into_any_named("collapsed context")
2291    //                 }
2292    //             }
2293    //         };
2294
2295    //         element.layout(
2296    //             SizeConstraint {
2297    //                 min: gpui::Point::<Pixels>::zero(),
2298    //                 max: point(width, block.height() as f32 * line_height),
2299    //             },
2300    //             editor,
2301    //             cx,
2302    //         );
2303    //         element
2304    //     };
2305
2306    //     let mut fixed_block_max_width = 0f32;
2307    //     let mut blocks = Vec::new();
2308    //     for (row, block) in fixed_blocks {
2309    //         let element = render_block(block, f32::INFINITY, block_id);
2310    //         block_id += 1;
2311    //         fixed_block_max_width = fixed_block_max_width.max(element.size().x + em_width);
2312    //         blocks.push(BlockLayout {
2313    //             row,
2314    //             element,
2315    //             style: BlockStyle::Fixed,
2316    //         });
2317    //     }
2318    //     for (row, block) in non_fixed_blocks {
2319    //         let style = match block {
2320    //             TransformBlock::Custom(block) => block.style(),
2321    //             TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
2322    //         };
2323    //         let width = match style {
2324    //             BlockStyle::Sticky => editor_width,
2325    //             BlockStyle::Flex => editor_width
2326    //                 .max(fixed_block_max_width)
2327    //                 .max(gutter_width + scroll_width),
2328    //             BlockStyle::Fixed => unreachable!(),
2329    //         };
2330    //         let element = render_block(block, width, block_id);
2331    //         block_id += 1;
2332    //         blocks.push(BlockLayout {
2333    //             row,
2334    //             element,
2335    //             style,
2336    //         });
2337    //     }
2338    //     (
2339    //         scroll_width.max(fixed_block_max_width - gutter_width),
2340    //         blocks,
2341    //     )
2342    // }
2343}
2344
2345#[derive(Debug)]
2346pub struct LineWithInvisibles {
2347    pub line: Line,
2348    invisibles: Vec<Invisible>,
2349}
2350
2351impl LineWithInvisibles {
2352    fn from_chunks<'a>(
2353        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
2354        text_style: &TextStyle,
2355        max_line_len: usize,
2356        max_line_count: usize,
2357        line_number_layouts: &[Option<Line>],
2358        editor_mode: EditorMode,
2359        cx: &WindowContext,
2360    ) -> Vec<Self> {
2361        let mut layouts = Vec::with_capacity(max_line_count);
2362        let mut line = String::new();
2363        let mut invisibles = Vec::new();
2364        let mut styles = Vec::new();
2365        let mut non_whitespace_added = false;
2366        let mut row = 0;
2367        let mut line_exceeded_max_len = false;
2368        let font_size = text_style.font_size.to_pixels(cx.rem_size());
2369
2370        for highlighted_chunk in chunks.chain([HighlightedChunk {
2371            chunk: "\n",
2372            style: None,
2373            is_tab: false,
2374        }]) {
2375            for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
2376                if ix > 0 {
2377                    let layout = cx
2378                        .text_system()
2379                        .layout_text(&line, font_size, &styles, None);
2380                    layouts.push(Self {
2381                        line: layout.unwrap().pop().unwrap(),
2382                        invisibles: invisibles.drain(..).collect(),
2383                    });
2384
2385                    line.clear();
2386                    styles.clear();
2387                    row += 1;
2388                    line_exceeded_max_len = false;
2389                    non_whitespace_added = false;
2390                    if row == max_line_count {
2391                        return layouts;
2392                    }
2393                }
2394
2395                if !line_chunk.is_empty() && !line_exceeded_max_len {
2396                    let text_style = if let Some(style) = highlighted_chunk.style {
2397                        text_style
2398                            .clone()
2399                            .highlight(style)
2400                            .map(Cow::Owned)
2401                            .unwrap_or_else(|_| Cow::Borrowed(text_style))
2402                    } else {
2403                        Cow::Borrowed(text_style)
2404                    };
2405
2406                    if line.len() + line_chunk.len() > max_line_len {
2407                        let mut chunk_len = max_line_len - line.len();
2408                        while !line_chunk.is_char_boundary(chunk_len) {
2409                            chunk_len -= 1;
2410                        }
2411                        line_chunk = &line_chunk[..chunk_len];
2412                        line_exceeded_max_len = true;
2413                    }
2414
2415                    styles.push(TextRun {
2416                        len: line_chunk.len(),
2417                        font: text_style.font(),
2418                        color: text_style.color,
2419                        underline: text_style.underline,
2420                    });
2421
2422                    if editor_mode == EditorMode::Full {
2423                        // Line wrap pads its contents with fake whitespaces,
2424                        // avoid printing them
2425                        let inside_wrapped_string = line_number_layouts
2426                            .get(row)
2427                            .and_then(|layout| layout.as_ref())
2428                            .is_none();
2429                        if highlighted_chunk.is_tab {
2430                            if non_whitespace_added || !inside_wrapped_string {
2431                                invisibles.push(Invisible::Tab {
2432                                    line_start_offset: line.len(),
2433                                });
2434                            }
2435                        } else {
2436                            invisibles.extend(
2437                                line_chunk
2438                                    .chars()
2439                                    .enumerate()
2440                                    .filter(|(_, line_char)| {
2441                                        let is_whitespace = line_char.is_whitespace();
2442                                        non_whitespace_added |= !is_whitespace;
2443                                        is_whitespace
2444                                            && (non_whitespace_added || !inside_wrapped_string)
2445                                    })
2446                                    .map(|(whitespace_index, _)| Invisible::Whitespace {
2447                                        line_offset: line.len() + whitespace_index,
2448                                    }),
2449                            )
2450                        }
2451                    }
2452
2453                    line.push_str(line_chunk);
2454                }
2455            }
2456        }
2457
2458        layouts
2459    }
2460
2461    fn draw(
2462        &self,
2463        layout: &LayoutState,
2464        row: u32,
2465        scroll_top: Pixels,
2466        content_origin: gpui::Point<Pixels>,
2467        scroll_left: Pixels,
2468        whitespace_setting: ShowWhitespaceSetting,
2469        selection_ranges: &[Range<DisplayPoint>],
2470        cx: &mut ViewContext<Editor>,
2471    ) {
2472        let line_height = layout.position_map.line_height;
2473        let line_y = line_height * row as f32 - scroll_top;
2474
2475        self.line.paint(
2476            content_origin + gpui::point(-scroll_left, line_y),
2477            line_height,
2478            cx,
2479        );
2480
2481        self.draw_invisibles(
2482            &selection_ranges,
2483            layout,
2484            content_origin,
2485            scroll_left,
2486            line_y,
2487            row,
2488            line_height,
2489            whitespace_setting,
2490            cx,
2491        );
2492    }
2493
2494    fn draw_invisibles(
2495        &self,
2496        selection_ranges: &[Range<DisplayPoint>],
2497        layout: &LayoutState,
2498        content_origin: gpui::Point<Pixels>,
2499        scroll_left: Pixels,
2500        line_y: Pixels,
2501        row: u32,
2502        line_height: Pixels,
2503        whitespace_setting: ShowWhitespaceSetting,
2504        cx: &mut ViewContext<Editor>,
2505    ) {
2506        let allowed_invisibles_regions = match whitespace_setting {
2507            ShowWhitespaceSetting::None => return,
2508            ShowWhitespaceSetting::Selection => Some(selection_ranges),
2509            ShowWhitespaceSetting::All => None,
2510        };
2511
2512        for invisible in &self.invisibles {
2513            let (&token_offset, invisible_symbol) = match invisible {
2514                Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
2515                Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
2516            };
2517
2518            let x_offset = self.line.x_for_index(token_offset);
2519            let invisible_offset =
2520                (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
2521            let origin =
2522                content_origin + gpui::point(-scroll_left + x_offset + invisible_offset, line_y);
2523
2524            if let Some(allowed_regions) = allowed_invisibles_regions {
2525                let invisible_point = DisplayPoint::new(row, token_offset as u32);
2526                if !allowed_regions
2527                    .iter()
2528                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
2529                {
2530                    continue;
2531                }
2532            }
2533            invisible_symbol.paint(origin, line_height, cx);
2534        }
2535    }
2536}
2537
2538#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2539enum Invisible {
2540    Tab { line_start_offset: usize },
2541    Whitespace { line_offset: usize },
2542}
2543
2544impl Element<Editor> for EditorElement {
2545    type ElementState = ();
2546
2547    fn id(&self) -> Option<gpui::ElementId> {
2548        None
2549    }
2550
2551    fn initialize(
2552        &mut self,
2553        editor: &mut Editor,
2554        element_state: Option<Self::ElementState>,
2555        cx: &mut gpui::ViewContext<Editor>,
2556    ) -> Self::ElementState {
2557        ()
2558    }
2559
2560    fn layout(
2561        &mut self,
2562        editor: &mut Editor,
2563        element_state: &mut Self::ElementState,
2564        cx: &mut gpui::ViewContext<Editor>,
2565    ) -> gpui::LayoutId {
2566        let rem_size = cx.rem_size();
2567        let mut style = Style::default();
2568        style.size.width = relative(1.).into();
2569        style.size.height = relative(1.).into();
2570        cx.request_layout(&style, None)
2571    }
2572
2573    fn paint(
2574        &mut self,
2575        bounds: Bounds<gpui::Pixels>,
2576        editor: &mut Editor,
2577        element_state: &mut Self::ElementState,
2578        cx: &mut gpui::ViewContext<Editor>,
2579    ) {
2580        let layout = self.compute_layout(editor, cx, bounds);
2581
2582        cx.on_mouse_event({
2583            let position_map = layout.position_map.clone();
2584            move |editor, event: &ScrollWheelEvent, phase, cx| {
2585                if phase != DispatchPhase::Bubble {
2586                    return;
2587                }
2588
2589                if Self::scroll(editor, event, &position_map, bounds, cx) {
2590                    cx.stop_propagation();
2591                }
2592            }
2593        });
2594
2595        cx.with_content_mask(ContentMask { bounds }, |cx| {
2596            let gutter_bounds = Bounds {
2597                origin: bounds.origin,
2598                size: layout.gutter_size,
2599            };
2600            let text_bounds = Bounds {
2601                origin: gutter_bounds.upper_right(),
2602                size: layout.text_size,
2603            };
2604
2605            self.paint_background(gutter_bounds, text_bounds, &layout, cx);
2606            if layout.gutter_size.width > Pixels::ZERO {
2607                self.paint_gutter(gutter_bounds, &layout, editor, cx);
2608            }
2609            self.paint_text(text_bounds, &layout, editor, cx);
2610        });
2611    }
2612}
2613
2614// impl EditorElement {
2615//     type LayoutState = LayoutState;
2616//     type PaintState = ();
2617
2618//     fn layout(
2619//         &mut self,
2620//         constraint: SizeConstraint,
2621//         editor: &mut Editor,
2622//         cx: &mut ViewContext<Editor>,
2623//     ) -> (gpui::Point<Pixels>, Self::LayoutState) {
2624//         let mut size = constraint.max;
2625//         if size.x.is_infinite() {
2626//             unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
2627//         }
2628
2629//         let snapshot = editor.snapshot(cx);
2630//         let style = self.style.clone();
2631
2632//         let line_height = (style.text.font_size * style.line_height_scalar).round();
2633
2634//         let gutter_padding;
2635//         let gutter_width;
2636//         let gutter_margin;
2637//         if snapshot.show_gutter {
2638//             let em_width = style.text.em_width(cx.font_cache());
2639//             gutter_padding = (em_width * style.gutter_padding_factor).round();
2640//             gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
2641//             gutter_margin = -style.text.descent(cx.font_cache());
2642//         } else {
2643//             gutter_padding = 0.0;
2644//             gutter_width = 0.0;
2645//             gutter_margin = 0.0;
2646//         };
2647
2648//         let text_width = size.x - gutter_width;
2649//         let em_width = style.text.em_width(cx.font_cache());
2650//         let em_advance = style.text.em_advance(cx.font_cache());
2651//         let overscroll = point(em_width, 0.);
2652//         let snapshot = {
2653//             editor.set_visible_line_count(size.y / line_height, cx);
2654
2655//             let editor_width = text_width - gutter_margin - overscroll.x - em_width;
2656//             let wrap_width = match editor.soft_wrap_mode(cx) {
2657//                 SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
2658//                 SoftWrap::EditorWidth => editor_width,
2659//                 SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
2660//             };
2661
2662//             if editor.set_wrap_width(Some(wrap_width), cx) {
2663//                 editor.snapshot(cx)
2664//             } else {
2665//                 snapshot
2666//             }
2667//         };
2668
2669//         let wrap_guides = editor
2670//             .wrap_guides(cx)
2671//             .iter()
2672//             .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
2673//             .collect();
2674
2675//         let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
2676//         if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
2677//             size.set_y(
2678//                 scroll_height
2679//                     .min(constraint.max_along(Axis::Vertical))
2680//                     .max(constraint.min_along(Axis::Vertical))
2681//                     .max(line_height)
2682//                     .min(line_height * max_lines as f32),
2683//             )
2684//         } else if let EditorMode::SingleLine = snapshot.mode {
2685//             size.set_y(line_height.max(constraint.min_along(Axis::Vertical)))
2686//         } else if size.y.is_infinite() {
2687//             size.set_y(scroll_height);
2688//         }
2689//         let gutter_size = point(gutter_width, size.y);
2690//         let text_size = point(text_width, size.y);
2691
2692//         let autoscroll_horizontally = editor.autoscroll_vertically(size.y, line_height, cx);
2693//         let mut snapshot = editor.snapshot(cx);
2694
2695//         let scroll_position = snapshot.scroll_position();
2696//         // The scroll position is a fractional point, the whole number of which represents
2697//         // the top of the window in terms of display rows.
2698//         let start_row = scroll_position.y as u32;
2699//         let height_in_lines = size.y / line_height;
2700//         let max_row = snapshot.max_point().row();
2701
2702//         // Add 1 to ensure selections bleed off screen
2703//         let end_row = 1 + cmp::min(
2704//             (scroll_position.y + height_in_lines).ceil() as u32,
2705//             max_row,
2706//         );
2707
2708//         let start_anchor = if start_row == 0 {
2709//             Anchor::min()
2710//         } else {
2711//             snapshot
2712//                 .buffer_snapshot
2713//                 .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
2714//         };
2715//         let end_anchor = if end_row > max_row {
2716//             Anchor::max
2717//         } else {
2718//             snapshot
2719//                 .buffer_snapshot
2720//                 .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
2721//         };
2722
2723//         let mut selections: Vec<(SelectionStyle, Vec<SelectionLayout>)> = Vec::new();
2724//         let mut active_rows = BTreeMap::new();
2725//         let mut fold_ranges = Vec::new();
2726//         let is_singleton = editor.is_singleton(cx);
2727
2728//         let highlighted_rows = editor.highlighted_rows();
2729//         let theme = theme::current(cx);
2730//         let highlighted_ranges = editor.background_highlights_in_range(
2731//             start_anchor..end_anchor,
2732//             &snapshot.display_snapshot,
2733//             theme.as_ref(),
2734//         );
2735
2736//         fold_ranges.extend(
2737//             snapshot
2738//                 .folds_in_range(start_anchor..end_anchor)
2739//                 .map(|anchor| {
2740//                     let start = anchor.start.to_point(&snapshot.buffer_snapshot);
2741//                     (
2742//                         start.row,
2743//                         start.to_display_point(&snapshot.display_snapshot)
2744//                             ..anchor.end.to_display_point(&snapshot),
2745//                     )
2746//                 }),
2747//         );
2748
2749//         let mut newest_selection_head = None;
2750
2751//         if editor.show_local_selections {
2752//             let mut local_selections: Vec<Selection<Point>> = editor
2753//                 .selections
2754//                 .disjoint_in_range(start_anchor..end_anchor, cx);
2755//             local_selections.extend(editor.selections.pending(cx));
2756//             let mut layouts = Vec::new();
2757//             let newest = editor.selections.newest(cx);
2758//             for selection in local_selections.drain(..) {
2759//                 let is_empty = selection.start == selection.end;
2760//                 let is_newest = selection == newest;
2761
2762//                 let layout = SelectionLayout::new(
2763//                     selection,
2764//                     editor.selections.line_mode,
2765//                     editor.cursor_shape,
2766//                     &snapshot.display_snapshot,
2767//                     is_newest,
2768//                     true,
2769//                 );
2770//                 if is_newest {
2771//                     newest_selection_head = Some(layout.head);
2772//                 }
2773
2774//                 for row in cmp::max(layout.active_rows.start, start_row)
2775//                     ..=cmp::min(layout.active_rows.end, end_row)
2776//                 {
2777//                     let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
2778//                     *contains_non_empty_selection |= !is_empty;
2779//                 }
2780//                 layouts.push(layout);
2781//             }
2782
2783//             selections.push((style.selection, layouts));
2784//         }
2785
2786//         if let Some(collaboration_hub) = &editor.collaboration_hub {
2787//             // When following someone, render the local selections in their color.
2788//             if let Some(leader_id) = editor.leader_peer_id {
2789//                 if let Some(collaborator) = collaboration_hub.collaborators(cx).get(&leader_id) {
2790//                     if let Some(participant_index) = collaboration_hub
2791//                         .user_participant_indices(cx)
2792//                         .get(&collaborator.user_id)
2793//                     {
2794//                         if let Some((local_selection_style, _)) = selections.first_mut() {
2795//                             *local_selection_style =
2796//                                 style.selection_style_for_room_participant(participant_index.0);
2797//                         }
2798//                     }
2799//                 }
2800//             }
2801
2802//             let mut remote_selections = HashMap::default();
2803//             for selection in snapshot.remote_selections_in_range(
2804//                 &(start_anchor..end_anchor),
2805//                 collaboration_hub.as_ref(),
2806//                 cx,
2807//             ) {
2808//                 let selection_style = if let Some(participant_index) = selection.participant_index {
2809//                     style.selection_style_for_room_participant(participant_index.0)
2810//                 } else {
2811//                     style.absent_selection
2812//                 };
2813
2814//                 // Don't re-render the leader's selections, since the local selections
2815//                 // match theirs.
2816//                 if Some(selection.peer_id) == editor.leader_peer_id {
2817//                     continue;
2818//                 }
2819
2820//                 remote_selections
2821//                     .entry(selection.replica_id)
2822//                     .or_insert((selection_style, Vec::new()))
2823//                     .1
2824//                     .push(SelectionLayout::new(
2825//                         selection.selection,
2826//                         selection.line_mode,
2827//                         selection.cursor_shape,
2828//                         &snapshot.display_snapshot,
2829//                         false,
2830//                         false,
2831//                     ));
2832//             }
2833
2834//             selections.extend(remote_selections.into_values());
2835//         }
2836
2837//         let scrollbar_settings = &settings::get::<EditorSettings>(cx).scrollbar;
2838//         let show_scrollbars = match scrollbar_settings.show {
2839//             ShowScrollbar::Auto => {
2840//                 // Git
2841//                 (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_git_diffs())
2842//                 ||
2843//                 // Selections
2844//                 (is_singleton && scrollbar_settings.selections && !highlighted_ranges.is_empty)
2845//                 // Scrollmanager
2846//                 || editor.scroll_manager.scrollbars_visible()
2847//             }
2848//             ShowScrollbar::System => editor.scroll_manager.scrollbars_visible(),
2849//             ShowScrollbar::Always => true,
2850//             ShowScrollbar::Never => false,
2851//         };
2852
2853//         let fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)> = fold_ranges
2854//             .into_iter()
2855//             .map(|(id, fold)| {
2856//                 let color = self
2857//                     .style
2858//                     .folds
2859//                     .ellipses
2860//                     .background
2861//                     .style_for(&mut cx.mouse_state::<FoldMarkers>(id as usize))
2862//                     .color;
2863
2864//                 (id, fold, color)
2865//             })
2866//             .collect();
2867
2868//         let head_for_relative = newest_selection_head.unwrap_or_else(|| {
2869//             let newest = editor.selections.newest::<Point>(cx);
2870//             SelectionLayout::new(
2871//                 newest,
2872//                 editor.selections.line_mode,
2873//                 editor.cursor_shape,
2874//                 &snapshot.display_snapshot,
2875//                 true,
2876//                 true,
2877//             )
2878//             .head
2879//         });
2880
2881//         let (line_number_layouts, fold_statuses) = self.layout_line_numbers(
2882//             start_row..end_row,
2883//             &active_rows,
2884//             head_for_relative,
2885//             is_singleton,
2886//             &snapshot,
2887//             cx,
2888//         );
2889
2890//         let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
2891
2892//         let scrollbar_row_range = scroll_position.y..(scroll_position.y + height_in_lines);
2893
2894//         let mut max_visible_line_width = 0.0;
2895//         let line_layouts =
2896//             self.layout_lines(start_row..end_row, &line_number_layouts, &snapshot, cx);
2897//         for line_with_invisibles in &line_layouts {
2898//             if line_with_invisibles.line.width() > max_visible_line_width {
2899//                 max_visible_line_width = line_with_invisibles.line.width();
2900//             }
2901//         }
2902
2903//         let style = self.style.clone();
2904//         let longest_line_width = layout_line(
2905//             snapshot.longest_row(),
2906//             &snapshot,
2907//             &style,
2908//             cx.text_layout_cache(),
2909//         )
2910//         .width();
2911//         let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x;
2912//         let em_width = style.text.em_width(cx.font_cache());
2913//         let (scroll_width, blocks) = self.layout_blocks(
2914//             start_row..end_row,
2915//             &snapshot,
2916//             size.x,
2917//             scroll_width,
2918//             gutter_padding,
2919//             gutter_width,
2920//             em_width,
2921//             gutter_width + gutter_margin,
2922//             line_height,
2923//             &style,
2924//             &line_layouts,
2925//             editor,
2926//             cx,
2927//         );
2928
2929//         let scroll_max = point(
2930//             ((scroll_width - text_size.x) / em_width).max(0.0),
2931//             max_row as f32,
2932//         );
2933
2934//         let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
2935
2936//         let autoscrolled = if autoscroll_horizontally {
2937//             editor.autoscroll_horizontally(
2938//                 start_row,
2939//                 text_size.x,
2940//                 scroll_width,
2941//                 em_width,
2942//                 &line_layouts,
2943//                 cx,
2944//             )
2945//         } else {
2946//             false
2947//         };
2948
2949//         if clamped || autoscrolled {
2950//             snapshot = editor.snapshot(cx);
2951//         }
2952
2953//         let style = editor.style(cx);
2954
2955//         let mut context_menu = None;
2956//         let mut code_actions_indicator = None;
2957//         if let Some(newest_selection_head) = newest_selection_head {
2958//             if (start_row..end_row).contains(&newest_selection_head.row()) {
2959//                 if editor.context_menu_visible() {
2960//                     context_menu =
2961//                         editor.render_context_menu(newest_selection_head, style.clone(), cx);
2962//                 }
2963
2964//                 let active = matches!(
2965//                     editor.context_menu.read().as_ref(),
2966//                     Some(crate::ContextMenu::CodeActions(_))
2967//                 );
2968
2969//                 code_actions_indicator = editor
2970//                     .render_code_actions_indicator(&style, active, cx)
2971//                     .map(|indicator| (newest_selection_head.row(), indicator));
2972//             }
2973//         }
2974
2975//         let visible_rows = start_row..start_row + line_layouts.len() as u32;
2976//         let mut hover = editor.hover_state.render(
2977//             &snapshot,
2978//             &style,
2979//             visible_rows,
2980//             editor.workspace.as_ref().map(|(w, _)| w.clone()),
2981//             cx,
2982//         );
2983//         let mode = editor.mode;
2984
2985//         let mut fold_indicators = editor.render_fold_indicators(
2986//             fold_statuses,
2987//             &style,
2988//             editor.gutter_hovered,
2989//             line_height,
2990//             gutter_margin,
2991//             cx,
2992//         );
2993
2994//         if let Some((_, context_menu)) = context_menu.as_mut() {
2995//             context_menu.layout(
2996//                 SizeConstraint {
2997//                     min: gpui::Point::<Pixels>::zero(),
2998//                     max: point(
2999//                         cx.window_size().x * 0.7,
3000//                         (12. * line_height).min((size.y - line_height) / 2.),
3001//                     ),
3002//                 },
3003//                 editor,
3004//                 cx,
3005//             );
3006//         }
3007
3008//         if let Some((_, indicator)) = code_actions_indicator.as_mut() {
3009//             indicator.layout(
3010//                 SizeConstraint::strict_along(
3011//                     Axis::Vertical,
3012//                     line_height * style.code_actions.vertical_scale,
3013//                 ),
3014//                 editor,
3015//                 cx,
3016//             );
3017//         }
3018
3019//         for fold_indicator in fold_indicators.iter_mut() {
3020//             if let Some(indicator) = fold_indicator.as_mut() {
3021//                 indicator.layout(
3022//                     SizeConstraint::strict_along(
3023//                         Axis::Vertical,
3024//                         line_height * style.code_actions.vertical_scale,
3025//                     ),
3026//                     editor,
3027//                     cx,
3028//                 );
3029//             }
3030//         }
3031
3032//         if let Some((_, hover_popovers)) = hover.as_mut() {
3033//             for hover_popover in hover_popovers.iter_mut() {
3034//                 hover_popover.layout(
3035//                     SizeConstraint {
3036//                         min: gpui::Point::<Pixels>::zero(),
3037//                         max: point(
3038//                             (120. * em_width) // Default size
3039//                                 .min(size.x / 2.) // Shrink to half of the editor width
3040//                                 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
3041//                             (16. * line_height) // Default size
3042//                                 .min(size.y / 2.) // Shrink to half of the editor height
3043//                                 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
3044//                         ),
3045//                     },
3046//                     editor,
3047//                     cx,
3048//                 );
3049//             }
3050//         }
3051
3052//         let invisible_symbol_font_size = self.style.text.font_size / 2.0;
3053//         let invisible_symbol_style = RunStyle {
3054//             color: self.style.whitespace,
3055//             font_id: self.style.text.font_id,
3056//             underline: Default::default(),
3057//         };
3058
3059//         (
3060//             size,
3061//             LayoutState {
3062//                 mode,
3063//                 position_map: Arc::new(PositionMap {
3064//                     size,
3065//                     scroll_max,
3066//                     line_layouts,
3067//                     line_height,
3068//                     em_width,
3069//                     em_advance,
3070//                     snapshot,
3071//                 }),
3072//                 visible_display_row_range: start_row..end_row,
3073//                 wrap_guides,
3074//                 gutter_size,
3075//                 gutter_padding,
3076//                 text_size,
3077//                 scrollbar_row_range,
3078//                 show_scrollbars,
3079//                 is_singleton,
3080//                 max_row,
3081//                 gutter_margin,
3082//                 active_rows,
3083//                 highlighted_rows,
3084//                 highlighted_ranges,
3085//                 fold_ranges,
3086//                 line_number_layouts,
3087//                 display_hunks,
3088//                 blocks,
3089//                 selections,
3090//                 context_menu,
3091//                 code_actions_indicator,
3092//                 fold_indicators,
3093//                 tab_invisible: cx.text_layout_cache().layout_str(
3094//                     "→",
3095//                     invisible_symbol_font_size,
3096//                     &[("→".len(), invisible_symbol_style)],
3097//                 ),
3098//                 space_invisible: cx.text_layout_cache().layout_str(
3099//                     "•",
3100//                     invisible_symbol_font_size,
3101//                     &[("•".len(), invisible_symbol_style)],
3102//                 ),
3103//                 hover_popovers: hover,
3104//             },
3105//         )
3106//     }
3107
3108//     fn paint(
3109//         &mut self,
3110//         bounds: Bounds<Pixels>,
3111//         visible_bounds: Bounds<Pixels>,
3112//         layout: &mut Self::LayoutState,
3113//         editor: &mut Editor,
3114//         cx: &mut ViewContext<Editor>,
3115//     ) -> Self::PaintState {
3116//         let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
3117//         cx.scene().push_layer(Some(visible_bounds));
3118
3119//         let gutter_bounds = Bounds::<Pixels>::new(bounds.origin, layout.gutter_size);
3120//         let text_bounds = Bounds::<Pixels>::new(
3121//             bounds.origin + point(layout.gutter_size.x, 0.0),
3122//             layout.text_size,
3123//         );
3124
3125//         Self::attach_mouse_handlers(
3126//             &layout.position_map,
3127//             layout.hover_popovers.is_some(),
3128//             visible_bounds,
3129//             text_bounds,
3130//             gutter_bounds,
3131//             bounds,
3132//             cx,
3133//         );
3134
3135//         self.paint_background(gutter_bounds, text_bounds, layout, cx);
3136//         if layout.gutter_size.x > 0. {
3137//             self.paint_gutter(gutter_bounds, visible_bounds, layout, editor, cx);
3138//         }
3139//         self.paint_text(text_bounds, visible_bounds, layout, editor, cx);
3140
3141//         cx.scene().push_layer(Some(bounds));
3142//         if !layout.blocks.is_empty {
3143//             self.paint_blocks(bounds, visible_bounds, layout, editor, cx);
3144//         }
3145//         self.paint_scrollbar(bounds, layout, &editor, cx);
3146//         cx.scene().pop_layer();
3147//         cx.scene().pop_layer();
3148//     }
3149
3150//     fn rect_for_text_range(
3151//         &self,
3152//         range_utf16: Range<usize>,
3153//         bounds: Bounds<Pixels>,
3154//         _: Bounds<Pixels>,
3155//         layout: &Self::LayoutState,
3156//         _: &Self::PaintState,
3157//         _: &Editor,
3158//         _: &ViewContext<Editor>,
3159//     ) -> Option<Bounds<Pixels>> {
3160//         let text_bounds = Bounds::<Pixels>::new(
3161//             bounds.origin + point(layout.gutter_size.x, 0.0),
3162//             layout.text_size,
3163//         );
3164//         let content_origin = text_bounds.origin + point(layout.gutter_margin, 0.);
3165//         let scroll_position = layout.position_map.snapshot.scroll_position();
3166//         let start_row = scroll_position.y as u32;
3167//         let scroll_top = scroll_position.y * layout.position_map.line_height;
3168//         let scroll_left = scroll_position.x * layout.position_map.em_width;
3169
3170//         let range_start = OffsetUtf16(range_utf16.start)
3171//             .to_display_point(&layout.position_map.snapshot.display_snapshot);
3172//         if range_start.row() < start_row {
3173//             return None;
3174//         }
3175
3176//         let line = &layout
3177//             .position_map
3178//             .line_layouts
3179//             .get((range_start.row() - start_row) as usize)?
3180//             .line;
3181//         let range_start_x = line.x_for_index(range_start.column() as usize);
3182//         let range_start_y = range_start.row() as f32 * layout.position_map.line_height;
3183//         Some(Bounds::<Pixels>::new(
3184//             content_origin
3185//                 + point(
3186//                     range_start_x,
3187//                     range_start_y + layout.position_map.line_height,
3188//                 )
3189//                 - point(scroll_left, scroll_top),
3190//             point(
3191//                 layout.position_map.em_width,
3192//                 layout.position_map.line_height,
3193//             ),
3194//         ))
3195//     }
3196
3197//     fn debug(
3198//         &self,
3199//         bounds: Bounds<Pixels>,
3200//         _: &Self::LayoutState,
3201//         _: &Self::PaintState,
3202//         _: &Editor,
3203//         _: &ViewContext<Editor>,
3204//     ) -> json::Value {
3205//         json!({
3206//             "type": "BufferElement",
3207//             "bounds": bounds.to_json()
3208//         })
3209//     }
3210// }
3211
3212type BufferRow = u32;
3213
3214pub struct LayoutState {
3215    position_map: Arc<PositionMap>,
3216    gutter_size: Size<Pixels>,
3217    gutter_padding: Pixels,
3218    gutter_margin: Pixels,
3219    text_size: gpui::Size<Pixels>,
3220    mode: EditorMode,
3221    wrap_guides: SmallVec<[(Pixels, bool); 2]>,
3222    visible_display_row_range: Range<u32>,
3223    active_rows: BTreeMap<u32, bool>,
3224    highlighted_rows: Option<Range<u32>>,
3225    line_number_layouts: Vec<Option<gpui::Line>>,
3226    display_hunks: Vec<DisplayDiffHunk>,
3227    // blocks: Vec<BlockLayout>,
3228    highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
3229    fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Hsla)>,
3230    selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
3231    scrollbar_row_range: Range<f32>,
3232    show_scrollbars: bool,
3233    is_singleton: bool,
3234    max_row: u32,
3235    // context_menu: Option<(DisplayPoint, AnyElement<Editor>)>,
3236    // code_actions_indicator: Option<(u32, AnyElement<Editor>)>,
3237    // hover_popovers: Option<(DisplayPoint, Vec<AnyElement<Editor>>)>,
3238    // fold_indicators: Vec<Option<AnyElement<Editor>>>,
3239    tab_invisible: Line,
3240    space_invisible: Line,
3241}
3242
3243struct PositionMap {
3244    size: Size<Pixels>,
3245    line_height: Pixels,
3246    scroll_max: gpui::Point<f32>,
3247    em_width: Pixels,
3248    em_advance: Pixels,
3249    line_layouts: Vec<LineWithInvisibles>,
3250    snapshot: EditorSnapshot,
3251}
3252
3253#[derive(Debug, Copy, Clone)]
3254pub struct PointForPosition {
3255    pub previous_valid: DisplayPoint,
3256    pub next_valid: DisplayPoint,
3257    pub exact_unclipped: DisplayPoint,
3258    pub column_overshoot_after_line_end: u32,
3259}
3260
3261impl PointForPosition {
3262    #[cfg(test)]
3263    pub fn valid(valid: DisplayPoint) -> Self {
3264        Self {
3265            previous_valid: valid,
3266            next_valid: valid,
3267            exact_unclipped: valid,
3268            column_overshoot_after_line_end: 0,
3269        }
3270    }
3271
3272    pub fn as_valid(&self) -> Option<DisplayPoint> {
3273        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
3274            Some(self.previous_valid)
3275        } else {
3276            None
3277        }
3278    }
3279}
3280
3281impl PositionMap {
3282    fn point_for_position(
3283        &self,
3284        text_bounds: Bounds<Pixels>,
3285        position: gpui::Point<Pixels>,
3286    ) -> PointForPosition {
3287        let scroll_position = self.snapshot.scroll_position();
3288        let position = position - text_bounds.origin;
3289        let y = position.y.max(px(0.)).min(self.size.width);
3290        let x = position.x + (scroll_position.x * self.em_width);
3291        let row = (f32::from(y / self.line_height) + scroll_position.y) as u32;
3292
3293        let (column, x_overshoot_after_line_end) = if let Some(line) = self
3294            .line_layouts
3295            .get(row as usize - scroll_position.y as usize)
3296            .map(|&LineWithInvisibles { ref line, .. }| line)
3297        {
3298            if let Some(ix) = line.index_for_x(x) {
3299                (ix as u32, px(0.))
3300            } else {
3301                (line.len as u32, px(0.).max(x - line.width))
3302            }
3303        } else {
3304            (0, x)
3305        };
3306
3307        let mut exact_unclipped = DisplayPoint::new(row, column);
3308        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
3309        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
3310
3311        let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance).into();
3312        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
3313        PointForPosition {
3314            previous_valid,
3315            next_valid,
3316            exact_unclipped,
3317            column_overshoot_after_line_end,
3318        }
3319    }
3320}
3321
3322struct BlockLayout {
3323    row: u32,
3324    element: AnyElement<Editor>,
3325    style: BlockStyle,
3326}
3327
3328fn layout_line(
3329    row: u32,
3330    snapshot: &EditorSnapshot,
3331    style: &EditorStyle,
3332    cx: &WindowContext,
3333) -> Result<Line> {
3334    let mut line = snapshot.line(row);
3335
3336    if line.len() > MAX_LINE_LEN {
3337        let mut len = MAX_LINE_LEN;
3338        while !line.is_char_boundary(len) {
3339            len -= 1;
3340        }
3341
3342        line.truncate(len);
3343    }
3344
3345    Ok(cx
3346        .text_system()
3347        .layout_text(
3348            &line,
3349            style.text.font_size.to_pixels(cx.rem_size()),
3350            &[TextRun {
3351                len: snapshot.line_len(row) as usize,
3352                font: style.text.font(),
3353                color: Hsla::default(),
3354                underline: None,
3355            }],
3356            None,
3357        )?
3358        .pop()
3359        .unwrap())
3360}
3361
3362#[derive(Debug)]
3363pub struct Cursor {
3364    origin: gpui::Point<Pixels>,
3365    block_width: Pixels,
3366    line_height: Pixels,
3367    color: Hsla,
3368    shape: CursorShape,
3369    block_text: Option<Line>,
3370}
3371
3372impl Cursor {
3373    pub fn new(
3374        origin: gpui::Point<Pixels>,
3375        block_width: Pixels,
3376        line_height: Pixels,
3377        color: Hsla,
3378        shape: CursorShape,
3379        block_text: Option<Line>,
3380    ) -> Cursor {
3381        Cursor {
3382            origin,
3383            block_width,
3384            line_height,
3385            color,
3386            shape,
3387            block_text,
3388        }
3389    }
3390
3391    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
3392        Bounds {
3393            origin: self.origin + origin,
3394            size: size(self.block_width, self.line_height),
3395        }
3396    }
3397
3398    pub fn paint(&self, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
3399        let bounds = match self.shape {
3400            CursorShape::Bar => Bounds {
3401                origin: self.origin + origin,
3402                size: size(px(2.0), self.line_height),
3403            },
3404            CursorShape::Block | CursorShape::Hollow => Bounds {
3405                origin: self.origin + origin,
3406                size: size(self.block_width, self.line_height),
3407            },
3408            CursorShape::Underscore => Bounds {
3409                origin: self.origin
3410                    + origin
3411                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
3412                size: size(self.block_width, px(2.0)),
3413            },
3414        };
3415
3416        //Draw background or border quad
3417        if matches!(self.shape, CursorShape::Hollow) {
3418            cx.paint_quad(
3419                bounds,
3420                Corners::default(),
3421                transparent_black(),
3422                Edges::all(px(1.)),
3423                self.color,
3424            );
3425        } else {
3426            cx.paint_quad(
3427                bounds,
3428                Corners::default(),
3429                self.color,
3430                Edges::default(),
3431                transparent_black(),
3432            );
3433        }
3434
3435        if let Some(block_text) = &self.block_text {
3436            block_text.paint(self.origin + origin, self.line_height, cx);
3437        }
3438    }
3439
3440    pub fn shape(&self) -> CursorShape {
3441        self.shape
3442    }
3443}
3444
3445#[derive(Debug)]
3446pub struct HighlightedRange {
3447    pub start_y: Pixels,
3448    pub line_height: Pixels,
3449    pub lines: Vec<HighlightedRangeLine>,
3450    pub color: Hsla,
3451    pub corner_radius: Pixels,
3452}
3453
3454#[derive(Debug)]
3455pub struct HighlightedRangeLine {
3456    pub start_x: Pixels,
3457    pub end_x: Pixels,
3458}
3459
3460impl HighlightedRange {
3461    pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut WindowContext) {
3462        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
3463            self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
3464            self.paint_lines(
3465                self.start_y + self.line_height,
3466                &self.lines[1..],
3467                bounds,
3468                cx,
3469            );
3470        } else {
3471            self.paint_lines(self.start_y, &self.lines, bounds, cx);
3472        }
3473    }
3474
3475    fn paint_lines(
3476        &self,
3477        start_y: Pixels,
3478        lines: &[HighlightedRangeLine],
3479        bounds: Bounds<Pixels>,
3480        cx: &mut WindowContext,
3481    ) {
3482        if lines.is_empty() {
3483            return;
3484        }
3485
3486        let first_line = lines.first().unwrap();
3487        let last_line = lines.last().unwrap();
3488
3489        let first_top_left = point(first_line.start_x, start_y);
3490        let first_top_right = point(first_line.end_x, start_y);
3491
3492        let curve_height = point(Pixels::ZERO, self.corner_radius);
3493        let curve_width = |start_x: Pixels, end_x: Pixels| {
3494            let max = (end_x - start_x) / 2.;
3495            let width = if max < self.corner_radius {
3496                max
3497            } else {
3498                self.corner_radius
3499            };
3500
3501            point(width, Pixels::ZERO)
3502        };
3503
3504        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
3505        let mut path = gpui::Path::new(first_top_right - top_curve_width);
3506        path.curve_to(first_top_right + curve_height, first_top_right);
3507
3508        let mut iter = lines.iter().enumerate().peekable();
3509        while let Some((ix, line)) = iter.next() {
3510            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
3511
3512            if let Some((_, next_line)) = iter.peek() {
3513                let next_top_right = point(next_line.end_x, bottom_right.y);
3514
3515                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
3516                    Ordering::Equal => {
3517                        path.line_to(bottom_right);
3518                    }
3519                    Ordering::Less => {
3520                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
3521                        path.line_to(bottom_right - curve_height);
3522                        if self.corner_radius > Pixels::ZERO {
3523                            path.curve_to(bottom_right - curve_width, bottom_right);
3524                        }
3525                        path.line_to(next_top_right + curve_width);
3526                        if self.corner_radius > Pixels::ZERO {
3527                            path.curve_to(next_top_right + curve_height, next_top_right);
3528                        }
3529                    }
3530                    Ordering::Greater => {
3531                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
3532                        path.line_to(bottom_right - curve_height);
3533                        if self.corner_radius > Pixels::ZERO {
3534                            path.curve_to(bottom_right + curve_width, bottom_right);
3535                        }
3536                        path.line_to(next_top_right - curve_width);
3537                        if self.corner_radius > Pixels::ZERO {
3538                            path.curve_to(next_top_right + curve_height, next_top_right);
3539                        }
3540                    }
3541                }
3542            } else {
3543                let curve_width = curve_width(line.start_x, line.end_x);
3544                path.line_to(bottom_right - curve_height);
3545                if self.corner_radius > Pixels::ZERO {
3546                    path.curve_to(bottom_right - curve_width, bottom_right);
3547                }
3548
3549                let bottom_left = point(line.start_x, bottom_right.y);
3550                path.line_to(bottom_left + curve_width);
3551                if self.corner_radius > Pixels::ZERO {
3552                    path.curve_to(bottom_left - curve_height, bottom_left);
3553                }
3554            }
3555        }
3556
3557        if first_line.start_x > last_line.start_x {
3558            let curve_width = curve_width(last_line.start_x, first_line.start_x);
3559            let second_top_left = point(last_line.start_x, start_y + self.line_height);
3560            path.line_to(second_top_left + curve_height);
3561            if self.corner_radius > Pixels::ZERO {
3562                path.curve_to(second_top_left + curve_width, second_top_left);
3563            }
3564            let first_bottom_left = point(first_line.start_x, second_top_left.y);
3565            path.line_to(first_bottom_left - curve_width);
3566            if self.corner_radius > Pixels::ZERO {
3567                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
3568            }
3569        }
3570
3571        path.line_to(first_top_left + curve_height);
3572        if self.corner_radius > Pixels::ZERO {
3573            path.curve_to(first_top_left + top_curve_width, first_top_left);
3574        }
3575        path.line_to(first_top_right - top_curve_width);
3576
3577        cx.paint_path(path, self.color);
3578    }
3579}
3580
3581// fn range_to_bounds(
3582//     range: &Range<DisplayPoint>,
3583//     content_origin: gpui::Point<Pixels>,
3584//     scroll_left: f32,
3585//     scroll_top: f32,
3586//     visible_row_range: &Range<u32>,
3587//     line_end_overshoot: f32,
3588//     position_map: &PositionMap,
3589// ) -> impl Iterator<Item = Bounds<Pixels>> {
3590//     let mut bounds: SmallVec<[Bounds<Pixels>; 1]> = SmallVec::new();
3591
3592//     if range.start == range.end {
3593//         return bounds.into_iter();
3594//     }
3595
3596//     let start_row = visible_row_range.start;
3597//     let end_row = visible_row_range.end;
3598
3599//     let row_range = if range.end.column() == 0 {
3600//         cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
3601//     } else {
3602//         cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
3603//     };
3604
3605//     let first_y =
3606//         content_origin.y + row_range.start as f32 * position_map.line_height - scroll_top;
3607
3608//     for (idx, row) in row_range.enumerate() {
3609//         let line_layout = &position_map.line_layouts[(row - start_row) as usize].line;
3610
3611//         let start_x = if row == range.start.row() {
3612//             content_origin.x + line_layout.x_for_index(range.start.column() as usize)
3613//                 - scroll_left
3614//         } else {
3615//             content_origin.x - scroll_left
3616//         };
3617
3618//         let end_x = if row == range.end.row() {
3619//             content_origin.x + line_layout.x_for_index(range.end.column() as usize) - scroll_left
3620//         } else {
3621//             content_origin.x + line_layout.width() + line_end_overshoot - scroll_left
3622//         };
3623
3624//         bounds.push(Bounds::<Pixels>::from_points(
3625//             point(start_x, first_y + position_map.line_height * idx as f32),
3626//             point(end_x, first_y + position_map.line_height * (idx + 1) as f32),
3627//         ))
3628//     }
3629
3630//     bounds.into_iter()
3631// }
3632
3633pub fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
3634    delta.powf(1.5) / 100.0
3635}
3636
3637fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
3638    delta.powf(1.2) / 300.0
3639}
3640
3641// #[cfg(test)]
3642// mod tests {
3643//     use super::*;
3644//     use crate::{
3645//         display_map::{BlockDisposition, BlockProperties},
3646//         editor_tests::{init_test, update_test_language_settings},
3647//         Editor, MultiBuffer,
3648//     };
3649//     use gpui::TestAppContext;
3650//     use language::language_settings;
3651//     use log::info;
3652//     use std::{num::NonZeroU32, sync::Arc};
3653//     use util::test::sample_text;
3654
3655//     #[gpui::test]
3656//     fn test_layout_line_numbers(cx: &mut TestAppContext) {
3657//         init_test(cx, |_| {});
3658//         let editor = cx
3659//             .add_window(|cx| {
3660//                 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
3661//                 Editor::new(EditorMode::Full, buffer, None, None, cx)
3662//             })
3663//             .root(cx);
3664//         let element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3665
3666//         let layouts = editor.update(cx, |editor, cx| {
3667//             let snapshot = editor.snapshot(cx);
3668//             element
3669//                 .layout_line_numbers(
3670//                     0..6,
3671//                     &Default::default(),
3672//                     DisplayPoint::new(0, 0),
3673//                     false,
3674//                     &snapshot,
3675//                     cx,
3676//                 )
3677//                 .0
3678//         });
3679//         assert_eq!(layouts.len(), 6);
3680
3681//         let relative_rows = editor.update(cx, |editor, cx| {
3682//             let snapshot = editor.snapshot(cx);
3683//             element.calculate_relative_line_numbers(&snapshot, &(0..6), Some(3))
3684//         });
3685//         assert_eq!(relative_rows[&0], 3);
3686//         assert_eq!(relative_rows[&1], 2);
3687//         assert_eq!(relative_rows[&2], 1);
3688//         // current line has no relative number
3689//         assert_eq!(relative_rows[&4], 1);
3690//         assert_eq!(relative_rows[&5], 2);
3691
3692//         // works if cursor is before screen
3693//         let relative_rows = editor.update(cx, |editor, cx| {
3694//             let snapshot = editor.snapshot(cx);
3695
3696//             element.calculate_relative_line_numbers(&snapshot, &(3..6), Some(1))
3697//         });
3698//         assert_eq!(relative_rows.len(), 3);
3699//         assert_eq!(relative_rows[&3], 2);
3700//         assert_eq!(relative_rows[&4], 3);
3701//         assert_eq!(relative_rows[&5], 4);
3702
3703//         // works if cursor is after screen
3704//         let relative_rows = editor.update(cx, |editor, cx| {
3705//             let snapshot = editor.snapshot(cx);
3706
3707//             element.calculate_relative_line_numbers(&snapshot, &(0..3), Some(6))
3708//         });
3709//         assert_eq!(relative_rows.len(), 3);
3710//         assert_eq!(relative_rows[&0], 5);
3711//         assert_eq!(relative_rows[&1], 4);
3712//         assert_eq!(relative_rows[&2], 3);
3713//     }
3714
3715//     #[gpui::test]
3716//     async fn test_vim_visual_selections(cx: &mut TestAppContext) {
3717//         init_test(cx, |_| {});
3718
3719//         let editor = cx
3720//             .add_window(|cx| {
3721//                 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
3722//                 Editor::new(EditorMode::Full, buffer, None, None, cx)
3723//             })
3724//             .root(cx);
3725//         let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3726//         let (_, state) = editor.update(cx, |editor, cx| {
3727//             editor.cursor_shape = CursorShape::Block;
3728//             editor.change_selections(None, cx, |s| {
3729//                 s.select_ranges([
3730//                     Point::new(0, 0)..Point::new(1, 0),
3731//                     Point::new(3, 2)..Point::new(3, 3),
3732//                     Point::new(5, 6)..Point::new(6, 0),
3733//                 ]);
3734//             });
3735//             element.layout(
3736//                 SizeConstraint::new(point(500., 500.), point(500., 500.)),
3737//                 editor,
3738//                 cx,
3739//             )
3740//         });
3741//         assert_eq!(state.selections.len(), 1);
3742//         let local_selections = &state.selections[0].1;
3743//         assert_eq!(local_selections.len(), 3);
3744//         // moves cursor back one line
3745//         assert_eq!(local_selections[0].head, DisplayPoint::new(0, 6));
3746//         assert_eq!(
3747//             local_selections[0].range,
3748//             DisplayPoint::new(0, 0)..DisplayPoint::new(1, 0)
3749//         );
3750
3751//         // moves cursor back one column
3752//         assert_eq!(
3753//             local_selections[1].range,
3754//             DisplayPoint::new(3, 2)..DisplayPoint::new(3, 3)
3755//         );
3756//         assert_eq!(local_selections[1].head, DisplayPoint::new(3, 2));
3757
3758//         // leaves cursor on the max point
3759//         assert_eq!(
3760//             local_selections[2].range,
3761//             DisplayPoint::new(5, 6)..DisplayPoint::new(6, 0)
3762//         );
3763//         assert_eq!(local_selections[2].head, DisplayPoint::new(6, 0));
3764
3765//         // active lines does not include 1 (even though the range of the selection does)
3766//         assert_eq!(
3767//             state.active_rows.keys().cloned().collect::<Vec<u32>>(),
3768//             vec![0, 3, 5, 6]
3769//         );
3770
3771//         // multi-buffer support
3772//         // in DisplayPoint co-ordinates, this is what we're dealing with:
3773//         //  0: [[file
3774//         //  1:   header]]
3775//         //  2: aaaaaa
3776//         //  3: bbbbbb
3777//         //  4: cccccc
3778//         //  5:
3779//         //  6: ...
3780//         //  7: ffffff
3781//         //  8: gggggg
3782//         //  9: hhhhhh
3783//         // 10:
3784//         // 11: [[file
3785//         // 12:   header]]
3786//         // 13: bbbbbb
3787//         // 14: cccccc
3788//         // 15: dddddd
3789//         let editor = cx
3790//             .add_window(|cx| {
3791//                 let buffer = MultiBuffer::build_multi(
3792//                     [
3793//                         (
3794//                             &(sample_text(8, 6, 'a') + "\n"),
3795//                             vec![
3796//                                 Point::new(0, 0)..Point::new(3, 0),
3797//                                 Point::new(4, 0)..Point::new(7, 0),
3798//                             ],
3799//                         ),
3800//                         (
3801//                             &(sample_text(8, 6, 'a') + "\n"),
3802//                             vec![Point::new(1, 0)..Point::new(3, 0)],
3803//                         ),
3804//                     ],
3805//                     cx,
3806//                 );
3807//                 Editor::new(EditorMode::Full, buffer, None, None, cx)
3808//             })
3809//             .root(cx);
3810//         let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3811//         let (_, state) = editor.update(cx, |editor, cx| {
3812//             editor.cursor_shape = CursorShape::Block;
3813//             editor.change_selections(None, cx, |s| {
3814//                 s.select_display_ranges([
3815//                     DisplayPoint::new(4, 0)..DisplayPoint::new(7, 0),
3816//                     DisplayPoint::new(10, 0)..DisplayPoint::new(13, 0),
3817//                 ]);
3818//             });
3819//             element.layout(
3820//                 SizeConstraint::new(point(500., 500.), point(500., 500.)),
3821//                 editor,
3822//                 cx,
3823//             )
3824//         });
3825
3826//         assert_eq!(state.selections.len(), 1);
3827//         let local_selections = &state.selections[0].1;
3828//         assert_eq!(local_selections.len(), 2);
3829
3830//         // moves cursor on excerpt boundary back a line
3831//         // and doesn't allow selection to bleed through
3832//         assert_eq!(
3833//             local_selections[0].range,
3834//             DisplayPoint::new(4, 0)..DisplayPoint::new(6, 0)
3835//         );
3836//         assert_eq!(local_selections[0].head, DisplayPoint::new(5, 0));
3837
3838//         // moves cursor on buffer boundary back two lines
3839//         // and doesn't allow selection to bleed through
3840//         assert_eq!(
3841//             local_selections[1].range,
3842//             DisplayPoint::new(10, 0)..DisplayPoint::new(11, 0)
3843//         );
3844//         assert_eq!(local_selections[1].head, DisplayPoint::new(10, 0));
3845//     }
3846
3847//     #[gpui::test]
3848//     fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
3849//         init_test(cx, |_| {});
3850
3851//         let editor = cx
3852//             .add_window(|cx| {
3853//                 let buffer = MultiBuffer::build_simple("", cx);
3854//                 Editor::new(EditorMode::Full, buffer, None, None, cx)
3855//             })
3856//             .root(cx);
3857
3858//         editor.update(cx, |editor, cx| {
3859//             editor.set_placeholder_text("hello", cx);
3860//             editor.insert_blocks(
3861//                 [BlockProperties {
3862//                     style: BlockStyle::Fixed,
3863//                     disposition: BlockDisposition::Above,
3864//                     height: 3,
3865//                     position: Anchor::min(),
3866//                     render: Arc::new(|_| Empty::new().into_any),
3867//                 }],
3868//                 None,
3869//                 cx,
3870//             );
3871
3872//             // Blur the editor so that it displays placeholder text.
3873//             cx.blur();
3874//         });
3875
3876//         let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3877//         let (size, mut state) = editor.update(cx, |editor, cx| {
3878//             element.layout(
3879//                 SizeConstraint::new(point(500., 500.), point(500., 500.)),
3880//                 editor,
3881//                 cx,
3882//             )
3883//         });
3884
3885//         assert_eq!(state.position_map.line_layouts.len(), 4);
3886//         assert_eq!(
3887//             state
3888//                 .line_number_layouts
3889//                 .iter()
3890//                 .map(Option::is_some)
3891//                 .collect::<Vec<_>>(),
3892//             &[false, false, false, true]
3893//         );
3894
3895//         // Don't panic.
3896//         let bounds = Bounds::<Pixels>::new(Default::default(), size);
3897//         editor.update(cx, |editor, cx| {
3898//             element.paint(bounds, bounds, &mut state, editor, cx);
3899//         });
3900//     }
3901
3902//     #[gpui::test]
3903//     fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
3904//         const TAB_SIZE: u32 = 4;
3905
3906//         let input_text = "\t \t|\t| a b";
3907//         let expected_invisibles = vec![
3908//             Invisible::Tab {
3909//                 line_start_offset: 0,
3910//             },
3911//             Invisible::Whitespace {
3912//                 line_offset: TAB_SIZE as usize,
3913//             },
3914//             Invisible::Tab {
3915//                 line_start_offset: TAB_SIZE as usize + 1,
3916//             },
3917//             Invisible::Tab {
3918//                 line_start_offset: TAB_SIZE as usize * 2 + 1,
3919//             },
3920//             Invisible::Whitespace {
3921//                 line_offset: TAB_SIZE as usize * 3 + 1,
3922//             },
3923//             Invisible::Whitespace {
3924//                 line_offset: TAB_SIZE as usize * 3 + 3,
3925//             },
3926//         ];
3927//         assert_eq!(
3928//             expected_invisibles.len(),
3929//             input_text
3930//                 .chars()
3931//                 .filter(|initial_char| initial_char.is_whitespace())
3932//                 .count(),
3933//             "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
3934//         );
3935
3936//         init_test(cx, |s| {
3937//             s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3938//             s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
3939//         });
3940
3941//         let actual_invisibles =
3942//             collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, 500.0);
3943
3944//         assert_eq!(expected_invisibles, actual_invisibles);
3945//     }
3946
3947//     #[gpui::test]
3948//     fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
3949//         init_test(cx, |s| {
3950//             s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3951//             s.defaults.tab_size = NonZeroU32::new(4);
3952//         });
3953
3954//         for editor_mode_without_invisibles in [
3955//             EditorMode::SingleLine,
3956//             EditorMode::AutoHeight { max_lines: 100 },
3957//         ] {
3958//             let invisibles = collect_invisibles_from_new_editor(
3959//                 cx,
3960//                 editor_mode_without_invisibles,
3961//                 "\t\t\t| | a b",
3962//                 500.0,
3963//             );
3964//             assert!(invisibles.is_empty,
3965//                 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
3966//         }
3967//     }
3968
3969//     #[gpui::test]
3970//     fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
3971//         let tab_size = 4;
3972//         let input_text = "a\tbcd   ".repeat(9);
3973//         let repeated_invisibles = [
3974//             Invisible::Tab {
3975//                 line_start_offset: 1,
3976//             },
3977//             Invisible::Whitespace {
3978//                 line_offset: tab_size as usize + 3,
3979//             },
3980//             Invisible::Whitespace {
3981//                 line_offset: tab_size as usize + 4,
3982//             },
3983//             Invisible::Whitespace {
3984//                 line_offset: tab_size as usize + 5,
3985//             },
3986//         ];
3987//         let expected_invisibles = std::iter::once(repeated_invisibles)
3988//             .cycle()
3989//             .take(9)
3990//             .flatten()
3991//             .collect::<Vec<_>>();
3992//         assert_eq!(
3993//             expected_invisibles.len(),
3994//             input_text
3995//                 .chars()
3996//                 .filter(|initial_char| initial_char.is_whitespace())
3997//                 .count(),
3998//             "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
3999//         );
4000//         info!("Expected invisibles: {expected_invisibles:?}");
4001
4002//         init_test(cx, |_| {});
4003
4004//         // Put the same string with repeating whitespace pattern into editors of various size,
4005//         // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
4006//         let resize_step = 10.0;
4007//         let mut editor_width = 200.0;
4008//         while editor_width <= 1000.0 {
4009//             update_test_language_settings(cx, |s| {
4010//                 s.defaults.tab_size = NonZeroU32::new(tab_size);
4011//                 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4012//                 s.defaults.preferred_line_length = Some(editor_width as u32);
4013//                 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
4014//             });
4015
4016//             let actual_invisibles =
4017//                 collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, editor_width);
4018
4019//             // Whatever the editor size is, ensure it has the same invisible kinds in the same order
4020//             // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
4021//             let mut i = 0;
4022//             for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
4023//                 i = actual_index;
4024//                 match expected_invisibles.get(i) {
4025//                     Some(expected_invisible) => match (expected_invisible, actual_invisible) {
4026//                         (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
4027//                         | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
4028//                         _ => {
4029//                             panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
4030//                         }
4031//                     },
4032//                     None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
4033//                 }
4034//             }
4035//             let missing_expected_invisibles = &expected_invisibles[i + 1..];
4036//             assert!(
4037//                 missing_expected_invisibles.is_empty,
4038//                 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
4039//             );
4040
4041//             editor_width += resize_step;
4042//         }
4043//     }
4044
4045//     fn collect_invisibles_from_new_editor(
4046//         cx: &mut TestAppContext,
4047//         editor_mode: EditorMode,
4048//         input_text: &str,
4049//         editor_width: f32,
4050//     ) -> Vec<Invisible> {
4051//         info!(
4052//             "Creating editor with mode {editor_mode:?}, width {editor_width} and text '{input_text}'"
4053//         );
4054//         let editor = cx
4055//             .add_window(|cx| {
4056//                 let buffer = MultiBuffer::build_simple(&input_text, cx);
4057//                 Editor::new(editor_mode, buffer, None, None, cx)
4058//             })
4059//             .root(cx);
4060
4061//         let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
4062//         let (_, layout_state) = editor.update(cx, |editor, cx| {
4063//             editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
4064//             editor.set_wrap_width(Some(editor_width), cx);
4065
4066//             element.layout(
4067//                 SizeConstraint::new(point(editor_width, 500.), point(editor_width, 500.)),
4068//                 editor,
4069//                 cx,
4070//             )
4071//         });
4072
4073//         layout_state
4074//             .position_map
4075//             .line_layouts
4076//             .iter()
4077//             .map(|line_with_invisibles| &line_with_invisibles.invisibles)
4078//             .flatten()
4079//             .cloned()
4080//             .collect()
4081//     }
4082// }