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