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