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