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