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