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