element.rs

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