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 selection_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
 788
 789        for (replica_id, selections) in &layout.selections {
 790            let selection_style = style.replica_selection_style(*replica_id);
 791
 792            for selection in selections {
 793                if !selection.range.is_empty() {
 794                    selection_ranges.push(selection.range.clone());
 795                }
 796                self.paint_highlighted_range(
 797                    scene,
 798                    selection.range.clone(),
 799                    selection_style.selection,
 800                    corner_radius,
 801                    corner_radius * 2.,
 802                    layout,
 803                    content_origin,
 804                    scroll_top,
 805                    scroll_left,
 806                    bounds,
 807                );
 808
 809                if editor.show_local_cursors(cx) || *replica_id != local_replica_id {
 810                    let cursor_position = selection.head;
 811                    if layout
 812                        .visible_display_row_range
 813                        .contains(&cursor_position.row())
 814                    {
 815                        let cursor_row_layout = &layout.position_map.line_layouts
 816                            [(cursor_position.row() - start_row) as usize]
 817                            .line;
 818                        let cursor_column = cursor_position.column() as usize;
 819
 820                        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 821                        let mut block_width =
 822                            cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
 823                        if block_width == 0.0 {
 824                            block_width = layout.position_map.em_width;
 825                        }
 826                        let block_text = if let CursorShape::Block = selection.cursor_shape {
 827                            layout
 828                                .position_map
 829                                .snapshot
 830                                .chars_at(cursor_position)
 831                                .next()
 832                                .and_then(|(character, _)| {
 833                                    let font_id =
 834                                        cursor_row_layout.font_for_index(cursor_column)?;
 835                                    let text = character.to_string();
 836
 837                                    Some(cx.text_layout_cache().layout_str(
 838                                        &text,
 839                                        cursor_row_layout.font_size(),
 840                                        &[(
 841                                            text.len(),
 842                                            RunStyle {
 843                                                font_id,
 844                                                color: style.background,
 845                                                underline: Default::default(),
 846                                            },
 847                                        )],
 848                                    ))
 849                                })
 850                        } else {
 851                            None
 852                        };
 853
 854                        let x = cursor_character_x - scroll_left;
 855                        let y = cursor_position.row() as f32 * layout.position_map.line_height
 856                            - scroll_top;
 857                        cursors.push(Cursor {
 858                            color: selection_style.cursor,
 859                            block_width,
 860                            origin: vec2f(x, y),
 861                            line_height: layout.position_map.line_height,
 862                            shape: selection.cursor_shape,
 863                            block_text,
 864                        });
 865                    }
 866                }
 867            }
 868        }
 869
 870        if let Some(visible_text_bounds) = bounds.intersection(visible_bounds) {
 871            draw_line_glyphs(
 872                layout,
 873                start_row,
 874                scroll_top,
 875                scene,
 876                content_origin,
 877                scroll_left,
 878                visible_text_bounds,
 879                cx,
 880                selection_ranges,
 881                visible_bounds,
 882            );
 883        }
 884
 885        scene.paint_layer(Some(bounds), |scene| {
 886            for cursor in cursors {
 887                cursor.paint(scene, content_origin, cx);
 888            }
 889        });
 890
 891        if let Some((position, context_menu)) = layout.context_menu.as_mut() {
 892            scene.push_stacking_context(None, None);
 893            let cursor_row_layout =
 894                &layout.position_map.line_layouts[(position.row() - start_row) as usize].line;
 895            let x = cursor_row_layout.x_for_index(position.column() as usize) - scroll_left;
 896            let y = (position.row() + 1) as f32 * layout.position_map.line_height - scroll_top;
 897            let mut list_origin = content_origin + vec2f(x, y);
 898            let list_width = context_menu.size().x();
 899            let list_height = context_menu.size().y();
 900
 901            // Snap the right edge of the list to the right edge of the window if
 902            // its horizontal bounds overflow.
 903            if list_origin.x() + list_width > cx.window_size().x() {
 904                list_origin.set_x((cx.window_size().x() - list_width).max(0.));
 905            }
 906
 907            if list_origin.y() + list_height > bounds.max_y() {
 908                list_origin.set_y(list_origin.y() - layout.position_map.line_height - list_height);
 909            }
 910
 911            context_menu.paint(
 912                scene,
 913                list_origin,
 914                RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
 915                editor,
 916                cx,
 917            );
 918
 919            scene.pop_stacking_context();
 920        }
 921
 922        if let Some((position, hover_popovers)) = layout.hover_popovers.as_mut() {
 923            scene.push_stacking_context(None, None);
 924
 925            // This is safe because we check on layout whether the required row is available
 926            let hovered_row_layout =
 927                &layout.position_map.line_layouts[(position.row() - start_row) as usize].line;
 928
 929            // Minimum required size: Take the first popover, and add 1.5 times the minimum popover
 930            // height. This is the size we will use to decide whether to render popovers above or below
 931            // the hovered line.
 932            let first_size = hover_popovers[0].size();
 933            let height_to_reserve = first_size.y()
 934                + 1.5 * MIN_POPOVER_LINE_HEIGHT as f32 * layout.position_map.line_height;
 935
 936            // Compute Hovered Point
 937            let x = hovered_row_layout.x_for_index(position.column() as usize) - scroll_left;
 938            let y = position.row() as f32 * layout.position_map.line_height - scroll_top;
 939            let hovered_point = content_origin + vec2f(x, y);
 940
 941            if hovered_point.y() - height_to_reserve > 0.0 {
 942                // There is enough space above. Render popovers above the hovered point
 943                let mut current_y = hovered_point.y();
 944                for hover_popover in hover_popovers {
 945                    let size = hover_popover.size();
 946                    let mut popover_origin = vec2f(hovered_point.x(), current_y - size.y());
 947
 948                    let x_out_of_bounds = bounds.max_x() - (popover_origin.x() + size.x());
 949                    if x_out_of_bounds < 0.0 {
 950                        popover_origin.set_x(popover_origin.x() + x_out_of_bounds);
 951                    }
 952
 953                    hover_popover.paint(
 954                        scene,
 955                        popover_origin,
 956                        RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
 957                        editor,
 958                        cx,
 959                    );
 960
 961                    current_y = popover_origin.y() - HOVER_POPOVER_GAP;
 962                }
 963            } else {
 964                // There is not enough space above. Render popovers below the hovered point
 965                let mut current_y = hovered_point.y() + layout.position_map.line_height;
 966                for hover_popover in hover_popovers {
 967                    let size = hover_popover.size();
 968                    let mut popover_origin = vec2f(hovered_point.x(), current_y);
 969
 970                    let x_out_of_bounds = bounds.max_x() - (popover_origin.x() + size.x());
 971                    if x_out_of_bounds < 0.0 {
 972                        popover_origin.set_x(popover_origin.x() + x_out_of_bounds);
 973                    }
 974
 975                    hover_popover.paint(
 976                        scene,
 977                        popover_origin,
 978                        RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
 979                        editor,
 980                        cx,
 981                    );
 982
 983                    current_y = popover_origin.y() + size.y() + HOVER_POPOVER_GAP;
 984                }
 985            }
 986
 987            scene.pop_stacking_context();
 988        }
 989
 990        scene.pop_layer();
 991    }
 992
 993    fn paint_scrollbar(
 994        &mut self,
 995        scene: &mut SceneBuilder,
 996        bounds: RectF,
 997        layout: &mut LayoutState,
 998        cx: &mut ViewContext<Editor>,
 999    ) {
1000        enum ScrollbarMouseHandlers {}
1001        if layout.mode != EditorMode::Full {
1002            return;
1003        }
1004
1005        let style = &self.style.theme.scrollbar;
1006
1007        let top = bounds.min_y();
1008        let bottom = bounds.max_y();
1009        let right = bounds.max_x();
1010        let left = right - style.width;
1011        let row_range = &layout.scrollbar_row_range;
1012        let max_row = layout.max_row as f32 + (row_range.end - row_range.start);
1013
1014        let mut height = bounds.height();
1015        let mut first_row_y_offset = 0.0;
1016
1017        // Impose a minimum height on the scrollbar thumb
1018        let min_thumb_height =
1019            style.min_height_factor * cx.font_cache.line_height(self.style.text.font_size);
1020        let thumb_height = (row_range.end - row_range.start) * height / max_row;
1021        if thumb_height < min_thumb_height {
1022            first_row_y_offset = (min_thumb_height - thumb_height) / 2.0;
1023            height -= min_thumb_height - thumb_height;
1024        }
1025
1026        let y_for_row = |row: f32| -> f32 { top + first_row_y_offset + row * height / max_row };
1027
1028        let thumb_top = y_for_row(row_range.start) - first_row_y_offset;
1029        let thumb_bottom = y_for_row(row_range.end) + first_row_y_offset;
1030        let track_bounds = RectF::from_points(vec2f(left, top), vec2f(right, bottom));
1031        let thumb_bounds = RectF::from_points(vec2f(left, thumb_top), vec2f(right, thumb_bottom));
1032
1033        if layout.show_scrollbars {
1034            scene.push_quad(Quad {
1035                bounds: track_bounds,
1036                border: style.track.border,
1037                background: style.track.background_color,
1038                ..Default::default()
1039            });
1040            scene.push_quad(Quad {
1041                bounds: thumb_bounds,
1042                border: style.thumb.border,
1043                background: style.thumb.background_color,
1044                corner_radius: style.thumb.corner_radius,
1045            });
1046        }
1047
1048        scene.push_cursor_region(CursorRegion {
1049            bounds: track_bounds,
1050            style: CursorStyle::Arrow,
1051        });
1052        scene.push_mouse_region(
1053            MouseRegion::new::<ScrollbarMouseHandlers>(cx.view_id(), cx.view_id(), track_bounds)
1054                .on_move(move |_, editor: &mut Editor, cx| {
1055                    editor.scroll_manager.show_scrollbar(cx);
1056                })
1057                .on_down(MouseButton::Left, {
1058                    let row_range = row_range.clone();
1059                    move |event, editor: &mut Editor, cx| {
1060                        let y = event.position.y();
1061                        if y < thumb_top || thumb_bottom < y {
1062                            let center_row = ((y - top) * max_row as f32 / height).round() as u32;
1063                            let top_row = center_row
1064                                .saturating_sub((row_range.end - row_range.start) as u32 / 2);
1065                            let mut position = editor.scroll_position(cx);
1066                            position.set_y(top_row as f32);
1067                            editor.set_scroll_position(position, cx);
1068                        } else {
1069                            editor.scroll_manager.show_scrollbar(cx);
1070                        }
1071                    }
1072                })
1073                .on_drag(MouseButton::Left, {
1074                    move |event, editor: &mut Editor, cx| {
1075                        let y = event.prev_mouse_position.y();
1076                        let new_y = event.position.y();
1077                        if thumb_top < y && y < thumb_bottom {
1078                            let mut position = editor.scroll_position(cx);
1079                            position.set_y(position.y() + (new_y - y) * (max_row as f32) / height);
1080                            if position.y() < 0.0 {
1081                                position.set_y(0.);
1082                            }
1083                            editor.set_scroll_position(position, cx);
1084                        }
1085                    }
1086                }),
1087        );
1088    }
1089
1090    #[allow(clippy::too_many_arguments)]
1091    fn paint_highlighted_range(
1092        &self,
1093        scene: &mut SceneBuilder,
1094        range: Range<DisplayPoint>,
1095        color: Color,
1096        corner_radius: f32,
1097        line_end_overshoot: f32,
1098        layout: &LayoutState,
1099        content_origin: Vector2F,
1100        scroll_top: f32,
1101        scroll_left: f32,
1102        bounds: RectF,
1103    ) {
1104        let start_row = layout.visible_display_row_range.start;
1105        let end_row = layout.visible_display_row_range.end;
1106        if range.start != range.end {
1107            let row_range = if range.end.column() == 0 {
1108                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
1109            } else {
1110                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
1111            };
1112
1113            let highlighted_range = HighlightedRange {
1114                color,
1115                line_height: layout.position_map.line_height,
1116                corner_radius,
1117                start_y: content_origin.y()
1118                    + row_range.start as f32 * layout.position_map.line_height
1119                    - scroll_top,
1120                lines: row_range
1121                    .into_iter()
1122                    .map(|row| {
1123                        let line_layout =
1124                            &layout.position_map.line_layouts[(row - start_row) as usize].line;
1125                        HighlightedRangeLine {
1126                            start_x: if row == range.start.row() {
1127                                content_origin.x()
1128                                    + line_layout.x_for_index(range.start.column() as usize)
1129                                    - scroll_left
1130                            } else {
1131                                content_origin.x() - scroll_left
1132                            },
1133                            end_x: if row == range.end.row() {
1134                                content_origin.x()
1135                                    + line_layout.x_for_index(range.end.column() as usize)
1136                                    - scroll_left
1137                            } else {
1138                                content_origin.x() + line_layout.width() + line_end_overshoot
1139                                    - scroll_left
1140                            },
1141                        }
1142                    })
1143                    .collect(),
1144            };
1145
1146            highlighted_range.paint(bounds, scene);
1147        }
1148    }
1149
1150    fn paint_blocks(
1151        &mut self,
1152        scene: &mut SceneBuilder,
1153        bounds: RectF,
1154        visible_bounds: RectF,
1155        layout: &mut LayoutState,
1156        editor: &mut Editor,
1157        cx: &mut ViewContext<Editor>,
1158    ) {
1159        let scroll_position = layout.position_map.snapshot.scroll_position();
1160        let scroll_left = scroll_position.x() * layout.position_map.em_width;
1161        let scroll_top = scroll_position.y() * layout.position_map.line_height;
1162
1163        for block in &mut layout.blocks {
1164            let mut origin = bounds.origin()
1165                + vec2f(
1166                    0.,
1167                    block.row as f32 * layout.position_map.line_height - scroll_top,
1168                );
1169            if !matches!(block.style, BlockStyle::Sticky) {
1170                origin += vec2f(-scroll_left, 0.);
1171            }
1172            block
1173                .element
1174                .paint(scene, origin, visible_bounds, editor, cx);
1175        }
1176    }
1177
1178    fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &ViewContext<Editor>) -> f32 {
1179        let digit_count = (snapshot.max_buffer_row() as f32).log10().floor() as usize + 1;
1180        let style = &self.style;
1181
1182        cx.text_layout_cache()
1183            .layout_str(
1184                "1".repeat(digit_count).as_str(),
1185                style.text.font_size,
1186                &[(
1187                    digit_count,
1188                    RunStyle {
1189                        font_id: style.text.font_id,
1190                        color: Color::black(),
1191                        underline: Default::default(),
1192                    },
1193                )],
1194            )
1195            .width()
1196    }
1197
1198    //Folds contained in a hunk are ignored apart from shrinking visual size
1199    //If a fold contains any hunks then that fold line is marked as modified
1200    fn layout_git_gutters(
1201        &self,
1202        display_rows: Range<u32>,
1203        snapshot: &EditorSnapshot,
1204    ) -> Vec<DisplayDiffHunk> {
1205        let buffer_snapshot = &snapshot.buffer_snapshot;
1206
1207        let buffer_start_row = DisplayPoint::new(display_rows.start, 0)
1208            .to_point(snapshot)
1209            .row;
1210        let buffer_end_row = DisplayPoint::new(display_rows.end, 0)
1211            .to_point(snapshot)
1212            .row;
1213
1214        buffer_snapshot
1215            .git_diff_hunks_in_range(buffer_start_row..buffer_end_row, false)
1216            .map(|hunk| diff_hunk_to_display(hunk, snapshot))
1217            .dedup()
1218            .collect()
1219    }
1220
1221    fn layout_line_numbers(
1222        &self,
1223        rows: Range<u32>,
1224        active_rows: &BTreeMap<u32, bool>,
1225        is_singleton: bool,
1226        snapshot: &EditorSnapshot,
1227        cx: &ViewContext<Editor>,
1228    ) -> (
1229        Vec<Option<text_layout::Line>>,
1230        Vec<Option<(FoldStatus, BufferRow, bool)>>,
1231    ) {
1232        let style = &self.style;
1233        let include_line_numbers = snapshot.mode == EditorMode::Full;
1234        let mut line_number_layouts = Vec::with_capacity(rows.len());
1235        let mut fold_statuses = Vec::with_capacity(rows.len());
1236        let mut line_number = String::new();
1237        for (ix, row) in snapshot
1238            .buffer_rows(rows.start)
1239            .take((rows.end - rows.start) as usize)
1240            .enumerate()
1241        {
1242            let display_row = rows.start + ix as u32;
1243            let (active, color) = if active_rows.contains_key(&display_row) {
1244                (true, style.line_number_active)
1245            } else {
1246                (false, style.line_number)
1247            };
1248            if let Some(buffer_row) = row {
1249                if include_line_numbers {
1250                    line_number.clear();
1251                    write!(&mut line_number, "{}", buffer_row + 1).unwrap();
1252                    line_number_layouts.push(Some(cx.text_layout_cache().layout_str(
1253                        &line_number,
1254                        style.text.font_size,
1255                        &[(
1256                            line_number.len(),
1257                            RunStyle {
1258                                font_id: style.text.font_id,
1259                                color,
1260                                underline: Default::default(),
1261                            },
1262                        )],
1263                    )));
1264                    fold_statuses.push(
1265                        is_singleton
1266                            .then(|| {
1267                                snapshot
1268                                    .fold_for_line(buffer_row)
1269                                    .map(|fold_status| (fold_status, buffer_row, active))
1270                            })
1271                            .flatten(),
1272                    )
1273                }
1274            } else {
1275                fold_statuses.push(None);
1276                line_number_layouts.push(None);
1277            }
1278        }
1279
1280        (line_number_layouts, fold_statuses)
1281    }
1282
1283    fn layout_lines(
1284        &mut self,
1285        rows: Range<u32>,
1286        line_number_layouts: &[Option<Line>],
1287        snapshot: &EditorSnapshot,
1288        cx: &ViewContext<Editor>,
1289    ) -> Vec<LineWithInvisibles> {
1290        if rows.start >= rows.end {
1291            return Vec::new();
1292        }
1293
1294        // When the editor is empty and unfocused, then show the placeholder.
1295        if snapshot.is_empty() {
1296            let placeholder_style = self
1297                .style
1298                .placeholder_text
1299                .as_ref()
1300                .unwrap_or(&self.style.text);
1301            let placeholder_text = snapshot.placeholder_text();
1302            let placeholder_lines = placeholder_text
1303                .as_ref()
1304                .map_or("", AsRef::as_ref)
1305                .split('\n')
1306                .skip(rows.start as usize)
1307                .chain(iter::repeat(""))
1308                .take(rows.len());
1309            placeholder_lines
1310                .map(|line| {
1311                    cx.text_layout_cache().layout_str(
1312                        line,
1313                        placeholder_style.font_size,
1314                        &[(
1315                            line.len(),
1316                            RunStyle {
1317                                font_id: placeholder_style.font_id,
1318                                color: placeholder_style.color,
1319                                underline: Default::default(),
1320                            },
1321                        )],
1322                    )
1323                })
1324                .map(|line| LineWithInvisibles {
1325                    line,
1326                    invisibles: Vec::new(),
1327                })
1328                .collect()
1329        } else {
1330            let style = &self.style;
1331            let chunks = snapshot
1332                .chunks(rows.clone(), true, Some(style.theme.suggestion))
1333                .map(|chunk| {
1334                    let mut highlight_style = chunk
1335                        .syntax_highlight_id
1336                        .and_then(|id| id.style(&style.syntax));
1337
1338                    if let Some(chunk_highlight) = chunk.highlight_style {
1339                        if let Some(highlight_style) = highlight_style.as_mut() {
1340                            highlight_style.highlight(chunk_highlight);
1341                        } else {
1342                            highlight_style = Some(chunk_highlight);
1343                        }
1344                    }
1345
1346                    let mut diagnostic_highlight = HighlightStyle::default();
1347
1348                    if chunk.is_unnecessary {
1349                        diagnostic_highlight.fade_out = Some(style.unnecessary_code_fade);
1350                    }
1351
1352                    if let Some(severity) = chunk.diagnostic_severity {
1353                        // Omit underlines for HINT/INFO diagnostics on 'unnecessary' code.
1354                        if severity <= DiagnosticSeverity::WARNING || !chunk.is_unnecessary {
1355                            let diagnostic_style = super::diagnostic_style(severity, true, style);
1356                            diagnostic_highlight.underline = Some(Underline {
1357                                color: Some(diagnostic_style.message.text.color),
1358                                thickness: 1.0.into(),
1359                                squiggly: true,
1360                            });
1361                        }
1362                    }
1363
1364                    if let Some(highlight_style) = highlight_style.as_mut() {
1365                        highlight_style.highlight(diagnostic_highlight);
1366                    } else {
1367                        highlight_style = Some(diagnostic_highlight);
1368                    }
1369
1370                    HighlightedChunk {
1371                        chunk: chunk.text,
1372                        style: highlight_style,
1373                        is_tab: chunk.is_tab,
1374                    }
1375                });
1376
1377            layout_highlighted_chunks(
1378                chunks,
1379                &style.text,
1380                cx.text_layout_cache(),
1381                cx.font_cache(),
1382                MAX_LINE_LEN,
1383                rows.len() as usize,
1384                line_number_layouts,
1385                snapshot.mode,
1386            )
1387        }
1388    }
1389
1390    #[allow(clippy::too_many_arguments)]
1391    fn layout_blocks(
1392        &mut self,
1393        rows: Range<u32>,
1394        snapshot: &EditorSnapshot,
1395        editor_width: f32,
1396        scroll_width: f32,
1397        gutter_padding: f32,
1398        gutter_width: f32,
1399        em_width: f32,
1400        text_x: f32,
1401        line_height: f32,
1402        style: &EditorStyle,
1403        line_layouts: &[LineWithInvisibles],
1404        include_root: bool,
1405        editor: &mut Editor,
1406        cx: &mut LayoutContext<Editor>,
1407    ) -> (f32, Vec<BlockLayout>) {
1408        let tooltip_style = cx.global::<Settings>().theme.tooltip.clone();
1409        let scroll_x = snapshot.scroll_anchor.offset.x();
1410        let (fixed_blocks, non_fixed_blocks) = snapshot
1411            .blocks_in_range(rows.clone())
1412            .partition::<Vec<_>, _>(|(_, block)| match block {
1413                TransformBlock::ExcerptHeader { .. } => false,
1414                TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
1415            });
1416        let mut render_block = |block: &TransformBlock, width: f32| {
1417            let mut element = match block {
1418                TransformBlock::Custom(block) => {
1419                    let align_to = block
1420                        .position()
1421                        .to_point(&snapshot.buffer_snapshot)
1422                        .to_display_point(snapshot);
1423                    let anchor_x = text_x
1424                        + if rows.contains(&align_to.row()) {
1425                            line_layouts[(align_to.row() - rows.start) as usize]
1426                                .line
1427                                .x_for_index(align_to.column() as usize)
1428                        } else {
1429                            layout_line(align_to.row(), snapshot, style, cx.text_layout_cache())
1430                                .x_for_index(align_to.column() as usize)
1431                        };
1432
1433                    block.render(&mut BlockContext {
1434                        view_context: cx,
1435                        anchor_x,
1436                        gutter_padding,
1437                        line_height,
1438                        scroll_x,
1439                        gutter_width,
1440                        em_width,
1441                    })
1442                }
1443                TransformBlock::ExcerptHeader {
1444                    id,
1445                    buffer,
1446                    range,
1447                    starts_new_buffer,
1448                    ..
1449                } => {
1450                    let id = *id;
1451                    let jump_icon = project::File::from_dyn(buffer.file()).map(|file| {
1452                        let jump_path = ProjectPath {
1453                            worktree_id: file.worktree_id(cx),
1454                            path: file.path.clone(),
1455                        };
1456                        let jump_anchor = range
1457                            .primary
1458                            .as_ref()
1459                            .map_or(range.context.start, |primary| primary.start);
1460                        let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
1461
1462                        enum JumpIcon {}
1463                        MouseEventHandler::<JumpIcon, _>::new(id.into(), cx, |state, _| {
1464                            let style = style.jump_icon.style_for(state, false);
1465                            Svg::new("icons/arrow_up_right_8.svg")
1466                                .with_color(style.color)
1467                                .constrained()
1468                                .with_width(style.icon_width)
1469                                .aligned()
1470                                .contained()
1471                                .with_style(style.container)
1472                                .constrained()
1473                                .with_width(style.button_width)
1474                                .with_height(style.button_width)
1475                        })
1476                        .with_cursor_style(CursorStyle::PointingHand)
1477                        .on_click(MouseButton::Left, move |_, editor, cx| {
1478                            if let Some(workspace) = editor
1479                                .workspace
1480                                .as_ref()
1481                                .and_then(|(workspace, _)| workspace.upgrade(cx))
1482                            {
1483                                workspace.update(cx, |workspace, cx| {
1484                                    Editor::jump(
1485                                        workspace,
1486                                        jump_path.clone(),
1487                                        jump_position,
1488                                        jump_anchor,
1489                                        cx,
1490                                    );
1491                                });
1492                            }
1493                        })
1494                        .with_tooltip::<JumpIcon>(
1495                            id.into(),
1496                            "Jump to Buffer".to_string(),
1497                            Some(Box::new(crate::OpenExcerpts)),
1498                            tooltip_style.clone(),
1499                            cx,
1500                        )
1501                        .aligned()
1502                        .flex_float()
1503                    });
1504
1505                    if *starts_new_buffer {
1506                        let style = &self.style.diagnostic_path_header;
1507                        let font_size =
1508                            (style.text_scale_factor * self.style.text.font_size).round();
1509
1510                        let path = buffer.resolve_file_path(cx, include_root);
1511                        let mut filename = None;
1512                        let mut parent_path = None;
1513                        // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
1514                        if let Some(path) = path {
1515                            filename = path.file_name().map(|f| f.to_string_lossy().to_string());
1516                            parent_path =
1517                                path.parent().map(|p| p.to_string_lossy().to_string() + "/");
1518                        }
1519
1520                        Flex::row()
1521                            .with_child(
1522                                Label::new(
1523                                    filename.unwrap_or_else(|| "untitled".to_string()),
1524                                    style.filename.text.clone().with_font_size(font_size),
1525                                )
1526                                .contained()
1527                                .with_style(style.filename.container)
1528                                .aligned(),
1529                            )
1530                            .with_children(parent_path.map(|path| {
1531                                Label::new(path, style.path.text.clone().with_font_size(font_size))
1532                                    .contained()
1533                                    .with_style(style.path.container)
1534                                    .aligned()
1535                            }))
1536                            .with_children(jump_icon)
1537                            .contained()
1538                            .with_style(style.container)
1539                            .with_padding_left(gutter_padding)
1540                            .with_padding_right(gutter_padding)
1541                            .expanded()
1542                            .into_any_named("path header block")
1543                    } else {
1544                        let text_style = self.style.text.clone();
1545                        Flex::row()
1546                            .with_child(Label::new("", text_style))
1547                            .with_children(jump_icon)
1548                            .contained()
1549                            .with_padding_left(gutter_padding)
1550                            .with_padding_right(gutter_padding)
1551                            .expanded()
1552                            .into_any_named("collapsed context")
1553                    }
1554                }
1555            };
1556
1557            element.layout(
1558                SizeConstraint {
1559                    min: Vector2F::zero(),
1560                    max: vec2f(width, block.height() as f32 * line_height),
1561                },
1562                editor,
1563                cx,
1564            );
1565            element
1566        };
1567
1568        let mut fixed_block_max_width = 0f32;
1569        let mut blocks = Vec::new();
1570        for (row, block) in fixed_blocks {
1571            let element = render_block(block, f32::INFINITY);
1572            fixed_block_max_width = fixed_block_max_width.max(element.size().x() + em_width);
1573            blocks.push(BlockLayout {
1574                row,
1575                element,
1576                style: BlockStyle::Fixed,
1577            });
1578        }
1579        for (row, block) in non_fixed_blocks {
1580            let style = match block {
1581                TransformBlock::Custom(block) => block.style(),
1582                TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
1583            };
1584            let width = match style {
1585                BlockStyle::Sticky => editor_width,
1586                BlockStyle::Flex => editor_width
1587                    .max(fixed_block_max_width)
1588                    .max(gutter_width + scroll_width),
1589                BlockStyle::Fixed => unreachable!(),
1590            };
1591            let element = render_block(block, width);
1592            blocks.push(BlockLayout {
1593                row,
1594                element,
1595                style,
1596            });
1597        }
1598        (
1599            scroll_width.max(fixed_block_max_width - gutter_width),
1600            blocks,
1601        )
1602    }
1603}
1604
1605fn draw_line_glyphs(
1606    layout: &mut LayoutState,
1607    start_row: u32,
1608    scroll_top: f32,
1609    scene: &mut SceneBuilder,
1610    content_origin: Vector2F,
1611    scroll_left: f32,
1612    visible_text_bounds: RectF,
1613    cx: &mut ViewContext<Editor>,
1614    selection_ranges: SmallVec<[Range<DisplayPoint>; 32]>,
1615    visible_bounds: RectF,
1616) {
1617    let line_height = layout.position_map.line_height;
1618
1619    for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
1620        let row = start_row + ix as u32;
1621        let line_y = row as f32 * line_height - scroll_top;
1622
1623        line_with_invisibles.line.paint(
1624            scene,
1625            content_origin + vec2f(-scroll_left, line_y),
1626            visible_text_bounds,
1627            line_height,
1628            cx,
1629        );
1630
1631        draw_invisibles(
1632            cx,
1633            &selection_ranges,
1634            line_with_invisibles,
1635            layout,
1636            content_origin,
1637            scroll_left,
1638            line_y,
1639            row,
1640            scene,
1641            visible_bounds,
1642            line_height,
1643        );
1644    }
1645}
1646
1647fn draw_invisibles(
1648    cx: &mut ViewContext<Editor>,
1649    selection_ranges: &SmallVec<[Range<DisplayPoint>; 32]>,
1650    line_with_invisibles: &LineWithInvisibles,
1651    layout: &LayoutState,
1652    content_origin: Vector2F,
1653    scroll_left: f32,
1654    line_y: f32,
1655    row: u32,
1656    scene: &mut SceneBuilder,
1657    visible_bounds: RectF,
1658    line_height: f32,
1659) {
1660    let settings = cx.global::<Settings>();
1661    let regions_to_hit = match settings
1662        .editor_overrides
1663        .show_whitespaces
1664        .or(settings.editor_defaults.show_whitespaces)
1665        .unwrap_or_default()
1666    {
1667        ShowWhitespaces::None => return,
1668        ShowWhitespaces::Selection => Some(selection_ranges),
1669        ShowWhitespaces::All => None,
1670    };
1671
1672    for invisible in &line_with_invisibles.invisibles {
1673        let (&token_offset, invisible_symbol) = match invisible {
1674            Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
1675            Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
1676        };
1677
1678        let x_offset = line_with_invisibles.line.x_for_index(token_offset);
1679        let invisible_offset =
1680            (layout.position_map.em_width - invisible_symbol.width()).max(0.0) / 2.0;
1681        let origin = content_origin + vec2f(-scroll_left + x_offset + invisible_offset, line_y);
1682
1683        if let Some(regions_to_hit) = regions_to_hit {
1684            let invisible_point = DisplayPoint::new(row, token_offset as u32);
1685            if !regions_to_hit
1686                .iter()
1687                .any(|region| region.start <= invisible_point && invisible_point < region.end)
1688            {
1689                continue;
1690            }
1691        }
1692        invisible_symbol.paint(scene, origin, visible_bounds, line_height, cx);
1693    }
1694}
1695
1696struct HighlightedChunk<'a> {
1697    chunk: &'a str,
1698    style: Option<HighlightStyle>,
1699    is_tab: bool,
1700}
1701
1702#[derive(Debug)]
1703pub struct LineWithInvisibles {
1704    pub line: Line,
1705    invisibles: Vec<Invisible>,
1706}
1707
1708#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1709enum Invisible {
1710    Tab { line_start_offset: usize },
1711    Whitespace { line_offset: usize },
1712}
1713
1714fn layout_highlighted_chunks<'a>(
1715    chunks: impl Iterator<Item = HighlightedChunk<'a>>,
1716    text_style: &TextStyle,
1717    text_layout_cache: &TextLayoutCache,
1718    font_cache: &Arc<FontCache>,
1719    max_line_len: usize,
1720    max_line_count: usize,
1721    line_number_layouts: &[Option<Line>],
1722    editor_mode: EditorMode,
1723) -> Vec<LineWithInvisibles> {
1724    let mut layouts = Vec::with_capacity(max_line_count);
1725    let mut line = String::new();
1726    let mut invisibles = Vec::new();
1727    let mut styles = Vec::new();
1728    let mut non_whitespace_added = false;
1729    let mut row = 0;
1730    let mut line_exceeded_max_len = false;
1731    for highlighted_chunk in chunks.chain([HighlightedChunk {
1732        chunk: "\n",
1733        style: None,
1734        is_tab: false,
1735    }]) {
1736        for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
1737            if ix > 0 {
1738                layouts.push(LineWithInvisibles {
1739                    line: text_layout_cache.layout_str(&line, text_style.font_size, &styles),
1740                    invisibles: invisibles.drain(..).collect(),
1741                });
1742
1743                line.clear();
1744                styles.clear();
1745                row += 1;
1746                line_exceeded_max_len = false;
1747                non_whitespace_added = false;
1748                if row == max_line_count {
1749                    return layouts;
1750                }
1751            }
1752
1753            if !line_chunk.is_empty() && !line_exceeded_max_len {
1754                let text_style = if let Some(style) = highlighted_chunk.style {
1755                    text_style
1756                        .clone()
1757                        .highlight(style, font_cache)
1758                        .map(Cow::Owned)
1759                        .unwrap_or_else(|_| Cow::Borrowed(text_style))
1760                } else {
1761                    Cow::Borrowed(text_style)
1762                };
1763
1764                if line.len() + line_chunk.len() > max_line_len {
1765                    let mut chunk_len = max_line_len - line.len();
1766                    while !line_chunk.is_char_boundary(chunk_len) {
1767                        chunk_len -= 1;
1768                    }
1769                    line_chunk = &line_chunk[..chunk_len];
1770                    line_exceeded_max_len = true;
1771                }
1772
1773                styles.push((
1774                    line_chunk.len(),
1775                    RunStyle {
1776                        font_id: text_style.font_id,
1777                        color: text_style.color,
1778                        underline: text_style.underline,
1779                    },
1780                ));
1781
1782                if editor_mode == EditorMode::Full {
1783                    // Line wrap pads its contents with fake whitespaces,
1784                    // avoid printing them
1785                    let inside_wrapped_string = line_number_layouts
1786                        .get(row)
1787                        .and_then(|layout| layout.as_ref())
1788                        .is_none();
1789                    if highlighted_chunk.is_tab {
1790                        if non_whitespace_added || !inside_wrapped_string {
1791                            invisibles.push(Invisible::Tab {
1792                                line_start_offset: line.len(),
1793                            });
1794                        }
1795                    } else {
1796                        invisibles.extend(
1797                            line_chunk
1798                                .chars()
1799                                .enumerate()
1800                                .filter(|(_, line_char)| {
1801                                    let is_whitespace = line_char.is_whitespace();
1802                                    non_whitespace_added |= !is_whitespace;
1803                                    is_whitespace
1804                                        && (non_whitespace_added || !inside_wrapped_string)
1805                                })
1806                                .map(|(whitespace_index, _)| Invisible::Whitespace {
1807                                    line_offset: line.len() + whitespace_index,
1808                                }),
1809                        )
1810                    }
1811                }
1812
1813                line.push_str(line_chunk);
1814            }
1815        }
1816    }
1817
1818    layouts
1819}
1820
1821impl Element<Editor> for EditorElement {
1822    type LayoutState = LayoutState;
1823    type PaintState = ();
1824
1825    fn layout(
1826        &mut self,
1827        constraint: SizeConstraint,
1828        editor: &mut Editor,
1829        cx: &mut LayoutContext<Editor>,
1830    ) -> (Vector2F, Self::LayoutState) {
1831        let mut size = constraint.max;
1832        if size.x().is_infinite() {
1833            unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
1834        }
1835
1836        let snapshot = editor.snapshot(cx);
1837        let style = self.style.clone();
1838        let line_height = style.text.line_height(cx.font_cache());
1839
1840        let gutter_padding;
1841        let gutter_width;
1842        let gutter_margin;
1843        if snapshot.mode == EditorMode::Full {
1844            let em_width = style.text.em_width(cx.font_cache());
1845            gutter_padding = (em_width * style.gutter_padding_factor).round();
1846            gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
1847            gutter_margin = -style.text.descent(cx.font_cache());
1848        } else {
1849            gutter_padding = 0.0;
1850            gutter_width = 0.0;
1851            gutter_margin = 0.0;
1852        };
1853
1854        let text_width = size.x() - gutter_width;
1855        let em_width = style.text.em_width(cx.font_cache());
1856        let em_advance = style.text.em_advance(cx.font_cache());
1857        let overscroll = vec2f(em_width, 0.);
1858        let snapshot = {
1859            editor.set_visible_line_count(size.y() / line_height);
1860
1861            let editor_width = text_width - gutter_margin - overscroll.x() - em_width;
1862            let wrap_width = match editor.soft_wrap_mode(cx) {
1863                SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
1864                SoftWrap::EditorWidth => editor_width,
1865                SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
1866            };
1867
1868            if editor.set_wrap_width(Some(wrap_width), cx) {
1869                editor.snapshot(cx)
1870            } else {
1871                snapshot
1872            }
1873        };
1874
1875        let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
1876        if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
1877            size.set_y(
1878                scroll_height
1879                    .min(constraint.max_along(Axis::Vertical))
1880                    .max(constraint.min_along(Axis::Vertical))
1881                    .min(line_height * max_lines as f32),
1882            )
1883        } else if let EditorMode::SingleLine = snapshot.mode {
1884            size.set_y(
1885                line_height
1886                    .min(constraint.max_along(Axis::Vertical))
1887                    .max(constraint.min_along(Axis::Vertical)),
1888            )
1889        } else if size.y().is_infinite() {
1890            size.set_y(scroll_height);
1891        }
1892        let gutter_size = vec2f(gutter_width, size.y());
1893        let text_size = vec2f(text_width, size.y());
1894
1895        let autoscroll_horizontally = editor.autoscroll_vertically(size.y(), line_height, cx);
1896        let mut snapshot = editor.snapshot(cx);
1897
1898        let scroll_position = snapshot.scroll_position();
1899        // The scroll position is a fractional point, the whole number of which represents
1900        // the top of the window in terms of display rows.
1901        let start_row = scroll_position.y() as u32;
1902        let height_in_lines = size.y() / line_height;
1903        let max_row = snapshot.max_point().row();
1904
1905        // Add 1 to ensure selections bleed off screen
1906        let end_row = 1 + cmp::min(
1907            (scroll_position.y() + height_in_lines).ceil() as u32,
1908            max_row,
1909        );
1910
1911        let start_anchor = if start_row == 0 {
1912            Anchor::min()
1913        } else {
1914            snapshot
1915                .buffer_snapshot
1916                .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
1917        };
1918        let end_anchor = if end_row > max_row {
1919            Anchor::max()
1920        } else {
1921            snapshot
1922                .buffer_snapshot
1923                .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
1924        };
1925
1926        let mut selections: Vec<(ReplicaId, Vec<SelectionLayout>)> = Vec::new();
1927        let mut active_rows = BTreeMap::new();
1928        let mut fold_ranges = Vec::new();
1929        let is_singleton = editor.is_singleton(cx);
1930
1931        let highlighted_rows = editor.highlighted_rows();
1932        let theme = cx.global::<Settings>().theme.as_ref();
1933        let highlighted_ranges = editor.background_highlights_in_range(
1934            start_anchor..end_anchor,
1935            &snapshot.display_snapshot,
1936            theme,
1937        );
1938
1939        fold_ranges.extend(
1940            snapshot
1941                .folds_in_range(start_anchor..end_anchor)
1942                .map(|anchor| {
1943                    let start = anchor.start.to_point(&snapshot.buffer_snapshot);
1944                    (
1945                        start.row,
1946                        start.to_display_point(&snapshot.display_snapshot)
1947                            ..anchor.end.to_display_point(&snapshot),
1948                    )
1949                }),
1950        );
1951
1952        let mut remote_selections = HashMap::default();
1953        for (replica_id, line_mode, cursor_shape, selection) in snapshot
1954            .buffer_snapshot
1955            .remote_selections_in_range(&(start_anchor..end_anchor))
1956        {
1957            // The local selections match the leader's selections.
1958            if Some(replica_id) == editor.leader_replica_id {
1959                continue;
1960            }
1961            remote_selections
1962                .entry(replica_id)
1963                .or_insert(Vec::new())
1964                .push(SelectionLayout::new(
1965                    selection,
1966                    line_mode,
1967                    cursor_shape,
1968                    &snapshot.display_snapshot,
1969                ));
1970        }
1971        selections.extend(remote_selections);
1972
1973        if editor.show_local_selections {
1974            let mut local_selections = editor
1975                .selections
1976                .disjoint_in_range(start_anchor..end_anchor, cx);
1977            local_selections.extend(editor.selections.pending(cx));
1978            for selection in &local_selections {
1979                let is_empty = selection.start == selection.end;
1980                let selection_start = snapshot.prev_line_boundary(selection.start).1;
1981                let selection_end = snapshot.next_line_boundary(selection.end).1;
1982                for row in cmp::max(selection_start.row(), start_row)
1983                    ..=cmp::min(selection_end.row(), end_row)
1984                {
1985                    let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
1986                    *contains_non_empty_selection |= !is_empty;
1987                }
1988            }
1989
1990            // Render the local selections in the leader's color when following.
1991            let local_replica_id = editor
1992                .leader_replica_id
1993                .unwrap_or_else(|| editor.replica_id(cx));
1994
1995            selections.push((
1996                local_replica_id,
1997                local_selections
1998                    .into_iter()
1999                    .map(|selection| {
2000                        SelectionLayout::new(
2001                            selection,
2002                            editor.selections.line_mode,
2003                            editor.cursor_shape,
2004                            &snapshot.display_snapshot,
2005                        )
2006                    })
2007                    .collect(),
2008            ));
2009        }
2010
2011        let show_scrollbars = editor.scroll_manager.scrollbars_visible();
2012        let include_root = editor
2013            .project
2014            .as_ref()
2015            .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
2016            .unwrap_or_default();
2017
2018        let fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)> = fold_ranges
2019            .into_iter()
2020            .map(|(id, fold)| {
2021                let color = self
2022                    .style
2023                    .folds
2024                    .ellipses
2025                    .background
2026                    .style_for(&mut cx.mouse_state::<FoldMarkers>(id as usize), false)
2027                    .color;
2028
2029                (id, fold, color)
2030            })
2031            .collect();
2032
2033        let (line_number_layouts, fold_statuses) = self.layout_line_numbers(
2034            start_row..end_row,
2035            &active_rows,
2036            is_singleton,
2037            &snapshot,
2038            cx,
2039        );
2040
2041        let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
2042
2043        let scrollbar_row_range = scroll_position.y()..(scroll_position.y() + height_in_lines);
2044
2045        let mut max_visible_line_width = 0.0;
2046        let line_layouts =
2047            self.layout_lines(start_row..end_row, &line_number_layouts, &snapshot, cx);
2048        for line_with_invisibles in &line_layouts {
2049            if line_with_invisibles.line.width() > max_visible_line_width {
2050                max_visible_line_width = line_with_invisibles.line.width();
2051            }
2052        }
2053
2054        let style = self.style.clone();
2055        let longest_line_width = layout_line(
2056            snapshot.longest_row(),
2057            &snapshot,
2058            &style,
2059            cx.text_layout_cache(),
2060        )
2061        .width();
2062        let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
2063        let em_width = style.text.em_width(cx.font_cache());
2064        let (scroll_width, blocks) = self.layout_blocks(
2065            start_row..end_row,
2066            &snapshot,
2067            size.x(),
2068            scroll_width,
2069            gutter_padding,
2070            gutter_width,
2071            em_width,
2072            gutter_width + gutter_margin,
2073            line_height,
2074            &style,
2075            &line_layouts,
2076            include_root,
2077            editor,
2078            cx,
2079        );
2080
2081        let scroll_max = vec2f(
2082            ((scroll_width - text_size.x()) / em_width).max(0.0),
2083            max_row as f32,
2084        );
2085
2086        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x());
2087
2088        let autoscrolled = if autoscroll_horizontally {
2089            editor.autoscroll_horizontally(
2090                start_row,
2091                text_size.x(),
2092                scroll_width,
2093                em_width,
2094                &line_layouts,
2095                cx,
2096            )
2097        } else {
2098            false
2099        };
2100
2101        if clamped || autoscrolled {
2102            snapshot = editor.snapshot(cx);
2103        }
2104
2105        let newest_selection_head = editor
2106            .selections
2107            .newest::<usize>(cx)
2108            .head()
2109            .to_display_point(&snapshot);
2110        let style = editor.style(cx);
2111
2112        let mut context_menu = None;
2113        let mut code_actions_indicator = None;
2114        if (start_row..end_row).contains(&newest_selection_head.row()) {
2115            if editor.context_menu_visible() {
2116                context_menu = editor.render_context_menu(newest_selection_head, style.clone(), cx);
2117            }
2118
2119            let active = matches!(
2120                editor.context_menu,
2121                Some(crate::ContextMenu::CodeActions(_))
2122            );
2123
2124            code_actions_indicator = editor
2125                .render_code_actions_indicator(&style, active, cx)
2126                .map(|indicator| (newest_selection_head.row(), indicator));
2127        }
2128
2129        let visible_rows = start_row..start_row + line_layouts.len() as u32;
2130        let mut hover = editor
2131            .hover_state
2132            .render(&snapshot, &style, visible_rows, cx);
2133        let mode = editor.mode;
2134
2135        let mut fold_indicators = editor.render_fold_indicators(
2136            fold_statuses,
2137            &style,
2138            editor.gutter_hovered,
2139            line_height,
2140            gutter_margin,
2141            cx,
2142        );
2143
2144        if let Some((_, context_menu)) = context_menu.as_mut() {
2145            context_menu.layout(
2146                SizeConstraint {
2147                    min: Vector2F::zero(),
2148                    max: vec2f(
2149                        cx.window_size().x() * 0.7,
2150                        (12. * line_height).min((size.y() - line_height) / 2.),
2151                    ),
2152                },
2153                editor,
2154                cx,
2155            );
2156        }
2157
2158        if let Some((_, indicator)) = code_actions_indicator.as_mut() {
2159            indicator.layout(
2160                SizeConstraint::strict_along(
2161                    Axis::Vertical,
2162                    line_height * style.code_actions.vertical_scale,
2163                ),
2164                editor,
2165                cx,
2166            );
2167        }
2168
2169        for fold_indicator in fold_indicators.iter_mut() {
2170            if let Some(indicator) = fold_indicator.as_mut() {
2171                indicator.layout(
2172                    SizeConstraint::strict_along(
2173                        Axis::Vertical,
2174                        line_height * style.code_actions.vertical_scale,
2175                    ),
2176                    editor,
2177                    cx,
2178                );
2179            }
2180        }
2181
2182        if let Some((_, hover_popovers)) = hover.as_mut() {
2183            for hover_popover in hover_popovers.iter_mut() {
2184                hover_popover.layout(
2185                    SizeConstraint {
2186                        min: Vector2F::zero(),
2187                        max: vec2f(
2188                            (120. * em_width) // Default size
2189                                .min(size.x() / 2.) // Shrink to half of the editor width
2190                                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2191                            (16. * line_height) // Default size
2192                                .min(size.y() / 2.) // Shrink to half of the editor height
2193                                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2194                        ),
2195                    },
2196                    editor,
2197                    cx,
2198                );
2199            }
2200        }
2201
2202        let invisible_symbol_font_size = self.style.text.font_size / 2.0;
2203        let invisible_symbol_style = RunStyle {
2204            color: self.style.whitespace,
2205            font_id: self.style.text.font_id,
2206            underline: Default::default(),
2207        };
2208
2209        (
2210            size,
2211            LayoutState {
2212                mode,
2213                position_map: Arc::new(PositionMap {
2214                    size,
2215                    scroll_max,
2216                    line_layouts,
2217                    line_height,
2218                    em_width,
2219                    em_advance,
2220                    snapshot,
2221                }),
2222                visible_display_row_range: start_row..end_row,
2223                gutter_size,
2224                gutter_padding,
2225                text_size,
2226                scrollbar_row_range,
2227                show_scrollbars,
2228                max_row,
2229                gutter_margin,
2230                active_rows,
2231                highlighted_rows,
2232                highlighted_ranges,
2233                fold_ranges,
2234                line_number_layouts,
2235                display_hunks,
2236                blocks,
2237                selections,
2238                context_menu,
2239                code_actions_indicator,
2240                fold_indicators,
2241                tab_invisible: cx.text_layout_cache().layout_str(
2242                    "",
2243                    invisible_symbol_font_size,
2244                    &[("".len(), invisible_symbol_style)],
2245                ),
2246                space_invisible: cx.text_layout_cache().layout_str(
2247                    "",
2248                    invisible_symbol_font_size,
2249                    &[("".len(), invisible_symbol_style)],
2250                ),
2251                hover_popovers: hover,
2252            },
2253        )
2254    }
2255
2256    fn paint(
2257        &mut self,
2258        scene: &mut SceneBuilder,
2259        bounds: RectF,
2260        visible_bounds: RectF,
2261        layout: &mut Self::LayoutState,
2262        editor: &mut Editor,
2263        cx: &mut ViewContext<Editor>,
2264    ) -> Self::PaintState {
2265        let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
2266        scene.push_layer(Some(visible_bounds));
2267
2268        let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
2269        let text_bounds = RectF::new(
2270            bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
2271            layout.text_size,
2272        );
2273
2274        Self::attach_mouse_handlers(
2275            scene,
2276            &layout.position_map,
2277            layout.hover_popovers.is_some(),
2278            visible_bounds,
2279            text_bounds,
2280            gutter_bounds,
2281            bounds,
2282            cx,
2283        );
2284
2285        self.paint_background(scene, gutter_bounds, text_bounds, layout);
2286        if layout.gutter_size.x() > 0. {
2287            self.paint_gutter(scene, gutter_bounds, visible_bounds, layout, editor, cx);
2288        }
2289        self.paint_text(scene, text_bounds, visible_bounds, layout, editor, cx);
2290
2291        scene.push_layer(Some(bounds));
2292        if !layout.blocks.is_empty() {
2293            self.paint_blocks(scene, bounds, visible_bounds, layout, editor, cx);
2294        }
2295        self.paint_scrollbar(scene, bounds, layout, cx);
2296        scene.pop_layer();
2297
2298        scene.pop_layer();
2299    }
2300
2301    fn rect_for_text_range(
2302        &self,
2303        range_utf16: Range<usize>,
2304        bounds: RectF,
2305        _: RectF,
2306        layout: &Self::LayoutState,
2307        _: &Self::PaintState,
2308        _: &Editor,
2309        _: &ViewContext<Editor>,
2310    ) -> Option<RectF> {
2311        let text_bounds = RectF::new(
2312            bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
2313            layout.text_size,
2314        );
2315        let content_origin = text_bounds.origin() + vec2f(layout.gutter_margin, 0.);
2316        let scroll_position = layout.position_map.snapshot.scroll_position();
2317        let start_row = scroll_position.y() as u32;
2318        let scroll_top = scroll_position.y() * layout.position_map.line_height;
2319        let scroll_left = scroll_position.x() * layout.position_map.em_width;
2320
2321        let range_start = OffsetUtf16(range_utf16.start)
2322            .to_display_point(&layout.position_map.snapshot.display_snapshot);
2323        if range_start.row() < start_row {
2324            return None;
2325        }
2326
2327        let line = &layout
2328            .position_map
2329            .line_layouts
2330            .get((range_start.row() - start_row) as usize)?
2331            .line;
2332        let range_start_x = line.x_for_index(range_start.column() as usize);
2333        let range_start_y = range_start.row() as f32 * layout.position_map.line_height;
2334        Some(RectF::new(
2335            content_origin
2336                + vec2f(
2337                    range_start_x,
2338                    range_start_y + layout.position_map.line_height,
2339                )
2340                - vec2f(scroll_left, scroll_top),
2341            vec2f(
2342                layout.position_map.em_width,
2343                layout.position_map.line_height,
2344            ),
2345        ))
2346    }
2347
2348    fn debug(
2349        &self,
2350        bounds: RectF,
2351        _: &Self::LayoutState,
2352        _: &Self::PaintState,
2353        _: &Editor,
2354        _: &ViewContext<Editor>,
2355    ) -> json::Value {
2356        json!({
2357            "type": "BufferElement",
2358            "bounds": bounds.to_json()
2359        })
2360    }
2361}
2362
2363type BufferRow = u32;
2364
2365pub struct LayoutState {
2366    position_map: Arc<PositionMap>,
2367    gutter_size: Vector2F,
2368    gutter_padding: f32,
2369    gutter_margin: f32,
2370    text_size: Vector2F,
2371    mode: EditorMode,
2372    visible_display_row_range: Range<u32>,
2373    active_rows: BTreeMap<u32, bool>,
2374    highlighted_rows: Option<Range<u32>>,
2375    line_number_layouts: Vec<Option<text_layout::Line>>,
2376    display_hunks: Vec<DisplayDiffHunk>,
2377    blocks: Vec<BlockLayout>,
2378    highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
2379    fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)>,
2380    selections: Vec<(ReplicaId, Vec<SelectionLayout>)>,
2381    scrollbar_row_range: Range<f32>,
2382    show_scrollbars: bool,
2383    max_row: u32,
2384    context_menu: Option<(DisplayPoint, AnyElement<Editor>)>,
2385    code_actions_indicator: Option<(u32, AnyElement<Editor>)>,
2386    hover_popovers: Option<(DisplayPoint, Vec<AnyElement<Editor>>)>,
2387    fold_indicators: Vec<Option<AnyElement<Editor>>>,
2388    tab_invisible: Line,
2389    space_invisible: Line,
2390}
2391
2392struct PositionMap {
2393    size: Vector2F,
2394    line_height: f32,
2395    scroll_max: Vector2F,
2396    em_width: f32,
2397    em_advance: f32,
2398    line_layouts: Vec<LineWithInvisibles>,
2399    snapshot: EditorSnapshot,
2400}
2401
2402impl PositionMap {
2403    /// Returns two display points:
2404    /// 1. The nearest *valid* position in the editor
2405    /// 2. An unclipped, potentially *invalid* position that maps directly to
2406    ///    the given pixel position.
2407    fn point_for_position(
2408        &self,
2409        text_bounds: RectF,
2410        position: Vector2F,
2411    ) -> (DisplayPoint, DisplayPoint) {
2412        let scroll_position = self.snapshot.scroll_position();
2413        let position = position - text_bounds.origin();
2414        let y = position.y().max(0.0).min(self.size.y());
2415        let x = position.x() + (scroll_position.x() * self.em_width);
2416        let row = (y / self.line_height + scroll_position.y()) as u32;
2417        let (column, x_overshoot) = if let Some(line) = self
2418            .line_layouts
2419            .get(row as usize - scroll_position.y() as usize)
2420            .map(|line_with_spaces| &line_with_spaces.line)
2421        {
2422            if let Some(ix) = line.index_for_x(x) {
2423                (ix as u32, 0.0)
2424            } else {
2425                (line.len() as u32, 0f32.max(x - line.width()))
2426            }
2427        } else {
2428            (0, x)
2429        };
2430
2431        let mut target_point = DisplayPoint::new(row, column);
2432        let point = self.snapshot.clip_point(target_point, Bias::Left);
2433        *target_point.column_mut() += (x_overshoot / self.em_advance) as u32;
2434
2435        (point, target_point)
2436    }
2437}
2438
2439struct BlockLayout {
2440    row: u32,
2441    element: AnyElement<Editor>,
2442    style: BlockStyle,
2443}
2444
2445fn layout_line(
2446    row: u32,
2447    snapshot: &EditorSnapshot,
2448    style: &EditorStyle,
2449    layout_cache: &TextLayoutCache,
2450) -> text_layout::Line {
2451    let mut line = snapshot.line(row);
2452
2453    if line.len() > MAX_LINE_LEN {
2454        let mut len = MAX_LINE_LEN;
2455        while !line.is_char_boundary(len) {
2456            len -= 1;
2457        }
2458
2459        line.truncate(len);
2460    }
2461
2462    layout_cache.layout_str(
2463        &line,
2464        style.text.font_size,
2465        &[(
2466            snapshot.line_len(row) as usize,
2467            RunStyle {
2468                font_id: style.text.font_id,
2469                color: Color::black(),
2470                underline: Default::default(),
2471            },
2472        )],
2473    )
2474}
2475
2476#[derive(Debug)]
2477pub struct Cursor {
2478    origin: Vector2F,
2479    block_width: f32,
2480    line_height: f32,
2481    color: Color,
2482    shape: CursorShape,
2483    block_text: Option<Line>,
2484}
2485
2486impl Cursor {
2487    pub fn new(
2488        origin: Vector2F,
2489        block_width: f32,
2490        line_height: f32,
2491        color: Color,
2492        shape: CursorShape,
2493        block_text: Option<Line>,
2494    ) -> Cursor {
2495        Cursor {
2496            origin,
2497            block_width,
2498            line_height,
2499            color,
2500            shape,
2501            block_text,
2502        }
2503    }
2504
2505    pub fn bounding_rect(&self, origin: Vector2F) -> RectF {
2506        RectF::new(
2507            self.origin + origin,
2508            vec2f(self.block_width, self.line_height),
2509        )
2510    }
2511
2512    pub fn paint(&self, scene: &mut SceneBuilder, origin: Vector2F, cx: &mut WindowContext) {
2513        let bounds = match self.shape {
2514            CursorShape::Bar => RectF::new(self.origin + origin, vec2f(2.0, self.line_height)),
2515            CursorShape::Block | CursorShape::Hollow => RectF::new(
2516                self.origin + origin,
2517                vec2f(self.block_width, self.line_height),
2518            ),
2519            CursorShape::Underscore => RectF::new(
2520                self.origin + origin + Vector2F::new(0.0, self.line_height - 2.0),
2521                vec2f(self.block_width, 2.0),
2522            ),
2523        };
2524
2525        //Draw background or border quad
2526        if matches!(self.shape, CursorShape::Hollow) {
2527            scene.push_quad(Quad {
2528                bounds,
2529                background: None,
2530                border: Border::all(1., self.color),
2531                corner_radius: 0.,
2532            });
2533        } else {
2534            scene.push_quad(Quad {
2535                bounds,
2536                background: Some(self.color),
2537                border: Default::default(),
2538                corner_radius: 0.,
2539            });
2540        }
2541
2542        if let Some(block_text) = &self.block_text {
2543            block_text.paint(scene, self.origin + origin, bounds, self.line_height, cx);
2544        }
2545    }
2546
2547    pub fn shape(&self) -> CursorShape {
2548        self.shape
2549    }
2550}
2551
2552#[derive(Debug)]
2553pub struct HighlightedRange {
2554    pub start_y: f32,
2555    pub line_height: f32,
2556    pub lines: Vec<HighlightedRangeLine>,
2557    pub color: Color,
2558    pub corner_radius: f32,
2559}
2560
2561#[derive(Debug)]
2562pub struct HighlightedRangeLine {
2563    pub start_x: f32,
2564    pub end_x: f32,
2565}
2566
2567impl HighlightedRange {
2568    pub fn paint(&self, bounds: RectF, scene: &mut SceneBuilder) {
2569        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
2570            self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
2571            self.paint_lines(
2572                self.start_y + self.line_height,
2573                &self.lines[1..],
2574                bounds,
2575                scene,
2576            );
2577        } else {
2578            self.paint_lines(self.start_y, &self.lines, bounds, scene);
2579        }
2580    }
2581
2582    fn paint_lines(
2583        &self,
2584        start_y: f32,
2585        lines: &[HighlightedRangeLine],
2586        bounds: RectF,
2587        scene: &mut SceneBuilder,
2588    ) {
2589        if lines.is_empty() {
2590            return;
2591        }
2592
2593        let mut path = PathBuilder::new();
2594        let first_line = lines.first().unwrap();
2595        let last_line = lines.last().unwrap();
2596
2597        let first_top_left = vec2f(first_line.start_x, start_y);
2598        let first_top_right = vec2f(first_line.end_x, start_y);
2599
2600        let curve_height = vec2f(0., self.corner_radius);
2601        let curve_width = |start_x: f32, end_x: f32| {
2602            let max = (end_x - start_x) / 2.;
2603            let width = if max < self.corner_radius {
2604                max
2605            } else {
2606                self.corner_radius
2607            };
2608
2609            vec2f(width, 0.)
2610        };
2611
2612        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
2613        path.reset(first_top_right - top_curve_width);
2614        path.curve_to(first_top_right + curve_height, first_top_right);
2615
2616        let mut iter = lines.iter().enumerate().peekable();
2617        while let Some((ix, line)) = iter.next() {
2618            let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
2619
2620            if let Some((_, next_line)) = iter.peek() {
2621                let next_top_right = vec2f(next_line.end_x, bottom_right.y());
2622
2623                match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
2624                    Ordering::Equal => {
2625                        path.line_to(bottom_right);
2626                    }
2627                    Ordering::Less => {
2628                        let curve_width = curve_width(next_top_right.x(), bottom_right.x());
2629                        path.line_to(bottom_right - curve_height);
2630                        if self.corner_radius > 0. {
2631                            path.curve_to(bottom_right - curve_width, bottom_right);
2632                        }
2633                        path.line_to(next_top_right + curve_width);
2634                        if self.corner_radius > 0. {
2635                            path.curve_to(next_top_right + curve_height, next_top_right);
2636                        }
2637                    }
2638                    Ordering::Greater => {
2639                        let curve_width = curve_width(bottom_right.x(), next_top_right.x());
2640                        path.line_to(bottom_right - curve_height);
2641                        if self.corner_radius > 0. {
2642                            path.curve_to(bottom_right + curve_width, bottom_right);
2643                        }
2644                        path.line_to(next_top_right - curve_width);
2645                        if self.corner_radius > 0. {
2646                            path.curve_to(next_top_right + curve_height, next_top_right);
2647                        }
2648                    }
2649                }
2650            } else {
2651                let curve_width = curve_width(line.start_x, line.end_x);
2652                path.line_to(bottom_right - curve_height);
2653                if self.corner_radius > 0. {
2654                    path.curve_to(bottom_right - curve_width, bottom_right);
2655                }
2656
2657                let bottom_left = vec2f(line.start_x, bottom_right.y());
2658                path.line_to(bottom_left + curve_width);
2659                if self.corner_radius > 0. {
2660                    path.curve_to(bottom_left - curve_height, bottom_left);
2661                }
2662            }
2663        }
2664
2665        if first_line.start_x > last_line.start_x {
2666            let curve_width = curve_width(last_line.start_x, first_line.start_x);
2667            let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
2668            path.line_to(second_top_left + curve_height);
2669            if self.corner_radius > 0. {
2670                path.curve_to(second_top_left + curve_width, second_top_left);
2671            }
2672            let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
2673            path.line_to(first_bottom_left - curve_width);
2674            if self.corner_radius > 0. {
2675                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
2676            }
2677        }
2678
2679        path.line_to(first_top_left + curve_height);
2680        if self.corner_radius > 0. {
2681            path.curve_to(first_top_left + top_curve_width, first_top_left);
2682        }
2683        path.line_to(first_top_right - top_curve_width);
2684
2685        scene.push_path(path.build(self.color, Some(bounds)));
2686    }
2687}
2688
2689fn position_to_display_point(
2690    position: Vector2F,
2691    text_bounds: RectF,
2692    position_map: &PositionMap,
2693) -> Option<DisplayPoint> {
2694    if text_bounds.contains_point(position) {
2695        let (point, target_point) = position_map.point_for_position(text_bounds, position);
2696        if point == target_point {
2697            Some(point)
2698        } else {
2699            None
2700        }
2701    } else {
2702        None
2703    }
2704}
2705
2706fn range_to_bounds(
2707    range: &Range<DisplayPoint>,
2708    content_origin: Vector2F,
2709    scroll_left: f32,
2710    scroll_top: f32,
2711    visible_row_range: &Range<u32>,
2712    line_end_overshoot: f32,
2713    position_map: &PositionMap,
2714) -> impl Iterator<Item = RectF> {
2715    let mut bounds: SmallVec<[RectF; 1]> = SmallVec::new();
2716
2717    if range.start == range.end {
2718        return bounds.into_iter();
2719    }
2720
2721    let start_row = visible_row_range.start;
2722    let end_row = visible_row_range.end;
2723
2724    let row_range = if range.end.column() == 0 {
2725        cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
2726    } else {
2727        cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
2728    };
2729
2730    let first_y =
2731        content_origin.y() + row_range.start as f32 * position_map.line_height - scroll_top;
2732
2733    for (idx, row) in row_range.enumerate() {
2734        let line_layout = &position_map.line_layouts[(row - start_row) as usize].line;
2735
2736        let start_x = if row == range.start.row() {
2737            content_origin.x() + line_layout.x_for_index(range.start.column() as usize)
2738                - scroll_left
2739        } else {
2740            content_origin.x() - scroll_left
2741        };
2742
2743        let end_x = if row == range.end.row() {
2744            content_origin.x() + line_layout.x_for_index(range.end.column() as usize) - scroll_left
2745        } else {
2746            content_origin.x() + line_layout.width() + line_end_overshoot - scroll_left
2747        };
2748
2749        bounds.push(RectF::from_points(
2750            vec2f(start_x, first_y + position_map.line_height * idx as f32),
2751            vec2f(end_x, first_y + position_map.line_height * (idx + 1) as f32),
2752        ))
2753    }
2754
2755    bounds.into_iter()
2756}
2757
2758pub fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
2759    delta.powf(1.5) / 100.0
2760}
2761
2762fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
2763    delta.powf(1.2) / 300.0
2764}
2765
2766#[cfg(test)]
2767mod tests {
2768    use super::*;
2769    use crate::{
2770        display_map::{BlockDisposition, BlockProperties},
2771        Editor, MultiBuffer,
2772    };
2773    use gpui::TestAppContext;
2774    use log::info;
2775    use settings::Settings;
2776    use std::{num::NonZeroU32, sync::Arc};
2777    use util::test::sample_text;
2778
2779    #[gpui::test]
2780    fn test_layout_line_numbers(cx: &mut TestAppContext) {
2781        cx.update(|cx| cx.set_global(Settings::test(cx)));
2782        let (_, editor) = cx.add_window(|cx| {
2783            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
2784            Editor::new(EditorMode::Full, buffer, None, None, cx)
2785        });
2786        let element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
2787
2788        let layouts = editor.update(cx, |editor, cx| {
2789            let snapshot = editor.snapshot(cx);
2790            element
2791                .layout_line_numbers(0..6, &Default::default(), false, &snapshot, cx)
2792                .0
2793        });
2794        assert_eq!(layouts.len(), 6);
2795    }
2796
2797    #[gpui::test]
2798    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
2799        cx.update(|cx| cx.set_global(Settings::test(cx)));
2800        let (_, editor) = cx.add_window(|cx| {
2801            let buffer = MultiBuffer::build_simple("", cx);
2802            Editor::new(EditorMode::Full, buffer, None, None, cx)
2803        });
2804
2805        editor.update(cx, |editor, cx| {
2806            editor.set_placeholder_text("hello", cx);
2807            editor.insert_blocks(
2808                [BlockProperties {
2809                    style: BlockStyle::Fixed,
2810                    disposition: BlockDisposition::Above,
2811                    height: 3,
2812                    position: Anchor::min(),
2813                    render: Arc::new(|_| Empty::new().into_any()),
2814                }],
2815                cx,
2816            );
2817
2818            // Blur the editor so that it displays placeholder text.
2819            cx.blur();
2820        });
2821
2822        let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
2823        let (size, mut state) = editor.update(cx, |editor, cx| {
2824            let mut new_parents = Default::default();
2825            let mut notify_views_if_parents_change = Default::default();
2826            let mut layout_cx = LayoutContext::new(
2827                cx,
2828                &mut new_parents,
2829                &mut notify_views_if_parents_change,
2830                false,
2831            );
2832            element.layout(
2833                SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
2834                editor,
2835                &mut layout_cx,
2836            )
2837        });
2838
2839        assert_eq!(state.position_map.line_layouts.len(), 4);
2840        assert_eq!(
2841            state
2842                .line_number_layouts
2843                .iter()
2844                .map(Option::is_some)
2845                .collect::<Vec<_>>(),
2846            &[false, false, false, true]
2847        );
2848
2849        // Don't panic.
2850        let mut scene = SceneBuilder::new(1.0);
2851        let bounds = RectF::new(Default::default(), size);
2852        editor.update(cx, |editor, cx| {
2853            element.paint(&mut scene, bounds, bounds, &mut state, editor, cx);
2854        });
2855    }
2856
2857    #[gpui::test]
2858    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
2859        let tab_size = 4;
2860        let input_text = "\t \t|\t| a b";
2861        let expected_invisibles = vec![
2862            Invisible::Tab {
2863                line_start_offset: 0,
2864            },
2865            Invisible::Whitespace {
2866                line_offset: tab_size as usize,
2867            },
2868            Invisible::Tab {
2869                line_start_offset: tab_size as usize + 1,
2870            },
2871            Invisible::Tab {
2872                line_start_offset: tab_size as usize * 2 + 1,
2873            },
2874            Invisible::Whitespace {
2875                line_offset: tab_size as usize * 3 + 1,
2876            },
2877            Invisible::Whitespace {
2878                line_offset: tab_size as usize * 3 + 3,
2879            },
2880        ];
2881        assert_eq!(
2882            expected_invisibles.len(),
2883            input_text
2884                .chars()
2885                .filter(|initial_char| initial_char.is_whitespace())
2886                .count(),
2887            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
2888        );
2889
2890        cx.update(|cx| {
2891            let mut test_settings = Settings::test(cx);
2892            test_settings.editor_defaults.show_whitespaces = Some(ShowWhitespaces::All);
2893            test_settings.editor_defaults.tab_size = Some(NonZeroU32::new(tab_size).unwrap());
2894            cx.set_global(test_settings);
2895        });
2896        let actual_invisibles =
2897            collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, 500.0);
2898
2899        assert_eq!(expected_invisibles, actual_invisibles);
2900    }
2901
2902    #[gpui::test]
2903    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
2904        cx.update(|cx| {
2905            let mut test_settings = Settings::test(cx);
2906            test_settings.editor_defaults.show_whitespaces = Some(ShowWhitespaces::All);
2907            test_settings.editor_defaults.tab_size = Some(NonZeroU32::new(4).unwrap());
2908            cx.set_global(test_settings);
2909        });
2910
2911        for editor_mode_without_invisibles in [
2912            EditorMode::SingleLine,
2913            EditorMode::AutoHeight { max_lines: 100 },
2914        ] {
2915            let invisibles = collect_invisibles_from_new_editor(
2916                cx,
2917                editor_mode_without_invisibles,
2918                "\t\t\t| | a b",
2919                500.0,
2920            );
2921            assert!(invisibles.is_empty(),
2922                "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
2923        }
2924    }
2925
2926    #[gpui::test]
2927    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
2928        let tab_size = 4;
2929        let input_text = "a\tbcd   ".repeat(9);
2930        let repeated_invisibles = [
2931            Invisible::Tab {
2932                line_start_offset: 1,
2933            },
2934            Invisible::Whitespace {
2935                line_offset: tab_size as usize + 3,
2936            },
2937            Invisible::Whitespace {
2938                line_offset: tab_size as usize + 4,
2939            },
2940            Invisible::Whitespace {
2941                line_offset: tab_size as usize + 5,
2942            },
2943        ];
2944        let expected_invisibles = std::iter::once(repeated_invisibles)
2945            .cycle()
2946            .take(9)
2947            .flatten()
2948            .collect::<Vec<_>>();
2949        assert_eq!(
2950            expected_invisibles.len(),
2951            input_text
2952                .chars()
2953                .filter(|initial_char| initial_char.is_whitespace())
2954                .count(),
2955            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
2956        );
2957        info!("Expected invisibles: {expected_invisibles:?}");
2958
2959        // Put the same string with repeating whitespace pattern into editors of various size,
2960        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
2961        let resize_step = 10.0;
2962        let mut editor_width = 200.0;
2963        while editor_width <= 1000.0 {
2964            cx.update(|cx| {
2965                let mut test_settings = Settings::test(cx);
2966                test_settings.editor_defaults.tab_size = Some(NonZeroU32::new(tab_size).unwrap());
2967                test_settings.editor_defaults.show_whitespaces = Some(ShowWhitespaces::All);
2968                test_settings.editor_defaults.preferred_line_length = Some(editor_width as u32);
2969                test_settings.editor_defaults.soft_wrap =
2970                    Some(settings::SoftWrap::PreferredLineLength);
2971                cx.set_global(test_settings);
2972            });
2973
2974            let actual_invisibles =
2975                collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, editor_width);
2976
2977            // Whatever the editor size is, ensure it has the same invisible kinds in the same order
2978            // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
2979            let mut i = 0;
2980            for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
2981                i = actual_index;
2982                match expected_invisibles.get(i) {
2983                    Some(expected_invisible) => match (expected_invisible, actual_invisible) {
2984                        (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
2985                        | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
2986                        _ => {
2987                            panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
2988                        }
2989                    },
2990                    None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
2991                }
2992            }
2993            let missing_expected_invisibles = &expected_invisibles[i + 1..];
2994            assert!(
2995                missing_expected_invisibles.is_empty(),
2996                "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
2997            );
2998
2999            editor_width += resize_step;
3000        }
3001    }
3002
3003    fn collect_invisibles_from_new_editor(
3004        cx: &mut TestAppContext,
3005        editor_mode: EditorMode,
3006        input_text: &str,
3007        editor_width: f32,
3008    ) -> Vec<Invisible> {
3009        info!(
3010            "Creating editor with mode {editor_mode:?}, witdh {editor_width} and text '{input_text}'"
3011        );
3012        let (_, editor) = cx.add_window(|cx| {
3013            let buffer = MultiBuffer::build_simple(&input_text, cx);
3014            Editor::new(editor_mode, buffer, None, None, cx)
3015        });
3016
3017        let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3018        let (_, layout_state) = editor.update(cx, |editor, cx| {
3019            editor.set_soft_wrap_mode(settings::SoftWrap::EditorWidth, cx);
3020            editor.set_wrap_width(Some(editor_width), cx);
3021
3022            let mut new_parents = Default::default();
3023            let mut notify_views_if_parents_change = Default::default();
3024            let mut layout_cx = LayoutContext::new(
3025                cx,
3026                &mut new_parents,
3027                &mut notify_views_if_parents_change,
3028                false,
3029            );
3030            element.layout(
3031                SizeConstraint::new(vec2f(editor_width, 500.), vec2f(editor_width, 500.)),
3032                editor,
3033                &mut layout_cx,
3034            )
3035        });
3036
3037        layout_state
3038            .position_map
3039            .line_layouts
3040            .iter()
3041            .map(|line_with_invisibles| &line_with_invisibles.invisibles)
3042            .flatten()
3043            .cloned()
3044            .collect()
3045    }
3046}