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