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            let mut remote_selections = HashMap::default();
2254            for selection in snapshot.remote_selections_in_range(
2255                &(start_anchor..end_anchor),
2256                collaboration_hub.as_ref(),
2257                cx,
2258            ) {
2259                let selection_style = if let Some(participant_index) = selection.participant_index {
2260                    style.selection_style_for_room_participant(participant_index.0)
2261                } else {
2262                    style.absent_selection
2263                };
2264
2265                // The local selections match the leader's selections.
2266                if Some(selection.peer_id) == editor.leader_peer_id {
2267                    if let Some((local_selection_style, _)) = selections.first_mut() {
2268                        *local_selection_style = selection_style;
2269                    }
2270                    continue;
2271                }
2272
2273                remote_selections
2274                    .entry(selection.replica_id)
2275                    .or_insert((selection_style, Vec::new()))
2276                    .1
2277                    .push(SelectionLayout::new(
2278                        selection.selection,
2279                        selection.line_mode,
2280                        selection.cursor_shape,
2281                        &snapshot.display_snapshot,
2282                        false,
2283                        false,
2284                    ));
2285            }
2286
2287            selections.extend(remote_selections.into_values());
2288        }
2289
2290        let scrollbar_settings = &settings::get::<EditorSettings>(cx).scrollbar;
2291        let show_scrollbars = match scrollbar_settings.show {
2292            ShowScrollbar::Auto => {
2293                // Git
2294                (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_git_diffs())
2295                ||
2296                // Selections
2297                (is_singleton && scrollbar_settings.selections && !highlighted_ranges.is_empty())
2298                // Scrollmanager
2299                || editor.scroll_manager.scrollbars_visible()
2300            }
2301            ShowScrollbar::System => editor.scroll_manager.scrollbars_visible(),
2302            ShowScrollbar::Always => true,
2303            ShowScrollbar::Never => false,
2304        };
2305
2306        let fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)> = fold_ranges
2307            .into_iter()
2308            .map(|(id, fold)| {
2309                let color = self
2310                    .style
2311                    .folds
2312                    .ellipses
2313                    .background
2314                    .style_for(&mut cx.mouse_state::<FoldMarkers>(id as usize))
2315                    .color;
2316
2317                (id, fold, color)
2318            })
2319            .collect();
2320
2321        let head_for_relative = newest_selection_head.unwrap_or_else(|| {
2322            let newest = editor.selections.newest::<Point>(cx);
2323            SelectionLayout::new(
2324                newest,
2325                editor.selections.line_mode,
2326                editor.cursor_shape,
2327                &snapshot.display_snapshot,
2328                true,
2329                true,
2330            )
2331            .head
2332        });
2333
2334        let (line_number_layouts, fold_statuses) = self.layout_line_numbers(
2335            start_row..end_row,
2336            &active_rows,
2337            head_for_relative,
2338            is_singleton,
2339            &snapshot,
2340            cx,
2341        );
2342
2343        let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
2344
2345        let scrollbar_row_range = scroll_position.y()..(scroll_position.y() + height_in_lines);
2346
2347        let mut max_visible_line_width = 0.0;
2348        let line_layouts =
2349            self.layout_lines(start_row..end_row, &line_number_layouts, &snapshot, cx);
2350        for line_with_invisibles in &line_layouts {
2351            if line_with_invisibles.line.width() > max_visible_line_width {
2352                max_visible_line_width = line_with_invisibles.line.width();
2353            }
2354        }
2355
2356        let style = self.style.clone();
2357        let longest_line_width = layout_line(
2358            snapshot.longest_row(),
2359            &snapshot,
2360            &style,
2361            cx.text_layout_cache(),
2362        )
2363        .width();
2364        let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
2365        let em_width = style.text.em_width(cx.font_cache());
2366        let (scroll_width, blocks) = self.layout_blocks(
2367            start_row..end_row,
2368            &snapshot,
2369            size.x(),
2370            scroll_width,
2371            gutter_padding,
2372            gutter_width,
2373            em_width,
2374            gutter_width + gutter_margin,
2375            line_height,
2376            &style,
2377            &line_layouts,
2378            editor,
2379            cx,
2380        );
2381
2382        let scroll_max = vec2f(
2383            ((scroll_width - text_size.x()) / em_width).max(0.0),
2384            max_row as f32,
2385        );
2386
2387        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x());
2388
2389        let autoscrolled = if autoscroll_horizontally {
2390            editor.autoscroll_horizontally(
2391                start_row,
2392                text_size.x(),
2393                scroll_width,
2394                em_width,
2395                &line_layouts,
2396                cx,
2397            )
2398        } else {
2399            false
2400        };
2401
2402        if clamped || autoscrolled {
2403            snapshot = editor.snapshot(cx);
2404        }
2405
2406        let style = editor.style(cx);
2407
2408        let mut context_menu = None;
2409        let mut code_actions_indicator = None;
2410        if let Some(newest_selection_head) = newest_selection_head {
2411            if (start_row..end_row).contains(&newest_selection_head.row()) {
2412                if editor.context_menu_visible() {
2413                    context_menu =
2414                        editor.render_context_menu(newest_selection_head, style.clone(), cx);
2415                }
2416
2417                let active = matches!(
2418                    editor.context_menu,
2419                    Some(crate::ContextMenu::CodeActions(_))
2420                );
2421
2422                code_actions_indicator = editor
2423                    .render_code_actions_indicator(&style, active, cx)
2424                    .map(|indicator| (newest_selection_head.row(), indicator));
2425            }
2426        }
2427
2428        let visible_rows = start_row..start_row + line_layouts.len() as u32;
2429        let mut hover = editor
2430            .hover_state
2431            .render(&snapshot, &style, visible_rows, cx);
2432        let mode = editor.mode;
2433
2434        let mut fold_indicators = editor.render_fold_indicators(
2435            fold_statuses,
2436            &style,
2437            editor.gutter_hovered,
2438            line_height,
2439            gutter_margin,
2440            cx,
2441        );
2442
2443        if let Some((_, context_menu)) = context_menu.as_mut() {
2444            context_menu.layout(
2445                SizeConstraint {
2446                    min: Vector2F::zero(),
2447                    max: vec2f(
2448                        cx.window_size().x() * 0.7,
2449                        (12. * line_height).min((size.y() - line_height) / 2.),
2450                    ),
2451                },
2452                editor,
2453                cx,
2454            );
2455        }
2456
2457        if let Some((_, indicator)) = code_actions_indicator.as_mut() {
2458            indicator.layout(
2459                SizeConstraint::strict_along(
2460                    Axis::Vertical,
2461                    line_height * style.code_actions.vertical_scale,
2462                ),
2463                editor,
2464                cx,
2465            );
2466        }
2467
2468        for fold_indicator in fold_indicators.iter_mut() {
2469            if let Some(indicator) = fold_indicator.as_mut() {
2470                indicator.layout(
2471                    SizeConstraint::strict_along(
2472                        Axis::Vertical,
2473                        line_height * style.code_actions.vertical_scale,
2474                    ),
2475                    editor,
2476                    cx,
2477                );
2478            }
2479        }
2480
2481        if let Some((_, hover_popovers)) = hover.as_mut() {
2482            for hover_popover in hover_popovers.iter_mut() {
2483                hover_popover.layout(
2484                    SizeConstraint {
2485                        min: Vector2F::zero(),
2486                        max: vec2f(
2487                            (120. * em_width) // Default size
2488                                .min(size.x() / 2.) // Shrink to half of the editor width
2489                                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2490                            (16. * line_height) // Default size
2491                                .min(size.y() / 2.) // Shrink to half of the editor height
2492                                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2493                        ),
2494                    },
2495                    editor,
2496                    cx,
2497                );
2498            }
2499        }
2500
2501        let invisible_symbol_font_size = self.style.text.font_size / 2.0;
2502        let invisible_symbol_style = RunStyle {
2503            color: self.style.whitespace,
2504            font_id: self.style.text.font_id,
2505            underline: Default::default(),
2506        };
2507
2508        (
2509            size,
2510            LayoutState {
2511                mode,
2512                position_map: Arc::new(PositionMap {
2513                    size,
2514                    scroll_max,
2515                    line_layouts,
2516                    line_height,
2517                    em_width,
2518                    em_advance,
2519                    snapshot,
2520                }),
2521                visible_display_row_range: start_row..end_row,
2522                wrap_guides,
2523                gutter_size,
2524                gutter_padding,
2525                text_size,
2526                scrollbar_row_range,
2527                show_scrollbars,
2528                is_singleton,
2529                max_row,
2530                gutter_margin,
2531                active_rows,
2532                highlighted_rows,
2533                highlighted_ranges,
2534                fold_ranges,
2535                line_number_layouts,
2536                display_hunks,
2537                blocks,
2538                selections,
2539                context_menu,
2540                code_actions_indicator,
2541                fold_indicators,
2542                tab_invisible: cx.text_layout_cache().layout_str(
2543                    "",
2544                    invisible_symbol_font_size,
2545                    &[("".len(), invisible_symbol_style)],
2546                ),
2547                space_invisible: cx.text_layout_cache().layout_str(
2548                    "",
2549                    invisible_symbol_font_size,
2550                    &[("".len(), invisible_symbol_style)],
2551                ),
2552                hover_popovers: hover,
2553            },
2554        )
2555    }
2556
2557    fn paint(
2558        &mut self,
2559        bounds: RectF,
2560        visible_bounds: RectF,
2561        layout: &mut Self::LayoutState,
2562        editor: &mut Editor,
2563        cx: &mut ViewContext<Editor>,
2564    ) -> Self::PaintState {
2565        let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
2566        cx.scene().push_layer(Some(visible_bounds));
2567
2568        let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
2569        let text_bounds = RectF::new(
2570            bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
2571            layout.text_size,
2572        );
2573
2574        Self::attach_mouse_handlers(
2575            &layout.position_map,
2576            layout.hover_popovers.is_some(),
2577            visible_bounds,
2578            text_bounds,
2579            gutter_bounds,
2580            bounds,
2581            cx,
2582        );
2583
2584        self.paint_background(gutter_bounds, text_bounds, layout, cx);
2585        if layout.gutter_size.x() > 0. {
2586            self.paint_gutter(gutter_bounds, visible_bounds, layout, editor, cx);
2587        }
2588        self.paint_text(text_bounds, visible_bounds, layout, editor, cx);
2589
2590        cx.scene().push_layer(Some(bounds));
2591        if !layout.blocks.is_empty() {
2592            self.paint_blocks(bounds, visible_bounds, layout, editor, cx);
2593        }
2594        self.paint_scrollbar(bounds, layout, &editor, cx);
2595        cx.scene().pop_layer();
2596        cx.scene().pop_layer();
2597    }
2598
2599    fn rect_for_text_range(
2600        &self,
2601        range_utf16: Range<usize>,
2602        bounds: RectF,
2603        _: RectF,
2604        layout: &Self::LayoutState,
2605        _: &Self::PaintState,
2606        _: &Editor,
2607        _: &ViewContext<Editor>,
2608    ) -> Option<RectF> {
2609        let text_bounds = RectF::new(
2610            bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
2611            layout.text_size,
2612        );
2613        let content_origin = text_bounds.origin() + vec2f(layout.gutter_margin, 0.);
2614        let scroll_position = layout.position_map.snapshot.scroll_position();
2615        let start_row = scroll_position.y() as u32;
2616        let scroll_top = scroll_position.y() * layout.position_map.line_height;
2617        let scroll_left = scroll_position.x() * layout.position_map.em_width;
2618
2619        let range_start = OffsetUtf16(range_utf16.start)
2620            .to_display_point(&layout.position_map.snapshot.display_snapshot);
2621        if range_start.row() < start_row {
2622            return None;
2623        }
2624
2625        let line = &layout
2626            .position_map
2627            .line_layouts
2628            .get((range_start.row() - start_row) as usize)?
2629            .line;
2630        let range_start_x = line.x_for_index(range_start.column() as usize);
2631        let range_start_y = range_start.row() as f32 * layout.position_map.line_height;
2632        Some(RectF::new(
2633            content_origin
2634                + vec2f(
2635                    range_start_x,
2636                    range_start_y + layout.position_map.line_height,
2637                )
2638                - vec2f(scroll_left, scroll_top),
2639            vec2f(
2640                layout.position_map.em_width,
2641                layout.position_map.line_height,
2642            ),
2643        ))
2644    }
2645
2646    fn debug(
2647        &self,
2648        bounds: RectF,
2649        _: &Self::LayoutState,
2650        _: &Self::PaintState,
2651        _: &Editor,
2652        _: &ViewContext<Editor>,
2653    ) -> json::Value {
2654        json!({
2655            "type": "BufferElement",
2656            "bounds": bounds.to_json()
2657        })
2658    }
2659}
2660
2661type BufferRow = u32;
2662
2663pub struct LayoutState {
2664    position_map: Arc<PositionMap>,
2665    gutter_size: Vector2F,
2666    gutter_padding: f32,
2667    gutter_margin: f32,
2668    text_size: Vector2F,
2669    mode: EditorMode,
2670    wrap_guides: SmallVec<[(f32, bool); 2]>,
2671    visible_display_row_range: Range<u32>,
2672    active_rows: BTreeMap<u32, bool>,
2673    highlighted_rows: Option<Range<u32>>,
2674    line_number_layouts: Vec<Option<text_layout::Line>>,
2675    display_hunks: Vec<DisplayDiffHunk>,
2676    blocks: Vec<BlockLayout>,
2677    highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
2678    fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)>,
2679    selections: Vec<(SelectionStyle, Vec<SelectionLayout>)>,
2680    scrollbar_row_range: Range<f32>,
2681    show_scrollbars: bool,
2682    is_singleton: bool,
2683    max_row: u32,
2684    context_menu: Option<(DisplayPoint, AnyElement<Editor>)>,
2685    code_actions_indicator: Option<(u32, AnyElement<Editor>)>,
2686    hover_popovers: Option<(DisplayPoint, Vec<AnyElement<Editor>>)>,
2687    fold_indicators: Vec<Option<AnyElement<Editor>>>,
2688    tab_invisible: Line,
2689    space_invisible: Line,
2690}
2691
2692struct PositionMap {
2693    size: Vector2F,
2694    line_height: f32,
2695    scroll_max: Vector2F,
2696    em_width: f32,
2697    em_advance: f32,
2698    line_layouts: Vec<LineWithInvisibles>,
2699    snapshot: EditorSnapshot,
2700}
2701
2702#[derive(Debug, Copy, Clone)]
2703pub struct PointForPosition {
2704    pub previous_valid: DisplayPoint,
2705    pub next_valid: DisplayPoint,
2706    pub exact_unclipped: DisplayPoint,
2707    pub column_overshoot_after_line_end: u32,
2708}
2709
2710impl PointForPosition {
2711    #[cfg(test)]
2712    pub fn valid(valid: DisplayPoint) -> Self {
2713        Self {
2714            previous_valid: valid,
2715            next_valid: valid,
2716            exact_unclipped: valid,
2717            column_overshoot_after_line_end: 0,
2718        }
2719    }
2720
2721    pub fn as_valid(&self) -> Option<DisplayPoint> {
2722        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
2723            Some(self.previous_valid)
2724        } else {
2725            None
2726        }
2727    }
2728}
2729
2730impl PositionMap {
2731    fn point_for_position(&self, text_bounds: RectF, position: Vector2F) -> PointForPosition {
2732        let scroll_position = self.snapshot.scroll_position();
2733        let position = position - text_bounds.origin();
2734        let y = position.y().max(0.0).min(self.size.y());
2735        let x = position.x() + (scroll_position.x() * self.em_width);
2736        let row = (y / self.line_height + scroll_position.y()) as u32;
2737        let (column, x_overshoot_after_line_end) = if let Some(line) = self
2738            .line_layouts
2739            .get(row as usize - scroll_position.y() as usize)
2740            .map(|line_with_spaces| &line_with_spaces.line)
2741        {
2742            if let Some(ix) = line.index_for_x(x) {
2743                (ix as u32, 0.0)
2744            } else {
2745                (line.len() as u32, 0f32.max(x - line.width()))
2746            }
2747        } else {
2748            (0, x)
2749        };
2750
2751        let mut exact_unclipped = DisplayPoint::new(row, column);
2752        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
2753        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
2754
2755        let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
2756        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
2757        PointForPosition {
2758            previous_valid,
2759            next_valid,
2760            exact_unclipped,
2761            column_overshoot_after_line_end,
2762        }
2763    }
2764}
2765
2766struct BlockLayout {
2767    row: u32,
2768    element: AnyElement<Editor>,
2769    style: BlockStyle,
2770}
2771
2772fn layout_line(
2773    row: u32,
2774    snapshot: &EditorSnapshot,
2775    style: &EditorStyle,
2776    layout_cache: &TextLayoutCache,
2777) -> text_layout::Line {
2778    let mut line = snapshot.line(row);
2779
2780    if line.len() > MAX_LINE_LEN {
2781        let mut len = MAX_LINE_LEN;
2782        while !line.is_char_boundary(len) {
2783            len -= 1;
2784        }
2785
2786        line.truncate(len);
2787    }
2788
2789    layout_cache.layout_str(
2790        &line,
2791        style.text.font_size,
2792        &[(
2793            snapshot.line_len(row) as usize,
2794            RunStyle {
2795                font_id: style.text.font_id,
2796                color: Color::black(),
2797                underline: Default::default(),
2798            },
2799        )],
2800    )
2801}
2802
2803#[derive(Debug)]
2804pub struct Cursor {
2805    origin: Vector2F,
2806    block_width: f32,
2807    line_height: f32,
2808    color: Color,
2809    shape: CursorShape,
2810    block_text: Option<Line>,
2811}
2812
2813impl Cursor {
2814    pub fn new(
2815        origin: Vector2F,
2816        block_width: f32,
2817        line_height: f32,
2818        color: Color,
2819        shape: CursorShape,
2820        block_text: Option<Line>,
2821    ) -> Cursor {
2822        Cursor {
2823            origin,
2824            block_width,
2825            line_height,
2826            color,
2827            shape,
2828            block_text,
2829        }
2830    }
2831
2832    pub fn bounding_rect(&self, origin: Vector2F) -> RectF {
2833        RectF::new(
2834            self.origin + origin,
2835            vec2f(self.block_width, self.line_height),
2836        )
2837    }
2838
2839    pub fn paint(&self, origin: Vector2F, cx: &mut WindowContext) {
2840        let bounds = match self.shape {
2841            CursorShape::Bar => RectF::new(self.origin + origin, vec2f(2.0, self.line_height)),
2842            CursorShape::Block | CursorShape::Hollow => RectF::new(
2843                self.origin + origin,
2844                vec2f(self.block_width, self.line_height),
2845            ),
2846            CursorShape::Underscore => RectF::new(
2847                self.origin + origin + Vector2F::new(0.0, self.line_height - 2.0),
2848                vec2f(self.block_width, 2.0),
2849            ),
2850        };
2851
2852        //Draw background or border quad
2853        if matches!(self.shape, CursorShape::Hollow) {
2854            cx.scene().push_quad(Quad {
2855                bounds,
2856                background: None,
2857                border: Border::all(1., self.color).into(),
2858                corner_radii: Default::default(),
2859            });
2860        } else {
2861            cx.scene().push_quad(Quad {
2862                bounds,
2863                background: Some(self.color),
2864                border: Default::default(),
2865                corner_radii: Default::default(),
2866            });
2867        }
2868
2869        if let Some(block_text) = &self.block_text {
2870            block_text.paint(self.origin + origin, bounds, self.line_height, cx);
2871        }
2872    }
2873
2874    pub fn shape(&self) -> CursorShape {
2875        self.shape
2876    }
2877}
2878
2879#[derive(Debug)]
2880pub struct HighlightedRange {
2881    pub start_y: f32,
2882    pub line_height: f32,
2883    pub lines: Vec<HighlightedRangeLine>,
2884    pub color: Color,
2885    pub corner_radius: f32,
2886}
2887
2888#[derive(Debug)]
2889pub struct HighlightedRangeLine {
2890    pub start_x: f32,
2891    pub end_x: f32,
2892}
2893
2894impl HighlightedRange {
2895    pub fn paint(&self, bounds: RectF, cx: &mut WindowContext) {
2896        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
2897            self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
2898            self.paint_lines(
2899                self.start_y + self.line_height,
2900                &self.lines[1..],
2901                bounds,
2902                cx,
2903            );
2904        } else {
2905            self.paint_lines(self.start_y, &self.lines, bounds, cx);
2906        }
2907    }
2908
2909    fn paint_lines(
2910        &self,
2911        start_y: f32,
2912        lines: &[HighlightedRangeLine],
2913        bounds: RectF,
2914        cx: &mut WindowContext,
2915    ) {
2916        if lines.is_empty() {
2917            return;
2918        }
2919
2920        let mut path = PathBuilder::new();
2921        let first_line = lines.first().unwrap();
2922        let last_line = lines.last().unwrap();
2923
2924        let first_top_left = vec2f(first_line.start_x, start_y);
2925        let first_top_right = vec2f(first_line.end_x, start_y);
2926
2927        let curve_height = vec2f(0., self.corner_radius);
2928        let curve_width = |start_x: f32, end_x: f32| {
2929            let max = (end_x - start_x) / 2.;
2930            let width = if max < self.corner_radius {
2931                max
2932            } else {
2933                self.corner_radius
2934            };
2935
2936            vec2f(width, 0.)
2937        };
2938
2939        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
2940        path.reset(first_top_right - top_curve_width);
2941        path.curve_to(first_top_right + curve_height, first_top_right);
2942
2943        let mut iter = lines.iter().enumerate().peekable();
2944        while let Some((ix, line)) = iter.next() {
2945            let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
2946
2947            if let Some((_, next_line)) = iter.peek() {
2948                let next_top_right = vec2f(next_line.end_x, bottom_right.y());
2949
2950                match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
2951                    Ordering::Equal => {
2952                        path.line_to(bottom_right);
2953                    }
2954                    Ordering::Less => {
2955                        let curve_width = curve_width(next_top_right.x(), bottom_right.x());
2956                        path.line_to(bottom_right - curve_height);
2957                        if self.corner_radius > 0. {
2958                            path.curve_to(bottom_right - curve_width, bottom_right);
2959                        }
2960                        path.line_to(next_top_right + curve_width);
2961                        if self.corner_radius > 0. {
2962                            path.curve_to(next_top_right + curve_height, next_top_right);
2963                        }
2964                    }
2965                    Ordering::Greater => {
2966                        let curve_width = curve_width(bottom_right.x(), next_top_right.x());
2967                        path.line_to(bottom_right - curve_height);
2968                        if self.corner_radius > 0. {
2969                            path.curve_to(bottom_right + curve_width, bottom_right);
2970                        }
2971                        path.line_to(next_top_right - curve_width);
2972                        if self.corner_radius > 0. {
2973                            path.curve_to(next_top_right + curve_height, next_top_right);
2974                        }
2975                    }
2976                }
2977            } else {
2978                let curve_width = curve_width(line.start_x, line.end_x);
2979                path.line_to(bottom_right - curve_height);
2980                if self.corner_radius > 0. {
2981                    path.curve_to(bottom_right - curve_width, bottom_right);
2982                }
2983
2984                let bottom_left = vec2f(line.start_x, bottom_right.y());
2985                path.line_to(bottom_left + curve_width);
2986                if self.corner_radius > 0. {
2987                    path.curve_to(bottom_left - curve_height, bottom_left);
2988                }
2989            }
2990        }
2991
2992        if first_line.start_x > last_line.start_x {
2993            let curve_width = curve_width(last_line.start_x, first_line.start_x);
2994            let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
2995            path.line_to(second_top_left + curve_height);
2996            if self.corner_radius > 0. {
2997                path.curve_to(second_top_left + curve_width, second_top_left);
2998            }
2999            let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
3000            path.line_to(first_bottom_left - curve_width);
3001            if self.corner_radius > 0. {
3002                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
3003            }
3004        }
3005
3006        path.line_to(first_top_left + curve_height);
3007        if self.corner_radius > 0. {
3008            path.curve_to(first_top_left + top_curve_width, first_top_left);
3009        }
3010        path.line_to(first_top_right - top_curve_width);
3011
3012        cx.scene().push_path(path.build(self.color, Some(bounds)));
3013    }
3014}
3015
3016fn range_to_bounds(
3017    range: &Range<DisplayPoint>,
3018    content_origin: Vector2F,
3019    scroll_left: f32,
3020    scroll_top: f32,
3021    visible_row_range: &Range<u32>,
3022    line_end_overshoot: f32,
3023    position_map: &PositionMap,
3024) -> impl Iterator<Item = RectF> {
3025    let mut bounds: SmallVec<[RectF; 1]> = SmallVec::new();
3026
3027    if range.start == range.end {
3028        return bounds.into_iter();
3029    }
3030
3031    let start_row = visible_row_range.start;
3032    let end_row = visible_row_range.end;
3033
3034    let row_range = if range.end.column() == 0 {
3035        cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
3036    } else {
3037        cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
3038    };
3039
3040    let first_y =
3041        content_origin.y() + row_range.start as f32 * position_map.line_height - scroll_top;
3042
3043    for (idx, row) in row_range.enumerate() {
3044        let line_layout = &position_map.line_layouts[(row - start_row) as usize].line;
3045
3046        let start_x = if row == range.start.row() {
3047            content_origin.x() + line_layout.x_for_index(range.start.column() as usize)
3048                - scroll_left
3049        } else {
3050            content_origin.x() - scroll_left
3051        };
3052
3053        let end_x = if row == range.end.row() {
3054            content_origin.x() + line_layout.x_for_index(range.end.column() as usize) - scroll_left
3055        } else {
3056            content_origin.x() + line_layout.width() + line_end_overshoot - scroll_left
3057        };
3058
3059        bounds.push(RectF::from_points(
3060            vec2f(start_x, first_y + position_map.line_height * idx as f32),
3061            vec2f(end_x, first_y + position_map.line_height * (idx + 1) as f32),
3062        ))
3063    }
3064
3065    bounds.into_iter()
3066}
3067
3068pub fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
3069    delta.powf(1.5) / 100.0
3070}
3071
3072fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
3073    delta.powf(1.2) / 300.0
3074}
3075
3076#[cfg(test)]
3077mod tests {
3078    use super::*;
3079    use crate::{
3080        display_map::{BlockDisposition, BlockProperties},
3081        editor_tests::{init_test, update_test_language_settings},
3082        Editor, MultiBuffer,
3083    };
3084    use gpui::TestAppContext;
3085    use language::language_settings;
3086    use log::info;
3087    use std::{num::NonZeroU32, sync::Arc};
3088    use util::test::sample_text;
3089
3090    #[gpui::test]
3091    fn test_layout_line_numbers(cx: &mut TestAppContext) {
3092        init_test(cx, |_| {});
3093        let editor = cx
3094            .add_window(|cx| {
3095                let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
3096                Editor::new(EditorMode::Full, buffer, None, None, cx)
3097            })
3098            .root(cx);
3099        let element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3100
3101        let layouts = editor.update(cx, |editor, cx| {
3102            let snapshot = editor.snapshot(cx);
3103            element
3104                .layout_line_numbers(
3105                    0..6,
3106                    &Default::default(),
3107                    DisplayPoint::new(0, 0),
3108                    false,
3109                    &snapshot,
3110                    cx,
3111                )
3112                .0
3113        });
3114        assert_eq!(layouts.len(), 6);
3115
3116        let relative_rows = editor.update(cx, |editor, cx| {
3117            let snapshot = editor.snapshot(cx);
3118            element.calculate_relative_line_numbers(&snapshot, &(0..6), Some(3))
3119        });
3120        assert_eq!(relative_rows[&0], 3);
3121        assert_eq!(relative_rows[&1], 2);
3122        assert_eq!(relative_rows[&2], 1);
3123        // current line has no relative number
3124        assert_eq!(relative_rows[&4], 1);
3125        assert_eq!(relative_rows[&5], 2);
3126
3127        // works if cursor is before screen
3128        let relative_rows = editor.update(cx, |editor, cx| {
3129            let snapshot = editor.snapshot(cx);
3130
3131            element.calculate_relative_line_numbers(&snapshot, &(3..6), Some(1))
3132        });
3133        assert_eq!(relative_rows.len(), 3);
3134        assert_eq!(relative_rows[&3], 2);
3135        assert_eq!(relative_rows[&4], 3);
3136        assert_eq!(relative_rows[&5], 4);
3137
3138        // works if cursor is after screen
3139        let relative_rows = editor.update(cx, |editor, cx| {
3140            let snapshot = editor.snapshot(cx);
3141
3142            element.calculate_relative_line_numbers(&snapshot, &(0..3), Some(6))
3143        });
3144        assert_eq!(relative_rows.len(), 3);
3145        assert_eq!(relative_rows[&0], 5);
3146        assert_eq!(relative_rows[&1], 4);
3147        assert_eq!(relative_rows[&2], 3);
3148    }
3149
3150    #[gpui::test]
3151    async fn test_vim_visual_selections(cx: &mut TestAppContext) {
3152        init_test(cx, |_| {});
3153
3154        let editor = cx
3155            .add_window(|cx| {
3156                let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
3157                Editor::new(EditorMode::Full, buffer, None, None, cx)
3158            })
3159            .root(cx);
3160        let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3161        let (_, state) = editor.update(cx, |editor, cx| {
3162            editor.cursor_shape = CursorShape::Block;
3163            editor.change_selections(None, cx, |s| {
3164                s.select_ranges([
3165                    Point::new(0, 0)..Point::new(1, 0),
3166                    Point::new(3, 2)..Point::new(3, 3),
3167                    Point::new(5, 6)..Point::new(6, 0),
3168                ]);
3169            });
3170            element.layout(
3171                SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
3172                editor,
3173                cx,
3174            )
3175        });
3176        assert_eq!(state.selections.len(), 1);
3177        let local_selections = &state.selections[0].1;
3178        assert_eq!(local_selections.len(), 3);
3179        // moves cursor back one line
3180        assert_eq!(local_selections[0].head, DisplayPoint::new(0, 6));
3181        assert_eq!(
3182            local_selections[0].range,
3183            DisplayPoint::new(0, 0)..DisplayPoint::new(1, 0)
3184        );
3185
3186        // moves cursor back one column
3187        assert_eq!(
3188            local_selections[1].range,
3189            DisplayPoint::new(3, 2)..DisplayPoint::new(3, 3)
3190        );
3191        assert_eq!(local_selections[1].head, DisplayPoint::new(3, 2));
3192
3193        // leaves cursor on the max point
3194        assert_eq!(
3195            local_selections[2].range,
3196            DisplayPoint::new(5, 6)..DisplayPoint::new(6, 0)
3197        );
3198        assert_eq!(local_selections[2].head, DisplayPoint::new(6, 0));
3199
3200        // active lines does not include 1 (even though the range of the selection does)
3201        assert_eq!(
3202            state.active_rows.keys().cloned().collect::<Vec<u32>>(),
3203            vec![0, 3, 5, 6]
3204        );
3205
3206        // multi-buffer support
3207        // in DisplayPoint co-ordinates, this is what we're dealing with:
3208        //  0: [[file
3209        //  1:   header]]
3210        //  2: aaaaaa
3211        //  3: bbbbbb
3212        //  4: cccccc
3213        //  5:
3214        //  6: ...
3215        //  7: ffffff
3216        //  8: gggggg
3217        //  9: hhhhhh
3218        // 10:
3219        // 11: [[file
3220        // 12:   header]]
3221        // 13: bbbbbb
3222        // 14: cccccc
3223        // 15: dddddd
3224        let editor = cx
3225            .add_window(|cx| {
3226                let buffer = MultiBuffer::build_multi(
3227                    [
3228                        (
3229                            &(sample_text(8, 6, 'a') + "\n"),
3230                            vec![
3231                                Point::new(0, 0)..Point::new(3, 0),
3232                                Point::new(4, 0)..Point::new(7, 0),
3233                            ],
3234                        ),
3235                        (
3236                            &(sample_text(8, 6, 'a') + "\n"),
3237                            vec![Point::new(1, 0)..Point::new(3, 0)],
3238                        ),
3239                    ],
3240                    cx,
3241                );
3242                Editor::new(EditorMode::Full, buffer, None, None, cx)
3243            })
3244            .root(cx);
3245        let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3246        let (_, state) = editor.update(cx, |editor, cx| {
3247            editor.cursor_shape = CursorShape::Block;
3248            editor.change_selections(None, cx, |s| {
3249                s.select_display_ranges([
3250                    DisplayPoint::new(4, 0)..DisplayPoint::new(7, 0),
3251                    DisplayPoint::new(10, 0)..DisplayPoint::new(13, 0),
3252                ]);
3253            });
3254            element.layout(
3255                SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
3256                editor,
3257                cx,
3258            )
3259        });
3260
3261        assert_eq!(state.selections.len(), 1);
3262        let local_selections = &state.selections[0].1;
3263        assert_eq!(local_selections.len(), 2);
3264
3265        // moves cursor on excerpt boundary back a line
3266        // and doesn't allow selection to bleed through
3267        assert_eq!(
3268            local_selections[0].range,
3269            DisplayPoint::new(4, 0)..DisplayPoint::new(6, 0)
3270        );
3271        assert_eq!(local_selections[0].head, DisplayPoint::new(5, 0));
3272
3273        // moves cursor on buffer boundary back two lines
3274        // and doesn't allow selection to bleed through
3275        assert_eq!(
3276            local_selections[1].range,
3277            DisplayPoint::new(10, 0)..DisplayPoint::new(11, 0)
3278        );
3279        assert_eq!(local_selections[1].head, DisplayPoint::new(10, 0));
3280    }
3281
3282    #[gpui::test]
3283    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
3284        init_test(cx, |_| {});
3285
3286        let editor = cx
3287            .add_window(|cx| {
3288                let buffer = MultiBuffer::build_simple("", cx);
3289                Editor::new(EditorMode::Full, buffer, None, None, cx)
3290            })
3291            .root(cx);
3292
3293        editor.update(cx, |editor, cx| {
3294            editor.set_placeholder_text("hello", cx);
3295            editor.insert_blocks(
3296                [BlockProperties {
3297                    style: BlockStyle::Fixed,
3298                    disposition: BlockDisposition::Above,
3299                    height: 3,
3300                    position: Anchor::min(),
3301                    render: Arc::new(|_| Empty::new().into_any()),
3302                }],
3303                None,
3304                cx,
3305            );
3306
3307            // Blur the editor so that it displays placeholder text.
3308            cx.blur();
3309        });
3310
3311        let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3312        let (size, mut state) = editor.update(cx, |editor, cx| {
3313            element.layout(
3314                SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
3315                editor,
3316                cx,
3317            )
3318        });
3319
3320        assert_eq!(state.position_map.line_layouts.len(), 4);
3321        assert_eq!(
3322            state
3323                .line_number_layouts
3324                .iter()
3325                .map(Option::is_some)
3326                .collect::<Vec<_>>(),
3327            &[false, false, false, true]
3328        );
3329
3330        // Don't panic.
3331        let bounds = RectF::new(Default::default(), size);
3332        editor.update(cx, |editor, cx| {
3333            element.paint(bounds, bounds, &mut state, editor, cx);
3334        });
3335    }
3336
3337    #[gpui::test]
3338    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
3339        const TAB_SIZE: u32 = 4;
3340
3341        let input_text = "\t \t|\t| a b";
3342        let expected_invisibles = vec![
3343            Invisible::Tab {
3344                line_start_offset: 0,
3345            },
3346            Invisible::Whitespace {
3347                line_offset: TAB_SIZE as usize,
3348            },
3349            Invisible::Tab {
3350                line_start_offset: TAB_SIZE as usize + 1,
3351            },
3352            Invisible::Tab {
3353                line_start_offset: TAB_SIZE as usize * 2 + 1,
3354            },
3355            Invisible::Whitespace {
3356                line_offset: TAB_SIZE as usize * 3 + 1,
3357            },
3358            Invisible::Whitespace {
3359                line_offset: TAB_SIZE as usize * 3 + 3,
3360            },
3361        ];
3362        assert_eq!(
3363            expected_invisibles.len(),
3364            input_text
3365                .chars()
3366                .filter(|initial_char| initial_char.is_whitespace())
3367                .count(),
3368            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
3369        );
3370
3371        init_test(cx, |s| {
3372            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3373            s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
3374        });
3375
3376        let actual_invisibles =
3377            collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, 500.0);
3378
3379        assert_eq!(expected_invisibles, actual_invisibles);
3380    }
3381
3382    #[gpui::test]
3383    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
3384        init_test(cx, |s| {
3385            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3386            s.defaults.tab_size = NonZeroU32::new(4);
3387        });
3388
3389        for editor_mode_without_invisibles in [
3390            EditorMode::SingleLine,
3391            EditorMode::AutoHeight { max_lines: 100 },
3392        ] {
3393            let invisibles = collect_invisibles_from_new_editor(
3394                cx,
3395                editor_mode_without_invisibles,
3396                "\t\t\t| | a b",
3397                500.0,
3398            );
3399            assert!(invisibles.is_empty(),
3400                "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
3401        }
3402    }
3403
3404    #[gpui::test]
3405    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
3406        let tab_size = 4;
3407        let input_text = "a\tbcd   ".repeat(9);
3408        let repeated_invisibles = [
3409            Invisible::Tab {
3410                line_start_offset: 1,
3411            },
3412            Invisible::Whitespace {
3413                line_offset: tab_size as usize + 3,
3414            },
3415            Invisible::Whitespace {
3416                line_offset: tab_size as usize + 4,
3417            },
3418            Invisible::Whitespace {
3419                line_offset: tab_size as usize + 5,
3420            },
3421        ];
3422        let expected_invisibles = std::iter::once(repeated_invisibles)
3423            .cycle()
3424            .take(9)
3425            .flatten()
3426            .collect::<Vec<_>>();
3427        assert_eq!(
3428            expected_invisibles.len(),
3429            input_text
3430                .chars()
3431                .filter(|initial_char| initial_char.is_whitespace())
3432                .count(),
3433            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
3434        );
3435        info!("Expected invisibles: {expected_invisibles:?}");
3436
3437        init_test(cx, |_| {});
3438
3439        // Put the same string with repeating whitespace pattern into editors of various size,
3440        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
3441        let resize_step = 10.0;
3442        let mut editor_width = 200.0;
3443        while editor_width <= 1000.0 {
3444            update_test_language_settings(cx, |s| {
3445                s.defaults.tab_size = NonZeroU32::new(tab_size);
3446                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3447                s.defaults.preferred_line_length = Some(editor_width as u32);
3448                s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
3449            });
3450
3451            let actual_invisibles =
3452                collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, editor_width);
3453
3454            // Whatever the editor size is, ensure it has the same invisible kinds in the same order
3455            // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
3456            let mut i = 0;
3457            for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
3458                i = actual_index;
3459                match expected_invisibles.get(i) {
3460                    Some(expected_invisible) => match (expected_invisible, actual_invisible) {
3461                        (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
3462                        | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
3463                        _ => {
3464                            panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
3465                        }
3466                    },
3467                    None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
3468                }
3469            }
3470            let missing_expected_invisibles = &expected_invisibles[i + 1..];
3471            assert!(
3472                missing_expected_invisibles.is_empty(),
3473                "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
3474            );
3475
3476            editor_width += resize_step;
3477        }
3478    }
3479
3480    fn collect_invisibles_from_new_editor(
3481        cx: &mut TestAppContext,
3482        editor_mode: EditorMode,
3483        input_text: &str,
3484        editor_width: f32,
3485    ) -> Vec<Invisible> {
3486        info!(
3487            "Creating editor with mode {editor_mode:?}, width {editor_width} and text '{input_text}'"
3488        );
3489        let editor = cx
3490            .add_window(|cx| {
3491                let buffer = MultiBuffer::build_simple(&input_text, cx);
3492                Editor::new(editor_mode, buffer, None, None, cx)
3493            })
3494            .root(cx);
3495
3496        let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3497        let (_, layout_state) = editor.update(cx, |editor, cx| {
3498            editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
3499            editor.set_wrap_width(Some(editor_width), cx);
3500
3501            element.layout(
3502                SizeConstraint::new(vec2f(editor_width, 500.), vec2f(editor_width, 500.)),
3503                editor,
3504                cx,
3505            )
3506        });
3507
3508        layout_state
3509            .position_map
3510            .line_layouts
3511            .iter()
3512            .map(|line_with_invisibles| &line_with_invisibles.invisibles)
3513            .flatten()
3514            .cloned()
3515            .collect()
3516    }
3517}