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