element.rs

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