element.rs

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