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