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