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