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