element.rs

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