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                    // highlight the last character in a selection
 854                    if CursorShape::Block == selection.cursor_shape
 855                        && !selection.range.is_empty()
 856                        && !selection.reversed
 857                    {
 858                        if cursor_column > 0 {
 859                            cursor_column -= 1;
 860                        } else if cursor_row > 0
 861                            && cursor_position != layout.position_map.snapshot.max_point()
 862                        {
 863                            cursor_row -= 1;
 864                            cursor_column =
 865                                layout.position_map.snapshot.line_len(cursor_row) as usize;
 866                        }
 867                    }
 868
 869                    if layout.visible_display_row_range.contains(&cursor_row) {
 870                        let cursor_row_layout = &layout.position_map.line_layouts
 871                            [(cursor_row - start_row) as usize]
 872                            .line;
 873
 874                        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 875                        let mut block_width =
 876                            cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
 877                        if block_width == 0.0 {
 878                            block_width = layout.position_map.em_width;
 879                        }
 880                        let block_text = if let CursorShape::Block = selection.cursor_shape {
 881                            layout
 882                                .position_map
 883                                .snapshot
 884                                .chars_at(DisplayPoint::new(
 885                                    cursor_row as u32,
 886                                    cursor_column as u32,
 887                                ))
 888                                .next()
 889                                .and_then(|(character, _)| {
 890                                    let font_id =
 891                                        cursor_row_layout.font_for_index(cursor_column)?;
 892                                    let text = character.to_string();
 893
 894                                    Some(cx.text_layout_cache().layout_str(
 895                                        &text,
 896                                        cursor_row_layout.font_size(),
 897                                        &[(
 898                                            text.len(),
 899                                            RunStyle {
 900                                                font_id,
 901                                                color: style.background,
 902                                                underline: Default::default(),
 903                                            },
 904                                        )],
 905                                    ))
 906                                })
 907                        } else {
 908                            None
 909                        };
 910
 911                        let x = cursor_character_x - scroll_left;
 912                        let y = cursor_row as f32 * layout.position_map.line_height - scroll_top;
 913                        if selection.is_newest {
 914                            editor.pixel_position_of_newest_cursor = Some(vec2f(
 915                                bounds.origin_x() + x + block_width / 2.,
 916                                bounds.origin_y() + y + layout.position_map.line_height / 2.,
 917                            ));
 918                        }
 919                        cursors.push(Cursor {
 920                            color: selection_style.cursor,
 921                            block_width,
 922                            origin: vec2f(x, y),
 923                            line_height: layout.position_map.line_height,
 924                            shape: selection.cursor_shape,
 925                            block_text,
 926                        });
 927                    }
 928                }
 929            }
 930        }
 931
 932        if let Some(visible_text_bounds) = bounds.intersection(visible_bounds) {
 933            for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
 934                let row = start_row + ix as u32;
 935                line_with_invisibles.draw(
 936                    layout,
 937                    row,
 938                    scroll_top,
 939                    scene,
 940                    content_origin,
 941                    scroll_left,
 942                    visible_text_bounds,
 943                    whitespace_setting,
 944                    &invisible_display_ranges,
 945                    visible_bounds,
 946                    cx,
 947                )
 948            }
 949        }
 950
 951        scene.paint_layer(Some(bounds), |scene| {
 952            for cursor in cursors {
 953                cursor.paint(scene, content_origin, cx);
 954            }
 955        });
 956
 957        if let Some((position, context_menu)) = layout.context_menu.as_mut() {
 958            scene.push_stacking_context(None, None);
 959            let cursor_row_layout =
 960                &layout.position_map.line_layouts[(position.row() - start_row) as usize].line;
 961            let x = cursor_row_layout.x_for_index(position.column() as usize) - scroll_left;
 962            let y = (position.row() + 1) as f32 * layout.position_map.line_height - scroll_top;
 963            let mut list_origin = content_origin + vec2f(x, y);
 964            let list_width = context_menu.size().x();
 965            let list_height = context_menu.size().y();
 966
 967            // Snap the right edge of the list to the right edge of the window if
 968            // its horizontal bounds overflow.
 969            if list_origin.x() + list_width > cx.window_size().x() {
 970                list_origin.set_x((cx.window_size().x() - list_width).max(0.));
 971            }
 972
 973            if list_origin.y() + list_height > bounds.max_y() {
 974                list_origin.set_y(list_origin.y() - layout.position_map.line_height - list_height);
 975            }
 976
 977            context_menu.paint(
 978                scene,
 979                list_origin,
 980                RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
 981                editor,
 982                cx,
 983            );
 984
 985            scene.pop_stacking_context();
 986        }
 987
 988        if let Some((position, hover_popovers)) = layout.hover_popovers.as_mut() {
 989            scene.push_stacking_context(None, None);
 990
 991            // This is safe because we check on layout whether the required row is available
 992            let hovered_row_layout =
 993                &layout.position_map.line_layouts[(position.row() - start_row) as usize].line;
 994
 995            // Minimum required size: Take the first popover, and add 1.5 times the minimum popover
 996            // height. This is the size we will use to decide whether to render popovers above or below
 997            // the hovered line.
 998            let first_size = hover_popovers[0].size();
 999            let height_to_reserve = first_size.y()
1000                + 1.5 * MIN_POPOVER_LINE_HEIGHT as f32 * layout.position_map.line_height;
1001
1002            // Compute Hovered Point
1003            let x = hovered_row_layout.x_for_index(position.column() as usize) - scroll_left;
1004            let y = position.row() as f32 * layout.position_map.line_height - scroll_top;
1005            let hovered_point = content_origin + vec2f(x, y);
1006
1007            if hovered_point.y() - height_to_reserve > 0.0 {
1008                // There is enough space above. Render popovers above the hovered point
1009                let mut current_y = hovered_point.y();
1010                for hover_popover in hover_popovers {
1011                    let size = hover_popover.size();
1012                    let mut popover_origin = vec2f(hovered_point.x(), current_y - size.y());
1013
1014                    let x_out_of_bounds = bounds.max_x() - (popover_origin.x() + size.x());
1015                    if x_out_of_bounds < 0.0 {
1016                        popover_origin.set_x(popover_origin.x() + x_out_of_bounds);
1017                    }
1018
1019                    hover_popover.paint(
1020                        scene,
1021                        popover_origin,
1022                        RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
1023                        editor,
1024                        cx,
1025                    );
1026
1027                    current_y = popover_origin.y() - HOVER_POPOVER_GAP;
1028                }
1029            } else {
1030                // There is not enough space above. Render popovers below the hovered point
1031                let mut current_y = hovered_point.y() + layout.position_map.line_height;
1032                for hover_popover in hover_popovers {
1033                    let size = hover_popover.size();
1034                    let mut popover_origin = vec2f(hovered_point.x(), current_y);
1035
1036                    let x_out_of_bounds = bounds.max_x() - (popover_origin.x() + size.x());
1037                    if x_out_of_bounds < 0.0 {
1038                        popover_origin.set_x(popover_origin.x() + x_out_of_bounds);
1039                    }
1040
1041                    hover_popover.paint(
1042                        scene,
1043                        popover_origin,
1044                        RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
1045                        editor,
1046                        cx,
1047                    );
1048
1049                    current_y = popover_origin.y() + size.y() + HOVER_POPOVER_GAP;
1050                }
1051            }
1052
1053            scene.pop_stacking_context();
1054        }
1055
1056        scene.pop_layer();
1057    }
1058
1059    fn paint_scrollbar(
1060        &mut self,
1061        scene: &mut SceneBuilder,
1062        bounds: RectF,
1063        layout: &mut LayoutState,
1064        cx: &mut ViewContext<Editor>,
1065        editor: &Editor,
1066    ) {
1067        enum ScrollbarMouseHandlers {}
1068        if layout.mode != EditorMode::Full {
1069            return;
1070        }
1071
1072        let style = &self.style.theme.scrollbar;
1073
1074        let top = bounds.min_y();
1075        let bottom = bounds.max_y();
1076        let right = bounds.max_x();
1077        let left = right - style.width;
1078        let row_range = &layout.scrollbar_row_range;
1079        let max_row = layout.max_row as f32 + (row_range.end - row_range.start);
1080
1081        let mut height = bounds.height();
1082        let mut first_row_y_offset = 0.0;
1083
1084        // Impose a minimum height on the scrollbar thumb
1085        let row_height = height / max_row;
1086        let min_thumb_height =
1087            style.min_height_factor * cx.font_cache.line_height(self.style.text.font_size);
1088        let thumb_height = (row_range.end - row_range.start) * row_height;
1089        if thumb_height < min_thumb_height {
1090            first_row_y_offset = (min_thumb_height - thumb_height) / 2.0;
1091            height -= min_thumb_height - thumb_height;
1092        }
1093
1094        let y_for_row = |row: f32| -> f32 { top + first_row_y_offset + row * row_height };
1095
1096        let thumb_top = y_for_row(row_range.start) - first_row_y_offset;
1097        let thumb_bottom = y_for_row(row_range.end) + first_row_y_offset;
1098        let track_bounds = RectF::from_points(vec2f(left, top), vec2f(right, bottom));
1099        let thumb_bounds = RectF::from_points(vec2f(left, thumb_top), vec2f(right, thumb_bottom));
1100
1101        if layout.show_scrollbars {
1102            scene.push_quad(Quad {
1103                bounds: track_bounds,
1104                border: style.track.border,
1105                background: style.track.background_color,
1106                ..Default::default()
1107            });
1108            let scrollbar_settings = settings::get::<EditorSettings>(cx).scrollbar;
1109            let theme = theme::current(cx);
1110            let scrollbar_theme = &theme.editor.scrollbar;
1111            if layout.is_singleton && scrollbar_settings.selections {
1112                let start_anchor = Anchor::min();
1113                let end_anchor = Anchor::max();
1114                let mut start_row = None;
1115                let mut end_row = None;
1116                let color = scrollbar_theme.selections;
1117                let border = Border {
1118                    width: 1.,
1119                    color: style.thumb.border.color,
1120                    overlay: false,
1121                    top: false,
1122                    right: true,
1123                    bottom: false,
1124                    left: true,
1125                };
1126                let mut push_region = |start, end| {
1127                    if let (Some(start_display), Some(end_display)) = (start, end) {
1128                        let start_y = y_for_row(start_display as f32);
1129                        let mut end_y = y_for_row(end_display as f32);
1130                        if end_y - start_y < 1. {
1131                            end_y = start_y + 1.;
1132                        }
1133                        let bounds = RectF::from_points(vec2f(left, start_y), vec2f(right, end_y));
1134
1135                        scene.push_quad(Quad {
1136                            bounds,
1137                            background: Some(color),
1138                            border,
1139                            corner_radius: style.thumb.corner_radius,
1140                        })
1141                    }
1142                };
1143                for (row, _) in &editor
1144                    .background_highlights_in_range_for::<crate::items::BufferSearchHighlights>(
1145                        start_anchor..end_anchor,
1146                        &layout.position_map.snapshot,
1147                        &theme,
1148                    )
1149                {
1150                    let start_display = row.start;
1151                    let end_display = row.end;
1152
1153                    if start_row.is_none() {
1154                        assert_eq!(end_row, None);
1155                        start_row = Some(start_display.row());
1156                        end_row = Some(end_display.row());
1157                        continue;
1158                    }
1159                    if let Some(current_end) = end_row.as_mut() {
1160                        if start_display.row() > *current_end + 1 {
1161                            push_region(start_row, end_row);
1162                            start_row = Some(start_display.row());
1163                            end_row = Some(end_display.row());
1164                        } else {
1165                            // Merge two hunks.
1166                            *current_end = end_display.row();
1167                        }
1168                    } else {
1169                        unreachable!();
1170                    }
1171                }
1172                // We might still have a hunk that was not rendered (if there was a search hit on the last line)
1173                push_region(start_row, end_row);
1174            }
1175
1176            if layout.is_singleton && scrollbar_settings.git_diff {
1177                let diff_style = scrollbar_theme.git.clone();
1178                for hunk in layout
1179                    .position_map
1180                    .snapshot
1181                    .buffer_snapshot
1182                    .git_diff_hunks_in_range(0..(max_row.floor() as u32))
1183                {
1184                    let start_display = Point::new(hunk.buffer_range.start, 0)
1185                        .to_display_point(&layout.position_map.snapshot.display_snapshot);
1186                    let end_display = Point::new(hunk.buffer_range.end, 0)
1187                        .to_display_point(&layout.position_map.snapshot.display_snapshot);
1188                    let start_y = y_for_row(start_display.row() as f32);
1189                    let mut end_y = if hunk.buffer_range.start == hunk.buffer_range.end {
1190                        y_for_row((end_display.row() + 1) as f32)
1191                    } else {
1192                        y_for_row((end_display.row()) as f32)
1193                    };
1194
1195                    if end_y - start_y < 1. {
1196                        end_y = start_y + 1.;
1197                    }
1198                    let bounds = RectF::from_points(vec2f(left, start_y), vec2f(right, end_y));
1199
1200                    let color = match hunk.status() {
1201                        DiffHunkStatus::Added => diff_style.inserted,
1202                        DiffHunkStatus::Modified => diff_style.modified,
1203                        DiffHunkStatus::Removed => diff_style.deleted,
1204                    };
1205
1206                    let border = Border {
1207                        width: 1.,
1208                        color: style.thumb.border.color,
1209                        overlay: false,
1210                        top: false,
1211                        right: true,
1212                        bottom: false,
1213                        left: true,
1214                    };
1215
1216                    scene.push_quad(Quad {
1217                        bounds,
1218                        background: Some(color),
1219                        border,
1220                        corner_radius: style.thumb.corner_radius,
1221                    })
1222                }
1223            }
1224
1225            scene.push_quad(Quad {
1226                bounds: thumb_bounds,
1227                border: style.thumb.border,
1228                background: style.thumb.background_color,
1229                corner_radius: style.thumb.corner_radius,
1230            });
1231        }
1232
1233        scene.push_cursor_region(CursorRegion {
1234            bounds: track_bounds,
1235            style: CursorStyle::Arrow,
1236        });
1237        scene.push_mouse_region(
1238            MouseRegion::new::<ScrollbarMouseHandlers>(cx.view_id(), cx.view_id(), track_bounds)
1239                .on_move(move |event, editor: &mut Editor, cx| {
1240                    if event.pressed_button.is_none() {
1241                        editor.scroll_manager.show_scrollbar(cx);
1242                    }
1243                })
1244                .on_down(MouseButton::Left, {
1245                    let row_range = row_range.clone();
1246                    move |event, editor: &mut Editor, cx| {
1247                        let y = event.position.y();
1248                        if y < thumb_top || thumb_bottom < y {
1249                            let center_row = ((y - top) * max_row as f32 / height).round() as u32;
1250                            let top_row = center_row
1251                                .saturating_sub((row_range.end - row_range.start) as u32 / 2);
1252                            let mut position = editor.scroll_position(cx);
1253                            position.set_y(top_row as f32);
1254                            editor.set_scroll_position(position, cx);
1255                        } else {
1256                            editor.scroll_manager.show_scrollbar(cx);
1257                        }
1258                    }
1259                })
1260                .on_drag(MouseButton::Left, {
1261                    move |event, editor: &mut Editor, cx| {
1262                        if event.end {
1263                            return;
1264                        }
1265
1266                        let y = event.prev_mouse_position.y();
1267                        let new_y = event.position.y();
1268                        if thumb_top < y && y < thumb_bottom {
1269                            let mut position = editor.scroll_position(cx);
1270                            position.set_y(position.y() + (new_y - y) * (max_row as f32) / height);
1271                            if position.y() < 0.0 {
1272                                position.set_y(0.);
1273                            }
1274                            editor.set_scroll_position(position, cx);
1275                        }
1276                    }
1277                }),
1278        );
1279    }
1280
1281    #[allow(clippy::too_many_arguments)]
1282    fn paint_highlighted_range(
1283        &self,
1284        scene: &mut SceneBuilder,
1285        range: Range<DisplayPoint>,
1286        color: Color,
1287        corner_radius: f32,
1288        line_end_overshoot: f32,
1289        layout: &LayoutState,
1290        content_origin: Vector2F,
1291        scroll_top: f32,
1292        scroll_left: f32,
1293        bounds: RectF,
1294    ) {
1295        let start_row = layout.visible_display_row_range.start;
1296        let end_row = layout.visible_display_row_range.end;
1297        if range.start != range.end {
1298            let row_range = if range.end.column() == 0 {
1299                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
1300            } else {
1301                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
1302            };
1303
1304            let highlighted_range = HighlightedRange {
1305                color,
1306                line_height: layout.position_map.line_height,
1307                corner_radius,
1308                start_y: content_origin.y()
1309                    + row_range.start as f32 * layout.position_map.line_height
1310                    - scroll_top,
1311                lines: row_range
1312                    .into_iter()
1313                    .map(|row| {
1314                        let line_layout =
1315                            &layout.position_map.line_layouts[(row - start_row) as usize].line;
1316                        HighlightedRangeLine {
1317                            start_x: if row == range.start.row() {
1318                                content_origin.x()
1319                                    + line_layout.x_for_index(range.start.column() as usize)
1320                                    - scroll_left
1321                            } else {
1322                                content_origin.x() - scroll_left
1323                            },
1324                            end_x: if row == range.end.row() {
1325                                content_origin.x()
1326                                    + line_layout.x_for_index(range.end.column() as usize)
1327                                    - scroll_left
1328                            } else {
1329                                content_origin.x() + line_layout.width() + line_end_overshoot
1330                                    - scroll_left
1331                            },
1332                        }
1333                    })
1334                    .collect(),
1335            };
1336
1337            highlighted_range.paint(bounds, scene);
1338        }
1339    }
1340
1341    fn paint_blocks(
1342        &mut self,
1343        scene: &mut SceneBuilder,
1344        bounds: RectF,
1345        visible_bounds: RectF,
1346        layout: &mut LayoutState,
1347        editor: &mut Editor,
1348        cx: &mut ViewContext<Editor>,
1349    ) {
1350        let scroll_position = layout.position_map.snapshot.scroll_position();
1351        let scroll_left = scroll_position.x() * layout.position_map.em_width;
1352        let scroll_top = scroll_position.y() * layout.position_map.line_height;
1353
1354        for block in &mut layout.blocks {
1355            let mut origin = bounds.origin()
1356                + vec2f(
1357                    0.,
1358                    block.row as f32 * layout.position_map.line_height - scroll_top,
1359                );
1360            if !matches!(block.style, BlockStyle::Sticky) {
1361                origin += vec2f(-scroll_left, 0.);
1362            }
1363            block
1364                .element
1365                .paint(scene, origin, visible_bounds, editor, cx);
1366        }
1367    }
1368
1369    fn column_pixels(&self, column: usize, cx: &ViewContext<Editor>) -> f32 {
1370        let style = &self.style;
1371
1372        cx.text_layout_cache()
1373            .layout_str(
1374                " ".repeat(column).as_str(),
1375                style.text.font_size,
1376                &[(
1377                    column,
1378                    RunStyle {
1379                        font_id: style.text.font_id,
1380                        color: Color::black(),
1381                        underline: Default::default(),
1382                    },
1383                )],
1384            )
1385            .width()
1386    }
1387
1388    fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &ViewContext<Editor>) -> f32 {
1389        let digit_count = (snapshot.max_buffer_row() as f32 + 1.).log10().floor() as usize + 1;
1390        self.column_pixels(digit_count, cx)
1391    }
1392
1393    //Folds contained in a hunk are ignored apart from shrinking visual size
1394    //If a fold contains any hunks then that fold line is marked as modified
1395    fn layout_git_gutters(
1396        &self,
1397        display_rows: Range<u32>,
1398        snapshot: &EditorSnapshot,
1399    ) -> Vec<DisplayDiffHunk> {
1400        let buffer_snapshot = &snapshot.buffer_snapshot;
1401
1402        let buffer_start_row = DisplayPoint::new(display_rows.start, 0)
1403            .to_point(snapshot)
1404            .row;
1405        let buffer_end_row = DisplayPoint::new(display_rows.end, 0)
1406            .to_point(snapshot)
1407            .row;
1408
1409        buffer_snapshot
1410            .git_diff_hunks_in_range(buffer_start_row..buffer_end_row)
1411            .map(|hunk| diff_hunk_to_display(hunk, snapshot))
1412            .dedup()
1413            .collect()
1414    }
1415
1416    fn layout_line_numbers(
1417        &self,
1418        rows: Range<u32>,
1419        active_rows: &BTreeMap<u32, bool>,
1420        is_singleton: bool,
1421        snapshot: &EditorSnapshot,
1422        cx: &ViewContext<Editor>,
1423    ) -> (
1424        Vec<Option<text_layout::Line>>,
1425        Vec<Option<(FoldStatus, BufferRow, bool)>>,
1426    ) {
1427        let style = &self.style;
1428        let include_line_numbers = snapshot.mode == EditorMode::Full;
1429        let mut line_number_layouts = Vec::with_capacity(rows.len());
1430        let mut fold_statuses = Vec::with_capacity(rows.len());
1431        let mut line_number = String::new();
1432        for (ix, row) in snapshot
1433            .buffer_rows(rows.start)
1434            .take((rows.end - rows.start) as usize)
1435            .enumerate()
1436        {
1437            let display_row = rows.start + ix as u32;
1438            let (active, color) = if active_rows.contains_key(&display_row) {
1439                (true, style.line_number_active)
1440            } else {
1441                (false, style.line_number)
1442            };
1443            if let Some(buffer_row) = row {
1444                if include_line_numbers {
1445                    line_number.clear();
1446                    write!(&mut line_number, "{}", buffer_row + 1).unwrap();
1447                    line_number_layouts.push(Some(cx.text_layout_cache().layout_str(
1448                        &line_number,
1449                        style.text.font_size,
1450                        &[(
1451                            line_number.len(),
1452                            RunStyle {
1453                                font_id: style.text.font_id,
1454                                color,
1455                                underline: Default::default(),
1456                            },
1457                        )],
1458                    )));
1459                    fold_statuses.push(
1460                        is_singleton
1461                            .then(|| {
1462                                snapshot
1463                                    .fold_for_line(buffer_row)
1464                                    .map(|fold_status| (fold_status, buffer_row, active))
1465                            })
1466                            .flatten(),
1467                    )
1468                }
1469            } else {
1470                fold_statuses.push(None);
1471                line_number_layouts.push(None);
1472            }
1473        }
1474
1475        (line_number_layouts, fold_statuses)
1476    }
1477
1478    fn layout_lines(
1479        &mut self,
1480        rows: Range<u32>,
1481        line_number_layouts: &[Option<Line>],
1482        snapshot: &EditorSnapshot,
1483        cx: &ViewContext<Editor>,
1484    ) -> Vec<LineWithInvisibles> {
1485        if rows.start >= rows.end {
1486            return Vec::new();
1487        }
1488
1489        // When the editor is empty and unfocused, then show the placeholder.
1490        if snapshot.is_empty() {
1491            let placeholder_style = self
1492                .style
1493                .placeholder_text
1494                .as_ref()
1495                .unwrap_or(&self.style.text);
1496            let placeholder_text = snapshot.placeholder_text();
1497            let placeholder_lines = placeholder_text
1498                .as_ref()
1499                .map_or("", AsRef::as_ref)
1500                .split('\n')
1501                .skip(rows.start as usize)
1502                .chain(iter::repeat(""))
1503                .take(rows.len());
1504            placeholder_lines
1505                .map(|line| {
1506                    cx.text_layout_cache().layout_str(
1507                        line,
1508                        placeholder_style.font_size,
1509                        &[(
1510                            line.len(),
1511                            RunStyle {
1512                                font_id: placeholder_style.font_id,
1513                                color: placeholder_style.color,
1514                                underline: Default::default(),
1515                            },
1516                        )],
1517                    )
1518                })
1519                .map(|line| LineWithInvisibles {
1520                    line,
1521                    invisibles: Vec::new(),
1522                })
1523                .collect()
1524        } else {
1525            let style = &self.style;
1526            let chunks = snapshot
1527                .chunks(
1528                    rows.clone(),
1529                    true,
1530                    Some(style.theme.hint),
1531                    Some(style.theme.suggestion),
1532                )
1533                .map(|chunk| {
1534                    let mut highlight_style = chunk
1535                        .syntax_highlight_id
1536                        .and_then(|id| id.style(&style.syntax));
1537
1538                    if let Some(chunk_highlight) = chunk.highlight_style {
1539                        if let Some(highlight_style) = highlight_style.as_mut() {
1540                            highlight_style.highlight(chunk_highlight);
1541                        } else {
1542                            highlight_style = Some(chunk_highlight);
1543                        }
1544                    }
1545
1546                    let mut diagnostic_highlight = HighlightStyle::default();
1547
1548                    if chunk.is_unnecessary {
1549                        diagnostic_highlight.fade_out = Some(style.unnecessary_code_fade);
1550                    }
1551
1552                    if let Some(severity) = chunk.diagnostic_severity {
1553                        // Omit underlines for HINT/INFO diagnostics on 'unnecessary' code.
1554                        if severity <= DiagnosticSeverity::WARNING || !chunk.is_unnecessary {
1555                            let diagnostic_style = super::diagnostic_style(severity, true, style);
1556                            diagnostic_highlight.underline = Some(Underline {
1557                                color: Some(diagnostic_style.message.text.color),
1558                                thickness: 1.0.into(),
1559                                squiggly: true,
1560                            });
1561                        }
1562                    }
1563
1564                    if let Some(highlight_style) = highlight_style.as_mut() {
1565                        highlight_style.highlight(diagnostic_highlight);
1566                    } else {
1567                        highlight_style = Some(diagnostic_highlight);
1568                    }
1569
1570                    HighlightedChunk {
1571                        chunk: chunk.text,
1572                        style: highlight_style,
1573                        is_tab: chunk.is_tab,
1574                    }
1575                });
1576
1577            LineWithInvisibles::from_chunks(
1578                chunks,
1579                &style.text,
1580                cx.text_layout_cache(),
1581                cx.font_cache(),
1582                MAX_LINE_LEN,
1583                rows.len() as usize,
1584                line_number_layouts,
1585                snapshot.mode,
1586            )
1587        }
1588    }
1589
1590    #[allow(clippy::too_many_arguments)]
1591    fn layout_blocks(
1592        &mut self,
1593        rows: Range<u32>,
1594        snapshot: &EditorSnapshot,
1595        editor_width: f32,
1596        scroll_width: f32,
1597        gutter_padding: f32,
1598        gutter_width: f32,
1599        em_width: f32,
1600        text_x: f32,
1601        line_height: f32,
1602        style: &EditorStyle,
1603        line_layouts: &[LineWithInvisibles],
1604        editor: &mut Editor,
1605        cx: &mut LayoutContext<Editor>,
1606    ) -> (f32, Vec<BlockLayout>) {
1607        let mut block_id = 0;
1608        let scroll_x = snapshot.scroll_anchor.offset.x();
1609        let (fixed_blocks, non_fixed_blocks) = snapshot
1610            .blocks_in_range(rows.clone())
1611            .partition::<Vec<_>, _>(|(_, block)| match block {
1612                TransformBlock::ExcerptHeader { .. } => false,
1613                TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
1614            });
1615        let mut render_block = |block: &TransformBlock, width: f32, block_id: usize| {
1616            let mut element = match block {
1617                TransformBlock::Custom(block) => {
1618                    let align_to = block
1619                        .position()
1620                        .to_point(&snapshot.buffer_snapshot)
1621                        .to_display_point(snapshot);
1622                    let anchor_x = text_x
1623                        + if rows.contains(&align_to.row()) {
1624                            line_layouts[(align_to.row() - rows.start) as usize]
1625                                .line
1626                                .x_for_index(align_to.column() as usize)
1627                        } else {
1628                            layout_line(align_to.row(), snapshot, style, cx.text_layout_cache())
1629                                .x_for_index(align_to.column() as usize)
1630                        };
1631
1632                    block.render(&mut BlockContext {
1633                        view_context: cx,
1634                        anchor_x,
1635                        gutter_padding,
1636                        line_height,
1637                        scroll_x,
1638                        gutter_width,
1639                        em_width,
1640                        block_id,
1641                    })
1642                }
1643                TransformBlock::ExcerptHeader {
1644                    id,
1645                    buffer,
1646                    range,
1647                    starts_new_buffer,
1648                    ..
1649                } => {
1650                    let tooltip_style = theme::current(cx).tooltip.clone();
1651                    let include_root = editor
1652                        .project
1653                        .as_ref()
1654                        .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
1655                        .unwrap_or_default();
1656                    let jump_icon = project::File::from_dyn(buffer.file()).map(|file| {
1657                        let jump_path = ProjectPath {
1658                            worktree_id: file.worktree_id(cx),
1659                            path: file.path.clone(),
1660                        };
1661                        let jump_anchor = range
1662                            .primary
1663                            .as_ref()
1664                            .map_or(range.context.start, |primary| primary.start);
1665                        let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
1666
1667                        enum JumpIcon {}
1668                        MouseEventHandler::<JumpIcon, _>::new((*id).into(), cx, |state, _| {
1669                            let style = style.jump_icon.style_for(state);
1670                            Svg::new("icons/arrow_up_right_8.svg")
1671                                .with_color(style.color)
1672                                .constrained()
1673                                .with_width(style.icon_width)
1674                                .aligned()
1675                                .contained()
1676                                .with_style(style.container)
1677                                .constrained()
1678                                .with_width(style.button_width)
1679                                .with_height(style.button_width)
1680                        })
1681                        .with_cursor_style(CursorStyle::PointingHand)
1682                        .on_click(MouseButton::Left, move |_, editor, cx| {
1683                            if let Some(workspace) = editor
1684                                .workspace
1685                                .as_ref()
1686                                .and_then(|(workspace, _)| workspace.upgrade(cx))
1687                            {
1688                                workspace.update(cx, |workspace, cx| {
1689                                    Editor::jump(
1690                                        workspace,
1691                                        jump_path.clone(),
1692                                        jump_position,
1693                                        jump_anchor,
1694                                        cx,
1695                                    );
1696                                });
1697                            }
1698                        })
1699                        .with_tooltip::<JumpIcon>(
1700                            (*id).into(),
1701                            "Jump to Buffer".to_string(),
1702                            Some(Box::new(crate::OpenExcerpts)),
1703                            tooltip_style.clone(),
1704                            cx,
1705                        )
1706                        .aligned()
1707                        .flex_float()
1708                    });
1709
1710                    if *starts_new_buffer {
1711                        let editor_font_size = style.text.font_size;
1712                        let style = &style.diagnostic_path_header;
1713                        let font_size = (style.text_scale_factor * editor_font_size).round();
1714
1715                        let path = buffer.resolve_file_path(cx, include_root);
1716                        let mut filename = None;
1717                        let mut parent_path = None;
1718                        // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
1719                        if let Some(path) = path {
1720                            filename = path.file_name().map(|f| f.to_string_lossy().to_string());
1721                            parent_path =
1722                                path.parent().map(|p| p.to_string_lossy().to_string() + "/");
1723                        }
1724
1725                        Flex::row()
1726                            .with_child(
1727                                Label::new(
1728                                    filename.unwrap_or_else(|| "untitled".to_string()),
1729                                    style.filename.text.clone().with_font_size(font_size),
1730                                )
1731                                .contained()
1732                                .with_style(style.filename.container)
1733                                .aligned(),
1734                            )
1735                            .with_children(parent_path.map(|path| {
1736                                Label::new(path, style.path.text.clone().with_font_size(font_size))
1737                                    .contained()
1738                                    .with_style(style.path.container)
1739                                    .aligned()
1740                            }))
1741                            .with_children(jump_icon)
1742                            .contained()
1743                            .with_style(style.container)
1744                            .with_padding_left(gutter_padding)
1745                            .with_padding_right(gutter_padding)
1746                            .expanded()
1747                            .into_any_named("path header block")
1748                    } else {
1749                        let text_style = style.text.clone();
1750                        Flex::row()
1751                            .with_child(Label::new("", text_style))
1752                            .with_children(jump_icon)
1753                            .contained()
1754                            .with_padding_left(gutter_padding)
1755                            .with_padding_right(gutter_padding)
1756                            .expanded()
1757                            .into_any_named("collapsed context")
1758                    }
1759                }
1760            };
1761
1762            element.layout(
1763                SizeConstraint {
1764                    min: Vector2F::zero(),
1765                    max: vec2f(width, block.height() as f32 * line_height),
1766                },
1767                editor,
1768                cx,
1769            );
1770            element
1771        };
1772
1773        let mut fixed_block_max_width = 0f32;
1774        let mut blocks = Vec::new();
1775        for (row, block) in fixed_blocks {
1776            let element = render_block(block, f32::INFINITY, block_id);
1777            block_id += 1;
1778            fixed_block_max_width = fixed_block_max_width.max(element.size().x() + em_width);
1779            blocks.push(BlockLayout {
1780                row,
1781                element,
1782                style: BlockStyle::Fixed,
1783            });
1784        }
1785        for (row, block) in non_fixed_blocks {
1786            let style = match block {
1787                TransformBlock::Custom(block) => block.style(),
1788                TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
1789            };
1790            let width = match style {
1791                BlockStyle::Sticky => editor_width,
1792                BlockStyle::Flex => editor_width
1793                    .max(fixed_block_max_width)
1794                    .max(gutter_width + scroll_width),
1795                BlockStyle::Fixed => unreachable!(),
1796            };
1797            let element = render_block(block, width, block_id);
1798            block_id += 1;
1799            blocks.push(BlockLayout {
1800                row,
1801                element,
1802                style,
1803            });
1804        }
1805        (
1806            scroll_width.max(fixed_block_max_width - gutter_width),
1807            blocks,
1808        )
1809    }
1810}
1811
1812struct HighlightedChunk<'a> {
1813    chunk: &'a str,
1814    style: Option<HighlightStyle>,
1815    is_tab: bool,
1816}
1817
1818#[derive(Debug)]
1819pub struct LineWithInvisibles {
1820    pub line: Line,
1821    invisibles: Vec<Invisible>,
1822}
1823
1824impl LineWithInvisibles {
1825    fn from_chunks<'a>(
1826        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
1827        text_style: &TextStyle,
1828        text_layout_cache: &TextLayoutCache,
1829        font_cache: &Arc<FontCache>,
1830        max_line_len: usize,
1831        max_line_count: usize,
1832        line_number_layouts: &[Option<Line>],
1833        editor_mode: EditorMode,
1834    ) -> Vec<Self> {
1835        let mut layouts = Vec::with_capacity(max_line_count);
1836        let mut line = String::new();
1837        let mut invisibles = Vec::new();
1838        let mut styles = Vec::new();
1839        let mut non_whitespace_added = false;
1840        let mut row = 0;
1841        let mut line_exceeded_max_len = false;
1842        for highlighted_chunk in chunks.chain([HighlightedChunk {
1843            chunk: "\n",
1844            style: None,
1845            is_tab: false,
1846        }]) {
1847            for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
1848                if ix > 0 {
1849                    layouts.push(Self {
1850                        line: text_layout_cache.layout_str(&line, text_style.font_size, &styles),
1851                        invisibles: invisibles.drain(..).collect(),
1852                    });
1853
1854                    line.clear();
1855                    styles.clear();
1856                    row += 1;
1857                    line_exceeded_max_len = false;
1858                    non_whitespace_added = false;
1859                    if row == max_line_count {
1860                        return layouts;
1861                    }
1862                }
1863
1864                if !line_chunk.is_empty() && !line_exceeded_max_len {
1865                    let text_style = if let Some(style) = highlighted_chunk.style {
1866                        text_style
1867                            .clone()
1868                            .highlight(style, font_cache)
1869                            .map(Cow::Owned)
1870                            .unwrap_or_else(|_| Cow::Borrowed(text_style))
1871                    } else {
1872                        Cow::Borrowed(text_style)
1873                    };
1874
1875                    if line.len() + line_chunk.len() > max_line_len {
1876                        let mut chunk_len = max_line_len - line.len();
1877                        while !line_chunk.is_char_boundary(chunk_len) {
1878                            chunk_len -= 1;
1879                        }
1880                        line_chunk = &line_chunk[..chunk_len];
1881                        line_exceeded_max_len = true;
1882                    }
1883
1884                    styles.push((
1885                        line_chunk.len(),
1886                        RunStyle {
1887                            font_id: text_style.font_id,
1888                            color: text_style.color,
1889                            underline: text_style.underline,
1890                        },
1891                    ));
1892
1893                    if editor_mode == EditorMode::Full {
1894                        // Line wrap pads its contents with fake whitespaces,
1895                        // avoid printing them
1896                        let inside_wrapped_string = line_number_layouts
1897                            .get(row)
1898                            .and_then(|layout| layout.as_ref())
1899                            .is_none();
1900                        if highlighted_chunk.is_tab {
1901                            if non_whitespace_added || !inside_wrapped_string {
1902                                invisibles.push(Invisible::Tab {
1903                                    line_start_offset: line.len(),
1904                                });
1905                            }
1906                        } else {
1907                            invisibles.extend(
1908                                line_chunk
1909                                    .chars()
1910                                    .enumerate()
1911                                    .filter(|(_, line_char)| {
1912                                        let is_whitespace = line_char.is_whitespace();
1913                                        non_whitespace_added |= !is_whitespace;
1914                                        is_whitespace
1915                                            && (non_whitespace_added || !inside_wrapped_string)
1916                                    })
1917                                    .map(|(whitespace_index, _)| Invisible::Whitespace {
1918                                        line_offset: line.len() + whitespace_index,
1919                                    }),
1920                            )
1921                        }
1922                    }
1923
1924                    line.push_str(line_chunk);
1925                }
1926            }
1927        }
1928
1929        layouts
1930    }
1931
1932    fn draw(
1933        &self,
1934        layout: &LayoutState,
1935        row: u32,
1936        scroll_top: f32,
1937        scene: &mut SceneBuilder,
1938        content_origin: Vector2F,
1939        scroll_left: f32,
1940        visible_text_bounds: RectF,
1941        whitespace_setting: ShowWhitespaceSetting,
1942        selection_ranges: &[Range<DisplayPoint>],
1943        visible_bounds: RectF,
1944        cx: &mut ViewContext<Editor>,
1945    ) {
1946        let line_height = layout.position_map.line_height;
1947        let line_y = row as f32 * line_height - scroll_top;
1948
1949        self.line.paint(
1950            scene,
1951            content_origin + vec2f(-scroll_left, line_y),
1952            visible_text_bounds,
1953            line_height,
1954            cx,
1955        );
1956
1957        self.draw_invisibles(
1958            &selection_ranges,
1959            layout,
1960            content_origin,
1961            scroll_left,
1962            line_y,
1963            row,
1964            scene,
1965            visible_bounds,
1966            line_height,
1967            whitespace_setting,
1968            cx,
1969        );
1970    }
1971
1972    fn draw_invisibles(
1973        &self,
1974        selection_ranges: &[Range<DisplayPoint>],
1975        layout: &LayoutState,
1976        content_origin: Vector2F,
1977        scroll_left: f32,
1978        line_y: f32,
1979        row: u32,
1980        scene: &mut SceneBuilder,
1981        visible_bounds: RectF,
1982        line_height: f32,
1983        whitespace_setting: ShowWhitespaceSetting,
1984        cx: &mut ViewContext<Editor>,
1985    ) {
1986        let allowed_invisibles_regions = match whitespace_setting {
1987            ShowWhitespaceSetting::None => return,
1988            ShowWhitespaceSetting::Selection => Some(selection_ranges),
1989            ShowWhitespaceSetting::All => None,
1990        };
1991
1992        for invisible in &self.invisibles {
1993            let (&token_offset, invisible_symbol) = match invisible {
1994                Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
1995                Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
1996            };
1997
1998            let x_offset = self.line.x_for_index(token_offset);
1999            let invisible_offset =
2000                (layout.position_map.em_width - invisible_symbol.width()).max(0.0) / 2.0;
2001            let origin = content_origin + vec2f(-scroll_left + x_offset + invisible_offset, line_y);
2002
2003            if let Some(allowed_regions) = allowed_invisibles_regions {
2004                let invisible_point = DisplayPoint::new(row, token_offset as u32);
2005                if !allowed_regions
2006                    .iter()
2007                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
2008                {
2009                    continue;
2010                }
2011            }
2012            invisible_symbol.paint(scene, origin, visible_bounds, line_height, cx);
2013        }
2014    }
2015}
2016
2017#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2018enum Invisible {
2019    Tab { line_start_offset: usize },
2020    Whitespace { line_offset: usize },
2021}
2022
2023impl Element<Editor> for EditorElement {
2024    type LayoutState = LayoutState;
2025    type PaintState = ();
2026
2027    fn layout(
2028        &mut self,
2029        constraint: SizeConstraint,
2030        editor: &mut Editor,
2031        cx: &mut LayoutContext<Editor>,
2032    ) -> (Vector2F, Self::LayoutState) {
2033        let mut size = constraint.max;
2034        if size.x().is_infinite() {
2035            unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
2036        }
2037
2038        let snapshot = editor.snapshot(cx);
2039        let style = self.style.clone();
2040
2041        let line_height = (style.text.font_size * style.line_height_scalar).round();
2042
2043        let gutter_padding;
2044        let gutter_width;
2045        let gutter_margin;
2046        if snapshot.show_gutter {
2047            let em_width = style.text.em_width(cx.font_cache());
2048            gutter_padding = (em_width * style.gutter_padding_factor).round();
2049            gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
2050            gutter_margin = -style.text.descent(cx.font_cache());
2051        } else {
2052            gutter_padding = 0.0;
2053            gutter_width = 0.0;
2054            gutter_margin = 0.0;
2055        };
2056
2057        let text_width = size.x() - gutter_width;
2058        let em_width = style.text.em_width(cx.font_cache());
2059        let em_advance = style.text.em_advance(cx.font_cache());
2060        let overscroll = vec2f(em_width, 0.);
2061        let snapshot = {
2062            editor.set_visible_line_count(size.y() / line_height, cx);
2063
2064            let editor_width = text_width - gutter_margin - overscroll.x() - em_width;
2065            let wrap_width = match editor.soft_wrap_mode(cx) {
2066                SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
2067                SoftWrap::EditorWidth => editor_width,
2068                SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
2069            };
2070
2071            if editor.set_wrap_width(Some(wrap_width), cx) {
2072                editor.snapshot(cx)
2073            } else {
2074                snapshot
2075            }
2076        };
2077
2078        let wrap_guides = editor
2079            .wrap_guides(cx)
2080            .iter()
2081            .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
2082            .collect();
2083
2084        let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
2085        if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
2086            size.set_y(
2087                scroll_height
2088                    .min(constraint.max_along(Axis::Vertical))
2089                    .max(constraint.min_along(Axis::Vertical))
2090                    .min(line_height * max_lines as f32),
2091            )
2092        } else if let EditorMode::SingleLine = snapshot.mode {
2093            size.set_y(
2094                line_height
2095                    .min(constraint.max_along(Axis::Vertical))
2096                    .max(constraint.min_along(Axis::Vertical)),
2097            )
2098        } else if size.y().is_infinite() {
2099            size.set_y(scroll_height);
2100        }
2101        let gutter_size = vec2f(gutter_width, size.y());
2102        let text_size = vec2f(text_width, size.y());
2103
2104        let autoscroll_horizontally = editor.autoscroll_vertically(size.y(), line_height, cx);
2105        let mut snapshot = editor.snapshot(cx);
2106
2107        let scroll_position = snapshot.scroll_position();
2108        // The scroll position is a fractional point, the whole number of which represents
2109        // the top of the window in terms of display rows.
2110        let start_row = scroll_position.y() as u32;
2111        let height_in_lines = size.y() / line_height;
2112        let max_row = snapshot.max_point().row();
2113
2114        // Add 1 to ensure selections bleed off screen
2115        let end_row = 1 + cmp::min(
2116            (scroll_position.y() + height_in_lines).ceil() as u32,
2117            max_row,
2118        );
2119
2120        let start_anchor = if start_row == 0 {
2121            Anchor::min()
2122        } else {
2123            snapshot
2124                .buffer_snapshot
2125                .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
2126        };
2127        let end_anchor = if end_row > max_row {
2128            Anchor::max()
2129        } else {
2130            snapshot
2131                .buffer_snapshot
2132                .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
2133        };
2134
2135        let mut selections: Vec<(ReplicaId, Vec<SelectionLayout>)> = Vec::new();
2136        let mut active_rows = BTreeMap::new();
2137        let mut fold_ranges = Vec::new();
2138        let is_singleton = editor.is_singleton(cx);
2139
2140        let highlighted_rows = editor.highlighted_rows();
2141        let theme = theme::current(cx);
2142        let highlighted_ranges = editor.background_highlights_in_range(
2143            start_anchor..end_anchor,
2144            &snapshot.display_snapshot,
2145            theme.as_ref(),
2146        );
2147
2148        fold_ranges.extend(
2149            snapshot
2150                .folds_in_range(start_anchor..end_anchor)
2151                .map(|anchor| {
2152                    let start = anchor.start.to_point(&snapshot.buffer_snapshot);
2153                    (
2154                        start.row,
2155                        start.to_display_point(&snapshot.display_snapshot)
2156                            ..anchor.end.to_display_point(&snapshot),
2157                    )
2158                }),
2159        );
2160
2161        let mut remote_selections = HashMap::default();
2162        for (replica_id, line_mode, cursor_shape, selection) in snapshot
2163            .buffer_snapshot
2164            .remote_selections_in_range(&(start_anchor..end_anchor))
2165        {
2166            // The local selections match the leader's selections.
2167            if Some(replica_id) == editor.leader_replica_id {
2168                continue;
2169            }
2170            remote_selections
2171                .entry(replica_id)
2172                .or_insert(Vec::new())
2173                .push(SelectionLayout::new(
2174                    selection,
2175                    line_mode,
2176                    cursor_shape,
2177                    &snapshot.display_snapshot,
2178                    false,
2179                ));
2180        }
2181        selections.extend(remote_selections);
2182
2183        if editor.show_local_selections {
2184            let mut local_selections = editor
2185                .selections
2186                .disjoint_in_range(start_anchor..end_anchor, cx);
2187            local_selections.extend(editor.selections.pending(cx));
2188            let newest = editor.selections.newest(cx);
2189            for selection in &local_selections {
2190                let is_empty = selection.start == selection.end;
2191                let selection_start = snapshot.prev_line_boundary(selection.start).1;
2192                let mut selection_end = snapshot.next_line_boundary(selection.end).1;
2193
2194                // in vim visual mode the newline is considered at the end of the previous line
2195                // instead of at the start of the current line
2196                if editor.cursor_shape == CursorShape::Block
2197                    && !is_empty
2198                    && !selection.reversed
2199                    && selection.end.column == 0
2200                    && selection_end.row() > 0
2201                    && selection_end.row() < snapshot.max_buffer_row()
2202                {
2203                    selection_end = DisplayPoint::new(selection_end.row() - 1, 0);
2204                }
2205                for row in cmp::max(selection_start.row(), start_row)
2206                    ..=cmp::min(selection_end.row(), end_row)
2207                {
2208                    let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
2209                    *contains_non_empty_selection |= !is_empty;
2210                }
2211            }
2212
2213            // Render the local selections in the leader's color when following.
2214            let local_replica_id = editor
2215                .leader_replica_id
2216                .unwrap_or_else(|| editor.replica_id(cx));
2217
2218            selections.push((
2219                local_replica_id,
2220                local_selections
2221                    .into_iter()
2222                    .map(|selection| {
2223                        let is_newest = selection == newest;
2224                        SelectionLayout::new(
2225                            selection,
2226                            editor.selections.line_mode,
2227                            editor.cursor_shape,
2228                            &snapshot.display_snapshot,
2229                            is_newest,
2230                        )
2231                    })
2232                    .collect(),
2233            ));
2234        }
2235
2236        let scrollbar_settings = &settings::get::<EditorSettings>(cx).scrollbar;
2237        let show_scrollbars = match scrollbar_settings.show {
2238            ShowScrollbar::Auto => {
2239                // Git
2240                (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_git_diffs())
2241                ||
2242                // Selections
2243                (is_singleton && scrollbar_settings.selections && !highlighted_ranges.is_empty())
2244                // Scrollmanager
2245                || editor.scroll_manager.scrollbars_visible()
2246            }
2247            ShowScrollbar::System => editor.scroll_manager.scrollbars_visible(),
2248            ShowScrollbar::Always => true,
2249            ShowScrollbar::Never => false,
2250        };
2251
2252        let fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)> = fold_ranges
2253            .into_iter()
2254            .map(|(id, fold)| {
2255                let color = self
2256                    .style
2257                    .folds
2258                    .ellipses
2259                    .background
2260                    .style_for(&mut cx.mouse_state::<FoldMarkers>(id as usize))
2261                    .color;
2262
2263                (id, fold, color)
2264            })
2265            .collect();
2266
2267        let (line_number_layouts, fold_statuses) = self.layout_line_numbers(
2268            start_row..end_row,
2269            &active_rows,
2270            is_singleton,
2271            &snapshot,
2272            cx,
2273        );
2274
2275        let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
2276
2277        let scrollbar_row_range = scroll_position.y()..(scroll_position.y() + height_in_lines);
2278
2279        let mut max_visible_line_width = 0.0;
2280        let line_layouts =
2281            self.layout_lines(start_row..end_row, &line_number_layouts, &snapshot, cx);
2282        for line_with_invisibles in &line_layouts {
2283            if line_with_invisibles.line.width() > max_visible_line_width {
2284                max_visible_line_width = line_with_invisibles.line.width();
2285            }
2286        }
2287
2288        let style = self.style.clone();
2289        let longest_line_width = layout_line(
2290            snapshot.longest_row(),
2291            &snapshot,
2292            &style,
2293            cx.text_layout_cache(),
2294        )
2295        .width();
2296        let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
2297        let em_width = style.text.em_width(cx.font_cache());
2298        let (scroll_width, blocks) = self.layout_blocks(
2299            start_row..end_row,
2300            &snapshot,
2301            size.x(),
2302            scroll_width,
2303            gutter_padding,
2304            gutter_width,
2305            em_width,
2306            gutter_width + gutter_margin,
2307            line_height,
2308            &style,
2309            &line_layouts,
2310            editor,
2311            cx,
2312        );
2313
2314        let scroll_max = vec2f(
2315            ((scroll_width - text_size.x()) / em_width).max(0.0),
2316            max_row as f32,
2317        );
2318
2319        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x());
2320
2321        let autoscrolled = if autoscroll_horizontally {
2322            editor.autoscroll_horizontally(
2323                start_row,
2324                text_size.x(),
2325                scroll_width,
2326                em_width,
2327                &line_layouts,
2328                cx,
2329            )
2330        } else {
2331            false
2332        };
2333
2334        if clamped || autoscrolled {
2335            snapshot = editor.snapshot(cx);
2336        }
2337
2338        let newest_selection_head = editor
2339            .selections
2340            .newest::<usize>(cx)
2341            .head()
2342            .to_display_point(&snapshot);
2343        let style = editor.style(cx);
2344
2345        let mut context_menu = None;
2346        let mut code_actions_indicator = None;
2347        if (start_row..end_row).contains(&newest_selection_head.row()) {
2348            if editor.context_menu_visible() {
2349                context_menu = editor.render_context_menu(newest_selection_head, style.clone(), cx);
2350            }
2351
2352            let active = matches!(
2353                editor.context_menu,
2354                Some(crate::ContextMenu::CodeActions(_))
2355            );
2356
2357            code_actions_indicator = editor
2358                .render_code_actions_indicator(&style, active, cx)
2359                .map(|indicator| (newest_selection_head.row(), indicator));
2360        }
2361
2362        let visible_rows = start_row..start_row + line_layouts.len() as u32;
2363        let mut hover = editor
2364            .hover_state
2365            .render(&snapshot, &style, visible_rows, cx);
2366        let mode = editor.mode;
2367
2368        let mut fold_indicators = editor.render_fold_indicators(
2369            fold_statuses,
2370            &style,
2371            editor.gutter_hovered,
2372            line_height,
2373            gutter_margin,
2374            cx,
2375        );
2376
2377        if let Some((_, context_menu)) = context_menu.as_mut() {
2378            context_menu.layout(
2379                SizeConstraint {
2380                    min: Vector2F::zero(),
2381                    max: vec2f(
2382                        cx.window_size().x() * 0.7,
2383                        (12. * line_height).min((size.y() - line_height) / 2.),
2384                    ),
2385                },
2386                editor,
2387                cx,
2388            );
2389        }
2390
2391        if let Some((_, indicator)) = code_actions_indicator.as_mut() {
2392            indicator.layout(
2393                SizeConstraint::strict_along(
2394                    Axis::Vertical,
2395                    line_height * style.code_actions.vertical_scale,
2396                ),
2397                editor,
2398                cx,
2399            );
2400        }
2401
2402        for fold_indicator in fold_indicators.iter_mut() {
2403            if let Some(indicator) = fold_indicator.as_mut() {
2404                indicator.layout(
2405                    SizeConstraint::strict_along(
2406                        Axis::Vertical,
2407                        line_height * style.code_actions.vertical_scale,
2408                    ),
2409                    editor,
2410                    cx,
2411                );
2412            }
2413        }
2414
2415        if let Some((_, hover_popovers)) = hover.as_mut() {
2416            for hover_popover in hover_popovers.iter_mut() {
2417                hover_popover.layout(
2418                    SizeConstraint {
2419                        min: Vector2F::zero(),
2420                        max: vec2f(
2421                            (120. * em_width) // Default size
2422                                .min(size.x() / 2.) // Shrink to half of the editor width
2423                                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2424                            (16. * line_height) // Default size
2425                                .min(size.y() / 2.) // Shrink to half of the editor height
2426                                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2427                        ),
2428                    },
2429                    editor,
2430                    cx,
2431                );
2432            }
2433        }
2434
2435        let invisible_symbol_font_size = self.style.text.font_size / 2.0;
2436        let invisible_symbol_style = RunStyle {
2437            color: self.style.whitespace,
2438            font_id: self.style.text.font_id,
2439            underline: Default::default(),
2440        };
2441
2442        (
2443            size,
2444            LayoutState {
2445                mode,
2446                position_map: Arc::new(PositionMap {
2447                    size,
2448                    scroll_max,
2449                    line_layouts,
2450                    line_height,
2451                    em_width,
2452                    em_advance,
2453                    snapshot,
2454                }),
2455                visible_display_row_range: start_row..end_row,
2456                wrap_guides,
2457                gutter_size,
2458                gutter_padding,
2459                text_size,
2460                scrollbar_row_range,
2461                show_scrollbars,
2462                is_singleton,
2463                max_row,
2464                gutter_margin,
2465                active_rows,
2466                highlighted_rows,
2467                highlighted_ranges,
2468                fold_ranges,
2469                line_number_layouts,
2470                display_hunks,
2471                blocks,
2472                selections,
2473                context_menu,
2474                code_actions_indicator,
2475                fold_indicators,
2476                tab_invisible: cx.text_layout_cache().layout_str(
2477                    "",
2478                    invisible_symbol_font_size,
2479                    &[("".len(), invisible_symbol_style)],
2480                ),
2481                space_invisible: cx.text_layout_cache().layout_str(
2482                    "",
2483                    invisible_symbol_font_size,
2484                    &[("".len(), invisible_symbol_style)],
2485                ),
2486                hover_popovers: hover,
2487            },
2488        )
2489    }
2490
2491    fn paint(
2492        &mut self,
2493        scene: &mut SceneBuilder,
2494        bounds: RectF,
2495        visible_bounds: RectF,
2496        layout: &mut Self::LayoutState,
2497        editor: &mut Editor,
2498        cx: &mut ViewContext<Editor>,
2499    ) -> Self::PaintState {
2500        let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
2501        scene.push_layer(Some(visible_bounds));
2502
2503        let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
2504        let text_bounds = RectF::new(
2505            bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
2506            layout.text_size,
2507        );
2508
2509        Self::attach_mouse_handlers(
2510            scene,
2511            &layout.position_map,
2512            layout.hover_popovers.is_some(),
2513            visible_bounds,
2514            text_bounds,
2515            gutter_bounds,
2516            bounds,
2517            cx,
2518        );
2519
2520        self.paint_background(scene, gutter_bounds, text_bounds, layout);
2521        if layout.gutter_size.x() > 0. {
2522            self.paint_gutter(scene, gutter_bounds, visible_bounds, layout, editor, cx);
2523        }
2524        self.paint_text(scene, text_bounds, visible_bounds, layout, editor, cx);
2525
2526        scene.push_layer(Some(bounds));
2527        if !layout.blocks.is_empty() {
2528            self.paint_blocks(scene, bounds, visible_bounds, layout, editor, cx);
2529        }
2530        self.paint_scrollbar(scene, bounds, layout, cx, &editor);
2531        scene.pop_layer();
2532
2533        scene.pop_layer();
2534    }
2535
2536    fn rect_for_text_range(
2537        &self,
2538        range_utf16: Range<usize>,
2539        bounds: RectF,
2540        _: RectF,
2541        layout: &Self::LayoutState,
2542        _: &Self::PaintState,
2543        _: &Editor,
2544        _: &ViewContext<Editor>,
2545    ) -> Option<RectF> {
2546        let text_bounds = RectF::new(
2547            bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
2548            layout.text_size,
2549        );
2550        let content_origin = text_bounds.origin() + vec2f(layout.gutter_margin, 0.);
2551        let scroll_position = layout.position_map.snapshot.scroll_position();
2552        let start_row = scroll_position.y() as u32;
2553        let scroll_top = scroll_position.y() * layout.position_map.line_height;
2554        let scroll_left = scroll_position.x() * layout.position_map.em_width;
2555
2556        let range_start = OffsetUtf16(range_utf16.start)
2557            .to_display_point(&layout.position_map.snapshot.display_snapshot);
2558        if range_start.row() < start_row {
2559            return None;
2560        }
2561
2562        let line = &layout
2563            .position_map
2564            .line_layouts
2565            .get((range_start.row() - start_row) as usize)?
2566            .line;
2567        let range_start_x = line.x_for_index(range_start.column() as usize);
2568        let range_start_y = range_start.row() as f32 * layout.position_map.line_height;
2569        Some(RectF::new(
2570            content_origin
2571                + vec2f(
2572                    range_start_x,
2573                    range_start_y + layout.position_map.line_height,
2574                )
2575                - vec2f(scroll_left, scroll_top),
2576            vec2f(
2577                layout.position_map.em_width,
2578                layout.position_map.line_height,
2579            ),
2580        ))
2581    }
2582
2583    fn debug(
2584        &self,
2585        bounds: RectF,
2586        _: &Self::LayoutState,
2587        _: &Self::PaintState,
2588        _: &Editor,
2589        _: &ViewContext<Editor>,
2590    ) -> json::Value {
2591        json!({
2592            "type": "BufferElement",
2593            "bounds": bounds.to_json()
2594        })
2595    }
2596}
2597
2598type BufferRow = u32;
2599
2600pub struct LayoutState {
2601    position_map: Arc<PositionMap>,
2602    gutter_size: Vector2F,
2603    gutter_padding: f32,
2604    gutter_margin: f32,
2605    text_size: Vector2F,
2606    mode: EditorMode,
2607    wrap_guides: SmallVec<[(f32, bool); 2]>,
2608    visible_display_row_range: Range<u32>,
2609    active_rows: BTreeMap<u32, bool>,
2610    highlighted_rows: Option<Range<u32>>,
2611    line_number_layouts: Vec<Option<text_layout::Line>>,
2612    display_hunks: Vec<DisplayDiffHunk>,
2613    blocks: Vec<BlockLayout>,
2614    highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
2615    fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)>,
2616    selections: Vec<(ReplicaId, Vec<SelectionLayout>)>,
2617    scrollbar_row_range: Range<f32>,
2618    show_scrollbars: bool,
2619    is_singleton: bool,
2620    max_row: u32,
2621    context_menu: Option<(DisplayPoint, AnyElement<Editor>)>,
2622    code_actions_indicator: Option<(u32, AnyElement<Editor>)>,
2623    hover_popovers: Option<(DisplayPoint, Vec<AnyElement<Editor>>)>,
2624    fold_indicators: Vec<Option<AnyElement<Editor>>>,
2625    tab_invisible: Line,
2626    space_invisible: Line,
2627}
2628
2629struct PositionMap {
2630    size: Vector2F,
2631    line_height: f32,
2632    scroll_max: Vector2F,
2633    em_width: f32,
2634    em_advance: f32,
2635    line_layouts: Vec<LineWithInvisibles>,
2636    snapshot: EditorSnapshot,
2637}
2638
2639impl PositionMap {
2640    /// Returns two display points:
2641    /// 1. The nearest *valid* position in the editor
2642    /// 2. An unclipped, potentially *invalid* position that maps directly to
2643    ///    the given pixel position.
2644    fn point_for_position(
2645        &self,
2646        text_bounds: RectF,
2647        position: Vector2F,
2648    ) -> (DisplayPoint, DisplayPoint) {
2649        let scroll_position = self.snapshot.scroll_position();
2650        let position = position - text_bounds.origin();
2651        let y = position.y().max(0.0).min(self.size.y());
2652        let x = position.x() + (scroll_position.x() * self.em_width);
2653        let row = (y / self.line_height + scroll_position.y()) as u32;
2654        let (column, x_overshoot) = if let Some(line) = self
2655            .line_layouts
2656            .get(row as usize - scroll_position.y() as usize)
2657            .map(|line_with_spaces| &line_with_spaces.line)
2658        {
2659            if let Some(ix) = line.index_for_x(x) {
2660                (ix as u32, 0.0)
2661            } else {
2662                (line.len() as u32, 0f32.max(x - line.width()))
2663            }
2664        } else {
2665            (0, x)
2666        };
2667
2668        let mut target_point = DisplayPoint::new(row, column);
2669        let point = self.snapshot.clip_point(target_point, Bias::Left);
2670        *target_point.column_mut() += (x_overshoot / self.em_advance) as u32;
2671
2672        (point, target_point)
2673    }
2674}
2675
2676struct BlockLayout {
2677    row: u32,
2678    element: AnyElement<Editor>,
2679    style: BlockStyle,
2680}
2681
2682fn layout_line(
2683    row: u32,
2684    snapshot: &EditorSnapshot,
2685    style: &EditorStyle,
2686    layout_cache: &TextLayoutCache,
2687) -> text_layout::Line {
2688    let mut line = snapshot.line(row);
2689
2690    if line.len() > MAX_LINE_LEN {
2691        let mut len = MAX_LINE_LEN;
2692        while !line.is_char_boundary(len) {
2693            len -= 1;
2694        }
2695
2696        line.truncate(len);
2697    }
2698
2699    layout_cache.layout_str(
2700        &line,
2701        style.text.font_size,
2702        &[(
2703            snapshot.line_len(row) as usize,
2704            RunStyle {
2705                font_id: style.text.font_id,
2706                color: Color::black(),
2707                underline: Default::default(),
2708            },
2709        )],
2710    )
2711}
2712
2713#[derive(Debug)]
2714pub struct Cursor {
2715    origin: Vector2F,
2716    block_width: f32,
2717    line_height: f32,
2718    color: Color,
2719    shape: CursorShape,
2720    block_text: Option<Line>,
2721}
2722
2723impl Cursor {
2724    pub fn new(
2725        origin: Vector2F,
2726        block_width: f32,
2727        line_height: f32,
2728        color: Color,
2729        shape: CursorShape,
2730        block_text: Option<Line>,
2731    ) -> Cursor {
2732        Cursor {
2733            origin,
2734            block_width,
2735            line_height,
2736            color,
2737            shape,
2738            block_text,
2739        }
2740    }
2741
2742    pub fn bounding_rect(&self, origin: Vector2F) -> RectF {
2743        RectF::new(
2744            self.origin + origin,
2745            vec2f(self.block_width, self.line_height),
2746        )
2747    }
2748
2749    pub fn paint(&self, scene: &mut SceneBuilder, origin: Vector2F, cx: &mut WindowContext) {
2750        let bounds = match self.shape {
2751            CursorShape::Bar => RectF::new(self.origin + origin, vec2f(2.0, self.line_height)),
2752            CursorShape::Block | CursorShape::Hollow => RectF::new(
2753                self.origin + origin,
2754                vec2f(self.block_width, self.line_height),
2755            ),
2756            CursorShape::Underscore => RectF::new(
2757                self.origin + origin + Vector2F::new(0.0, self.line_height - 2.0),
2758                vec2f(self.block_width, 2.0),
2759            ),
2760        };
2761
2762        //Draw background or border quad
2763        if matches!(self.shape, CursorShape::Hollow) {
2764            scene.push_quad(Quad {
2765                bounds,
2766                background: None,
2767                border: Border::all(1., self.color),
2768                corner_radius: 0.,
2769            });
2770        } else {
2771            scene.push_quad(Quad {
2772                bounds,
2773                background: Some(self.color),
2774                border: Default::default(),
2775                corner_radius: 0.,
2776            });
2777        }
2778
2779        if let Some(block_text) = &self.block_text {
2780            block_text.paint(scene, self.origin + origin, bounds, self.line_height, cx);
2781        }
2782    }
2783
2784    pub fn shape(&self) -> CursorShape {
2785        self.shape
2786    }
2787}
2788
2789#[derive(Debug)]
2790pub struct HighlightedRange {
2791    pub start_y: f32,
2792    pub line_height: f32,
2793    pub lines: Vec<HighlightedRangeLine>,
2794    pub color: Color,
2795    pub corner_radius: f32,
2796}
2797
2798#[derive(Debug)]
2799pub struct HighlightedRangeLine {
2800    pub start_x: f32,
2801    pub end_x: f32,
2802}
2803
2804impl HighlightedRange {
2805    pub fn paint(&self, bounds: RectF, scene: &mut SceneBuilder) {
2806        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
2807            self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
2808            self.paint_lines(
2809                self.start_y + self.line_height,
2810                &self.lines[1..],
2811                bounds,
2812                scene,
2813            );
2814        } else {
2815            self.paint_lines(self.start_y, &self.lines, bounds, scene);
2816        }
2817    }
2818
2819    fn paint_lines(
2820        &self,
2821        start_y: f32,
2822        lines: &[HighlightedRangeLine],
2823        bounds: RectF,
2824        scene: &mut SceneBuilder,
2825    ) {
2826        if lines.is_empty() {
2827            return;
2828        }
2829
2830        let mut path = PathBuilder::new();
2831        let first_line = lines.first().unwrap();
2832        let last_line = lines.last().unwrap();
2833
2834        let first_top_left = vec2f(first_line.start_x, start_y);
2835        let first_top_right = vec2f(first_line.end_x, start_y);
2836
2837        let curve_height = vec2f(0., self.corner_radius);
2838        let curve_width = |start_x: f32, end_x: f32| {
2839            let max = (end_x - start_x) / 2.;
2840            let width = if max < self.corner_radius {
2841                max
2842            } else {
2843                self.corner_radius
2844            };
2845
2846            vec2f(width, 0.)
2847        };
2848
2849        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
2850        path.reset(first_top_right - top_curve_width);
2851        path.curve_to(first_top_right + curve_height, first_top_right);
2852
2853        let mut iter = lines.iter().enumerate().peekable();
2854        while let Some((ix, line)) = iter.next() {
2855            let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
2856
2857            if let Some((_, next_line)) = iter.peek() {
2858                let next_top_right = vec2f(next_line.end_x, bottom_right.y());
2859
2860                match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
2861                    Ordering::Equal => {
2862                        path.line_to(bottom_right);
2863                    }
2864                    Ordering::Less => {
2865                        let curve_width = curve_width(next_top_right.x(), bottom_right.x());
2866                        path.line_to(bottom_right - curve_height);
2867                        if self.corner_radius > 0. {
2868                            path.curve_to(bottom_right - curve_width, bottom_right);
2869                        }
2870                        path.line_to(next_top_right + curve_width);
2871                        if self.corner_radius > 0. {
2872                            path.curve_to(next_top_right + curve_height, next_top_right);
2873                        }
2874                    }
2875                    Ordering::Greater => {
2876                        let curve_width = curve_width(bottom_right.x(), next_top_right.x());
2877                        path.line_to(bottom_right - curve_height);
2878                        if self.corner_radius > 0. {
2879                            path.curve_to(bottom_right + curve_width, bottom_right);
2880                        }
2881                        path.line_to(next_top_right - curve_width);
2882                        if self.corner_radius > 0. {
2883                            path.curve_to(next_top_right + curve_height, next_top_right);
2884                        }
2885                    }
2886                }
2887            } else {
2888                let curve_width = curve_width(line.start_x, line.end_x);
2889                path.line_to(bottom_right - curve_height);
2890                if self.corner_radius > 0. {
2891                    path.curve_to(bottom_right - curve_width, bottom_right);
2892                }
2893
2894                let bottom_left = vec2f(line.start_x, bottom_right.y());
2895                path.line_to(bottom_left + curve_width);
2896                if self.corner_radius > 0. {
2897                    path.curve_to(bottom_left - curve_height, bottom_left);
2898                }
2899            }
2900        }
2901
2902        if first_line.start_x > last_line.start_x {
2903            let curve_width = curve_width(last_line.start_x, first_line.start_x);
2904            let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
2905            path.line_to(second_top_left + curve_height);
2906            if self.corner_radius > 0. {
2907                path.curve_to(second_top_left + curve_width, second_top_left);
2908            }
2909            let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
2910            path.line_to(first_bottom_left - curve_width);
2911            if self.corner_radius > 0. {
2912                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
2913            }
2914        }
2915
2916        path.line_to(first_top_left + curve_height);
2917        if self.corner_radius > 0. {
2918            path.curve_to(first_top_left + top_curve_width, first_top_left);
2919        }
2920        path.line_to(first_top_right - top_curve_width);
2921
2922        scene.push_path(path.build(self.color, Some(bounds)));
2923    }
2924}
2925
2926fn position_to_display_point(
2927    position: Vector2F,
2928    text_bounds: RectF,
2929    position_map: &PositionMap,
2930) -> Option<DisplayPoint> {
2931    if text_bounds.contains_point(position) {
2932        let (point, target_point) = position_map.point_for_position(text_bounds, position);
2933        if point == target_point {
2934            Some(point)
2935        } else {
2936            None
2937        }
2938    } else {
2939        None
2940    }
2941}
2942
2943fn range_to_bounds(
2944    range: &Range<DisplayPoint>,
2945    content_origin: Vector2F,
2946    scroll_left: f32,
2947    scroll_top: f32,
2948    visible_row_range: &Range<u32>,
2949    line_end_overshoot: f32,
2950    position_map: &PositionMap,
2951) -> impl Iterator<Item = RectF> {
2952    let mut bounds: SmallVec<[RectF; 1]> = SmallVec::new();
2953
2954    if range.start == range.end {
2955        return bounds.into_iter();
2956    }
2957
2958    let start_row = visible_row_range.start;
2959    let end_row = visible_row_range.end;
2960
2961    let row_range = if range.end.column() == 0 {
2962        cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
2963    } else {
2964        cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
2965    };
2966
2967    let first_y =
2968        content_origin.y() + row_range.start as f32 * position_map.line_height - scroll_top;
2969
2970    for (idx, row) in row_range.enumerate() {
2971        let line_layout = &position_map.line_layouts[(row - start_row) as usize].line;
2972
2973        let start_x = if row == range.start.row() {
2974            content_origin.x() + line_layout.x_for_index(range.start.column() as usize)
2975                - scroll_left
2976        } else {
2977            content_origin.x() - scroll_left
2978        };
2979
2980        let end_x = if row == range.end.row() {
2981            content_origin.x() + line_layout.x_for_index(range.end.column() as usize) - scroll_left
2982        } else {
2983            content_origin.x() + line_layout.width() + line_end_overshoot - scroll_left
2984        };
2985
2986        bounds.push(RectF::from_points(
2987            vec2f(start_x, first_y + position_map.line_height * idx as f32),
2988            vec2f(end_x, first_y + position_map.line_height * (idx + 1) as f32),
2989        ))
2990    }
2991
2992    bounds.into_iter()
2993}
2994
2995pub fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
2996    delta.powf(1.5) / 100.0
2997}
2998
2999fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
3000    delta.powf(1.2) / 300.0
3001}
3002
3003#[cfg(test)]
3004mod tests {
3005    use super::*;
3006    use crate::{
3007        display_map::{BlockDisposition, BlockProperties},
3008        editor_tests::{init_test, update_test_language_settings},
3009        Editor, MultiBuffer,
3010    };
3011    use gpui::TestAppContext;
3012    use language::language_settings;
3013    use log::info;
3014    use std::{num::NonZeroU32, sync::Arc};
3015    use util::test::sample_text;
3016
3017    #[gpui::test]
3018    fn test_layout_line_numbers(cx: &mut TestAppContext) {
3019        init_test(cx, |_| {});
3020
3021        let (_, editor) = cx.add_window(|cx| {
3022            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
3023            Editor::new(EditorMode::Full, buffer, None, None, cx)
3024        });
3025        let element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3026
3027        let layouts = editor.update(cx, |editor, cx| {
3028            let snapshot = editor.snapshot(cx);
3029            element
3030                .layout_line_numbers(0..6, &Default::default(), false, &snapshot, cx)
3031                .0
3032        });
3033        assert_eq!(layouts.len(), 6);
3034    }
3035
3036    #[gpui::test]
3037    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
3038        init_test(cx, |_| {});
3039
3040        let (_, editor) = cx.add_window(|cx| {
3041            let buffer = MultiBuffer::build_simple("", cx);
3042            Editor::new(EditorMode::Full, buffer, None, None, cx)
3043        });
3044
3045        editor.update(cx, |editor, cx| {
3046            editor.set_placeholder_text("hello", cx);
3047            editor.insert_blocks(
3048                [BlockProperties {
3049                    style: BlockStyle::Fixed,
3050                    disposition: BlockDisposition::Above,
3051                    height: 3,
3052                    position: Anchor::min(),
3053                    render: Arc::new(|_| Empty::new().into_any()),
3054                }],
3055                None,
3056                cx,
3057            );
3058
3059            // Blur the editor so that it displays placeholder text.
3060            cx.blur();
3061        });
3062
3063        let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3064        let (size, mut state) = editor.update(cx, |editor, cx| {
3065            let mut new_parents = Default::default();
3066            let mut notify_views_if_parents_change = Default::default();
3067            let mut layout_cx = LayoutContext::new(
3068                cx,
3069                &mut new_parents,
3070                &mut notify_views_if_parents_change,
3071                false,
3072            );
3073            element.layout(
3074                SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
3075                editor,
3076                &mut layout_cx,
3077            )
3078        });
3079
3080        assert_eq!(state.position_map.line_layouts.len(), 4);
3081        assert_eq!(
3082            state
3083                .line_number_layouts
3084                .iter()
3085                .map(Option::is_some)
3086                .collect::<Vec<_>>(),
3087            &[false, false, false, true]
3088        );
3089
3090        // Don't panic.
3091        let mut scene = SceneBuilder::new(1.0);
3092        let bounds = RectF::new(Default::default(), size);
3093        editor.update(cx, |editor, cx| {
3094            element.paint(&mut scene, bounds, bounds, &mut state, editor, cx);
3095        });
3096    }
3097
3098    #[gpui::test]
3099    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
3100        const TAB_SIZE: u32 = 4;
3101
3102        let input_text = "\t \t|\t| a b";
3103        let expected_invisibles = vec![
3104            Invisible::Tab {
3105                line_start_offset: 0,
3106            },
3107            Invisible::Whitespace {
3108                line_offset: TAB_SIZE as usize,
3109            },
3110            Invisible::Tab {
3111                line_start_offset: TAB_SIZE as usize + 1,
3112            },
3113            Invisible::Tab {
3114                line_start_offset: TAB_SIZE as usize * 2 + 1,
3115            },
3116            Invisible::Whitespace {
3117                line_offset: TAB_SIZE as usize * 3 + 1,
3118            },
3119            Invisible::Whitespace {
3120                line_offset: TAB_SIZE as usize * 3 + 3,
3121            },
3122        ];
3123        assert_eq!(
3124            expected_invisibles.len(),
3125            input_text
3126                .chars()
3127                .filter(|initial_char| initial_char.is_whitespace())
3128                .count(),
3129            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
3130        );
3131
3132        init_test(cx, |s| {
3133            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3134            s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
3135        });
3136
3137        let actual_invisibles =
3138            collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, 500.0);
3139
3140        assert_eq!(expected_invisibles, actual_invisibles);
3141    }
3142
3143    #[gpui::test]
3144    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
3145        init_test(cx, |s| {
3146            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3147            s.defaults.tab_size = NonZeroU32::new(4);
3148        });
3149
3150        for editor_mode_without_invisibles in [
3151            EditorMode::SingleLine,
3152            EditorMode::AutoHeight { max_lines: 100 },
3153        ] {
3154            let invisibles = collect_invisibles_from_new_editor(
3155                cx,
3156                editor_mode_without_invisibles,
3157                "\t\t\t| | a b",
3158                500.0,
3159            );
3160            assert!(invisibles.is_empty(),
3161                "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
3162        }
3163    }
3164
3165    #[gpui::test]
3166    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
3167        let tab_size = 4;
3168        let input_text = "a\tbcd   ".repeat(9);
3169        let repeated_invisibles = [
3170            Invisible::Tab {
3171                line_start_offset: 1,
3172            },
3173            Invisible::Whitespace {
3174                line_offset: tab_size as usize + 3,
3175            },
3176            Invisible::Whitespace {
3177                line_offset: tab_size as usize + 4,
3178            },
3179            Invisible::Whitespace {
3180                line_offset: tab_size as usize + 5,
3181            },
3182        ];
3183        let expected_invisibles = std::iter::once(repeated_invisibles)
3184            .cycle()
3185            .take(9)
3186            .flatten()
3187            .collect::<Vec<_>>();
3188        assert_eq!(
3189            expected_invisibles.len(),
3190            input_text
3191                .chars()
3192                .filter(|initial_char| initial_char.is_whitespace())
3193                .count(),
3194            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
3195        );
3196        info!("Expected invisibles: {expected_invisibles:?}");
3197
3198        init_test(cx, |_| {});
3199
3200        // Put the same string with repeating whitespace pattern into editors of various size,
3201        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
3202        let resize_step = 10.0;
3203        let mut editor_width = 200.0;
3204        while editor_width <= 1000.0 {
3205            update_test_language_settings(cx, |s| {
3206                s.defaults.tab_size = NonZeroU32::new(tab_size);
3207                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3208                s.defaults.preferred_line_length = Some(editor_width as u32);
3209                s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
3210            });
3211
3212            let actual_invisibles =
3213                collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, editor_width);
3214
3215            // Whatever the editor size is, ensure it has the same invisible kinds in the same order
3216            // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
3217            let mut i = 0;
3218            for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
3219                i = actual_index;
3220                match expected_invisibles.get(i) {
3221                    Some(expected_invisible) => match (expected_invisible, actual_invisible) {
3222                        (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
3223                        | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
3224                        _ => {
3225                            panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
3226                        }
3227                    },
3228                    None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
3229                }
3230            }
3231            let missing_expected_invisibles = &expected_invisibles[i + 1..];
3232            assert!(
3233                missing_expected_invisibles.is_empty(),
3234                "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
3235            );
3236
3237            editor_width += resize_step;
3238        }
3239    }
3240
3241    fn collect_invisibles_from_new_editor(
3242        cx: &mut TestAppContext,
3243        editor_mode: EditorMode,
3244        input_text: &str,
3245        editor_width: f32,
3246    ) -> Vec<Invisible> {
3247        info!(
3248            "Creating editor with mode {editor_mode:?}, width {editor_width} and text '{input_text}'"
3249        );
3250        let (_, editor) = cx.add_window(|cx| {
3251            let buffer = MultiBuffer::build_simple(&input_text, cx);
3252            Editor::new(editor_mode, buffer, None, None, cx)
3253        });
3254
3255        let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3256        let (_, layout_state) = editor.update(cx, |editor, cx| {
3257            editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
3258            editor.set_wrap_width(Some(editor_width), cx);
3259
3260            let mut new_parents = Default::default();
3261            let mut notify_views_if_parents_change = Default::default();
3262            let mut layout_cx = LayoutContext::new(
3263                cx,
3264                &mut new_parents,
3265                &mut notify_views_if_parents_change,
3266                false,
3267            );
3268            element.layout(
3269                SizeConstraint::new(vec2f(editor_width, 500.), vec2f(editor_width, 500.)),
3270                editor,
3271                &mut layout_cx,
3272            )
3273        });
3274
3275        layout_state
3276            .position_map
3277            .line_layouts
3278            .iter()
3279            .map(|line_with_invisibles| &line_with_invisibles.invisibles)
3280            .flatten()
3281            .cloned()
3282            .collect()
3283    }
3284}