element.rs

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