element.rs

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