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