element.rs

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