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