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