element.rs

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