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