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        let line_height = (style.text.font_size * style.line_height_scalar).round();
1991
1992        let gutter_padding;
1993        let gutter_width;
1994        let gutter_margin;
1995        if snapshot.show_gutter {
1996            let em_width = style.text.em_width(cx.font_cache());
1997            gutter_padding = (em_width * style.gutter_padding_factor).round();
1998            gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
1999            gutter_margin = -style.text.descent(cx.font_cache());
2000        } else {
2001            gutter_padding = 0.0;
2002            gutter_width = 0.0;
2003            gutter_margin = 0.0;
2004        };
2005
2006        let text_width = size.x() - gutter_width;
2007        let em_width = style.text.em_width(cx.font_cache());
2008        let em_advance = style.text.em_advance(cx.font_cache());
2009        let overscroll = vec2f(em_width, 0.);
2010        let snapshot = {
2011            editor.set_visible_line_count(size.y() / line_height, cx);
2012
2013            let editor_width = text_width - gutter_margin - overscroll.x() - em_width;
2014            let wrap_width = match editor.soft_wrap_mode(cx) {
2015                SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
2016                SoftWrap::EditorWidth => editor_width,
2017                SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
2018            };
2019
2020            if editor.set_wrap_width(Some(wrap_width), cx) {
2021                editor.snapshot(cx)
2022            } else {
2023                snapshot
2024            }
2025        };
2026
2027        let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
2028        if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
2029            size.set_y(
2030                scroll_height
2031                    .min(constraint.max_along(Axis::Vertical))
2032                    .max(constraint.min_along(Axis::Vertical))
2033                    .min(line_height * max_lines as f32),
2034            )
2035        } else if let EditorMode::SingleLine = snapshot.mode {
2036            size.set_y(
2037                line_height
2038                    .min(constraint.max_along(Axis::Vertical))
2039                    .max(constraint.min_along(Axis::Vertical)),
2040            )
2041        } else if size.y().is_infinite() {
2042            size.set_y(scroll_height);
2043        }
2044        let gutter_size = vec2f(gutter_width, size.y());
2045        let text_size = vec2f(text_width, size.y());
2046
2047        let autoscroll_horizontally = editor.autoscroll_vertically(size.y(), line_height, cx);
2048        let mut snapshot = editor.snapshot(cx);
2049
2050        let scroll_position = snapshot.scroll_position();
2051        // The scroll position is a fractional point, the whole number of which represents
2052        // the top of the window in terms of display rows.
2053        let start_row = scroll_position.y() as u32;
2054        let height_in_lines = size.y() / line_height;
2055        let max_row = snapshot.max_point().row();
2056
2057        // Add 1 to ensure selections bleed off screen
2058        let end_row = 1 + cmp::min(
2059            (scroll_position.y() + height_in_lines).ceil() as u32,
2060            max_row,
2061        );
2062
2063        let start_anchor = if start_row == 0 {
2064            Anchor::min()
2065        } else {
2066            snapshot
2067                .buffer_snapshot
2068                .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
2069        };
2070        let end_anchor = if end_row > max_row {
2071            Anchor::max()
2072        } else {
2073            snapshot
2074                .buffer_snapshot
2075                .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
2076        };
2077
2078        let mut selections: Vec<(ReplicaId, Vec<SelectionLayout>)> = Vec::new();
2079        let mut active_rows = BTreeMap::new();
2080        let mut fold_ranges = Vec::new();
2081        let is_singleton = editor.is_singleton(cx);
2082
2083        let highlighted_rows = editor.highlighted_rows();
2084        let theme = theme::current(cx);
2085        let highlighted_ranges = editor.background_highlights_in_range(
2086            start_anchor..end_anchor,
2087            &snapshot.display_snapshot,
2088            theme.as_ref(),
2089        );
2090
2091        fold_ranges.extend(
2092            snapshot
2093                .folds_in_range(start_anchor..end_anchor)
2094                .map(|anchor| {
2095                    let start = anchor.start.to_point(&snapshot.buffer_snapshot);
2096                    (
2097                        start.row,
2098                        start.to_display_point(&snapshot.display_snapshot)
2099                            ..anchor.end.to_display_point(&snapshot),
2100                    )
2101                }),
2102        );
2103
2104        let mut remote_selections = HashMap::default();
2105        for (replica_id, line_mode, cursor_shape, selection) in snapshot
2106            .buffer_snapshot
2107            .remote_selections_in_range(&(start_anchor..end_anchor))
2108        {
2109            // The local selections match the leader's selections.
2110            if Some(replica_id) == editor.leader_replica_id {
2111                continue;
2112            }
2113            remote_selections
2114                .entry(replica_id)
2115                .or_insert(Vec::new())
2116                .push(SelectionLayout::new(
2117                    selection,
2118                    line_mode,
2119                    cursor_shape,
2120                    &snapshot.display_snapshot,
2121                    false,
2122                ));
2123        }
2124        selections.extend(remote_selections);
2125
2126        if editor.show_local_selections {
2127            let mut local_selections = editor
2128                .selections
2129                .disjoint_in_range(start_anchor..end_anchor, cx);
2130            local_selections.extend(editor.selections.pending(cx));
2131            let newest = editor.selections.newest(cx);
2132            for selection in &local_selections {
2133                let is_empty = selection.start == selection.end;
2134                let selection_start = snapshot.prev_line_boundary(selection.start).1;
2135                let selection_end = snapshot.next_line_boundary(selection.end).1;
2136                for row in cmp::max(selection_start.row(), start_row)
2137                    ..=cmp::min(selection_end.row(), end_row)
2138                {
2139                    let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
2140                    *contains_non_empty_selection |= !is_empty;
2141                }
2142            }
2143
2144            // Render the local selections in the leader's color when following.
2145            let local_replica_id = editor
2146                .leader_replica_id
2147                .unwrap_or_else(|| editor.replica_id(cx));
2148
2149            selections.push((
2150                local_replica_id,
2151                local_selections
2152                    .into_iter()
2153                    .map(|selection| {
2154                        let is_newest = selection == newest;
2155                        SelectionLayout::new(
2156                            selection,
2157                            editor.selections.line_mode,
2158                            editor.cursor_shape,
2159                            &snapshot.display_snapshot,
2160                            is_newest,
2161                        )
2162                    })
2163                    .collect(),
2164            ));
2165        }
2166
2167        let scrollbar_settings = &settings::get::<EditorSettings>(cx).scrollbar;
2168        let show_scrollbars = match scrollbar_settings.show {
2169            ShowScrollbar::Auto => {
2170                // Git
2171                (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_git_diffs())
2172                ||
2173                // Selections
2174                (is_singleton && scrollbar_settings.selections && !highlighted_ranges.is_empty())
2175                // Scrollmanager
2176                || editor.scroll_manager.scrollbars_visible()
2177            }
2178            ShowScrollbar::System => editor.scroll_manager.scrollbars_visible(),
2179            ShowScrollbar::Always => true,
2180            ShowScrollbar::Never => false,
2181        };
2182
2183        let fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)> = fold_ranges
2184            .into_iter()
2185            .map(|(id, fold)| {
2186                let color = self
2187                    .style
2188                    .folds
2189                    .ellipses
2190                    .background
2191                    .style_for(&mut cx.mouse_state::<FoldMarkers>(id as usize))
2192                    .color;
2193
2194                (id, fold, color)
2195            })
2196            .collect();
2197
2198        let (line_number_layouts, fold_statuses) = self.layout_line_numbers(
2199            start_row..end_row,
2200            &active_rows,
2201            is_singleton,
2202            &snapshot,
2203            cx,
2204        );
2205
2206        let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
2207
2208        let scrollbar_row_range = scroll_position.y()..(scroll_position.y() + height_in_lines);
2209
2210        let mut max_visible_line_width = 0.0;
2211        let line_layouts =
2212            self.layout_lines(start_row..end_row, &line_number_layouts, &snapshot, cx);
2213        for line_with_invisibles in &line_layouts {
2214            if line_with_invisibles.line.width() > max_visible_line_width {
2215                max_visible_line_width = line_with_invisibles.line.width();
2216            }
2217        }
2218
2219        let style = self.style.clone();
2220        let longest_line_width = layout_line(
2221            snapshot.longest_row(),
2222            &snapshot,
2223            &style,
2224            cx.text_layout_cache(),
2225        )
2226        .width();
2227        let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
2228        let em_width = style.text.em_width(cx.font_cache());
2229        let (scroll_width, blocks) = self.layout_blocks(
2230            start_row..end_row,
2231            &snapshot,
2232            size.x(),
2233            scroll_width,
2234            gutter_padding,
2235            gutter_width,
2236            em_width,
2237            gutter_width + gutter_margin,
2238            line_height,
2239            &style,
2240            &line_layouts,
2241            editor,
2242            cx,
2243        );
2244
2245        let scroll_max = vec2f(
2246            ((scroll_width - text_size.x()) / em_width).max(0.0),
2247            max_row as f32,
2248        );
2249
2250        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x());
2251
2252        let autoscrolled = if autoscroll_horizontally {
2253            editor.autoscroll_horizontally(
2254                start_row,
2255                text_size.x(),
2256                scroll_width,
2257                em_width,
2258                &line_layouts,
2259                cx,
2260            )
2261        } else {
2262            false
2263        };
2264
2265        if clamped || autoscrolled {
2266            snapshot = editor.snapshot(cx);
2267        }
2268
2269        let newest_selection_head = editor
2270            .selections
2271            .newest::<usize>(cx)
2272            .head()
2273            .to_display_point(&snapshot);
2274        let style = editor.style(cx);
2275
2276        let mut context_menu = None;
2277        let mut code_actions_indicator = None;
2278        if (start_row..end_row).contains(&newest_selection_head.row()) {
2279            if editor.context_menu_visible() {
2280                context_menu = editor.render_context_menu(newest_selection_head, style.clone(), cx);
2281            }
2282
2283            let active = matches!(
2284                editor.context_menu,
2285                Some(crate::ContextMenu::CodeActions(_))
2286            );
2287
2288            code_actions_indicator = editor
2289                .render_code_actions_indicator(&style, active, cx)
2290                .map(|indicator| (newest_selection_head.row(), indicator));
2291        }
2292
2293        let visible_rows = start_row..start_row + line_layouts.len() as u32;
2294        let mut hover = editor
2295            .hover_state
2296            .render(&snapshot, &style, visible_rows, cx);
2297        let mode = editor.mode;
2298
2299        let mut fold_indicators = editor.render_fold_indicators(
2300            fold_statuses,
2301            &style,
2302            editor.gutter_hovered,
2303            line_height,
2304            gutter_margin,
2305            cx,
2306        );
2307
2308        if let Some((_, context_menu)) = context_menu.as_mut() {
2309            context_menu.layout(
2310                SizeConstraint {
2311                    min: Vector2F::zero(),
2312                    max: vec2f(
2313                        cx.window_size().x() * 0.7,
2314                        (12. * line_height).min((size.y() - line_height) / 2.),
2315                    ),
2316                },
2317                editor,
2318                cx,
2319            );
2320        }
2321
2322        if let Some((_, indicator)) = code_actions_indicator.as_mut() {
2323            indicator.layout(
2324                SizeConstraint::strict_along(
2325                    Axis::Vertical,
2326                    line_height * style.code_actions.vertical_scale,
2327                ),
2328                editor,
2329                cx,
2330            );
2331        }
2332
2333        for fold_indicator in fold_indicators.iter_mut() {
2334            if let Some(indicator) = fold_indicator.as_mut() {
2335                indicator.layout(
2336                    SizeConstraint::strict_along(
2337                        Axis::Vertical,
2338                        line_height * style.code_actions.vertical_scale,
2339                    ),
2340                    editor,
2341                    cx,
2342                );
2343            }
2344        }
2345
2346        if let Some((_, hover_popovers)) = hover.as_mut() {
2347            for hover_popover in hover_popovers.iter_mut() {
2348                hover_popover.layout(
2349                    SizeConstraint {
2350                        min: Vector2F::zero(),
2351                        max: vec2f(
2352                            (120. * em_width) // Default size
2353                                .min(size.x() / 2.) // Shrink to half of the editor width
2354                                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2355                            (16. * line_height) // Default size
2356                                .min(size.y() / 2.) // Shrink to half of the editor height
2357                                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2358                        ),
2359                    },
2360                    editor,
2361                    cx,
2362                );
2363            }
2364        }
2365
2366        let invisible_symbol_font_size = self.style.text.font_size / 2.0;
2367        let invisible_symbol_style = RunStyle {
2368            color: self.style.whitespace,
2369            font_id: self.style.text.font_id,
2370            underline: Default::default(),
2371        };
2372
2373        (
2374            size,
2375            LayoutState {
2376                mode,
2377                position_map: Arc::new(PositionMap {
2378                    size,
2379                    scroll_max,
2380                    line_layouts,
2381                    line_height,
2382                    em_width,
2383                    em_advance,
2384                    snapshot,
2385                }),
2386                visible_display_row_range: start_row..end_row,
2387                gutter_size,
2388                gutter_padding,
2389                text_size,
2390                scrollbar_row_range,
2391                show_scrollbars,
2392                is_singleton,
2393                max_row,
2394                gutter_margin,
2395                active_rows,
2396                highlighted_rows,
2397                highlighted_ranges,
2398                fold_ranges,
2399                line_number_layouts,
2400                display_hunks,
2401                blocks,
2402                selections,
2403                context_menu,
2404                code_actions_indicator,
2405                fold_indicators,
2406                tab_invisible: cx.text_layout_cache().layout_str(
2407                    "",
2408                    invisible_symbol_font_size,
2409                    &[("".len(), invisible_symbol_style)],
2410                ),
2411                space_invisible: cx.text_layout_cache().layout_str(
2412                    "",
2413                    invisible_symbol_font_size,
2414                    &[("".len(), invisible_symbol_style)],
2415                ),
2416                hover_popovers: hover,
2417            },
2418        )
2419    }
2420
2421    fn paint(
2422        &mut self,
2423        scene: &mut SceneBuilder,
2424        bounds: RectF,
2425        visible_bounds: RectF,
2426        layout: &mut Self::LayoutState,
2427        editor: &mut Editor,
2428        cx: &mut ViewContext<Editor>,
2429    ) -> Self::PaintState {
2430        let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
2431        scene.push_layer(Some(visible_bounds));
2432
2433        let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
2434        let text_bounds = RectF::new(
2435            bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
2436            layout.text_size,
2437        );
2438
2439        Self::attach_mouse_handlers(
2440            scene,
2441            &layout.position_map,
2442            layout.hover_popovers.is_some(),
2443            visible_bounds,
2444            text_bounds,
2445            gutter_bounds,
2446            bounds,
2447            cx,
2448        );
2449
2450        self.paint_background(scene, gutter_bounds, text_bounds, layout);
2451        if layout.gutter_size.x() > 0. {
2452            self.paint_gutter(scene, gutter_bounds, visible_bounds, layout, editor, cx);
2453        }
2454        self.paint_text(scene, text_bounds, visible_bounds, layout, editor, cx);
2455
2456        scene.push_layer(Some(bounds));
2457        if !layout.blocks.is_empty() {
2458            self.paint_blocks(scene, bounds, visible_bounds, layout, editor, cx);
2459        }
2460        self.paint_scrollbar(scene, bounds, layout, cx, &editor);
2461        scene.pop_layer();
2462
2463        scene.pop_layer();
2464    }
2465
2466    fn rect_for_text_range(
2467        &self,
2468        range_utf16: Range<usize>,
2469        bounds: RectF,
2470        _: RectF,
2471        layout: &Self::LayoutState,
2472        _: &Self::PaintState,
2473        _: &Editor,
2474        _: &ViewContext<Editor>,
2475    ) -> Option<RectF> {
2476        let text_bounds = RectF::new(
2477            bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
2478            layout.text_size,
2479        );
2480        let content_origin = text_bounds.origin() + vec2f(layout.gutter_margin, 0.);
2481        let scroll_position = layout.position_map.snapshot.scroll_position();
2482        let start_row = scroll_position.y() as u32;
2483        let scroll_top = scroll_position.y() * layout.position_map.line_height;
2484        let scroll_left = scroll_position.x() * layout.position_map.em_width;
2485
2486        let range_start = OffsetUtf16(range_utf16.start)
2487            .to_display_point(&layout.position_map.snapshot.display_snapshot);
2488        if range_start.row() < start_row {
2489            return None;
2490        }
2491
2492        let line = &layout
2493            .position_map
2494            .line_layouts
2495            .get((range_start.row() - start_row) as usize)?
2496            .line;
2497        let range_start_x = line.x_for_index(range_start.column() as usize);
2498        let range_start_y = range_start.row() as f32 * layout.position_map.line_height;
2499        Some(RectF::new(
2500            content_origin
2501                + vec2f(
2502                    range_start_x,
2503                    range_start_y + layout.position_map.line_height,
2504                )
2505                - vec2f(scroll_left, scroll_top),
2506            vec2f(
2507                layout.position_map.em_width,
2508                layout.position_map.line_height,
2509            ),
2510        ))
2511    }
2512
2513    fn debug(
2514        &self,
2515        bounds: RectF,
2516        _: &Self::LayoutState,
2517        _: &Self::PaintState,
2518        _: &Editor,
2519        _: &ViewContext<Editor>,
2520    ) -> json::Value {
2521        json!({
2522            "type": "BufferElement",
2523            "bounds": bounds.to_json()
2524        })
2525    }
2526}
2527
2528type BufferRow = u32;
2529
2530pub struct LayoutState {
2531    position_map: Arc<PositionMap>,
2532    gutter_size: Vector2F,
2533    gutter_padding: f32,
2534    gutter_margin: f32,
2535    text_size: Vector2F,
2536    mode: EditorMode,
2537    visible_display_row_range: Range<u32>,
2538    active_rows: BTreeMap<u32, bool>,
2539    highlighted_rows: Option<Range<u32>>,
2540    line_number_layouts: Vec<Option<text_layout::Line>>,
2541    display_hunks: Vec<DisplayDiffHunk>,
2542    blocks: Vec<BlockLayout>,
2543    highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
2544    fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)>,
2545    selections: Vec<(ReplicaId, Vec<SelectionLayout>)>,
2546    scrollbar_row_range: Range<f32>,
2547    show_scrollbars: bool,
2548    is_singleton: bool,
2549    max_row: u32,
2550    context_menu: Option<(DisplayPoint, AnyElement<Editor>)>,
2551    code_actions_indicator: Option<(u32, AnyElement<Editor>)>,
2552    hover_popovers: Option<(DisplayPoint, Vec<AnyElement<Editor>>)>,
2553    fold_indicators: Vec<Option<AnyElement<Editor>>>,
2554    tab_invisible: Line,
2555    space_invisible: Line,
2556}
2557
2558struct PositionMap {
2559    size: Vector2F,
2560    line_height: f32,
2561    scroll_max: Vector2F,
2562    em_width: f32,
2563    em_advance: f32,
2564    line_layouts: Vec<LineWithInvisibles>,
2565    snapshot: EditorSnapshot,
2566}
2567
2568impl PositionMap {
2569    /// Returns two display points:
2570    /// 1. The nearest *valid* position in the editor
2571    /// 2. An unclipped, potentially *invalid* position that maps directly to
2572    ///    the given pixel position.
2573    fn point_for_position(
2574        &self,
2575        text_bounds: RectF,
2576        position: Vector2F,
2577    ) -> (DisplayPoint, DisplayPoint) {
2578        let scroll_position = self.snapshot.scroll_position();
2579        let position = position - text_bounds.origin();
2580        let y = position.y().max(0.0).min(self.size.y());
2581        let x = position.x() + (scroll_position.x() * self.em_width);
2582        let row = (y / self.line_height + scroll_position.y()) as u32;
2583        let (column, x_overshoot) = if let Some(line) = self
2584            .line_layouts
2585            .get(row as usize - scroll_position.y() as usize)
2586            .map(|line_with_spaces| &line_with_spaces.line)
2587        {
2588            if let Some(ix) = line.index_for_x(x) {
2589                (ix as u32, 0.0)
2590            } else {
2591                (line.len() as u32, 0f32.max(x - line.width()))
2592            }
2593        } else {
2594            (0, x)
2595        };
2596
2597        let mut target_point = DisplayPoint::new(row, column);
2598        let point = self.snapshot.clip_point(target_point, Bias::Left);
2599        *target_point.column_mut() += (x_overshoot / self.em_advance) as u32;
2600
2601        (point, target_point)
2602    }
2603}
2604
2605struct BlockLayout {
2606    row: u32,
2607    element: AnyElement<Editor>,
2608    style: BlockStyle,
2609}
2610
2611fn layout_line(
2612    row: u32,
2613    snapshot: &EditorSnapshot,
2614    style: &EditorStyle,
2615    layout_cache: &TextLayoutCache,
2616) -> text_layout::Line {
2617    let mut line = snapshot.line(row);
2618
2619    if line.len() > MAX_LINE_LEN {
2620        let mut len = MAX_LINE_LEN;
2621        while !line.is_char_boundary(len) {
2622            len -= 1;
2623        }
2624
2625        line.truncate(len);
2626    }
2627
2628    layout_cache.layout_str(
2629        &line,
2630        style.text.font_size,
2631        &[(
2632            snapshot.line_len(row) as usize,
2633            RunStyle {
2634                font_id: style.text.font_id,
2635                color: Color::black(),
2636                underline: Default::default(),
2637            },
2638        )],
2639    )
2640}
2641
2642#[derive(Debug)]
2643pub struct Cursor {
2644    origin: Vector2F,
2645    block_width: f32,
2646    line_height: f32,
2647    color: Color,
2648    shape: CursorShape,
2649    block_text: Option<Line>,
2650}
2651
2652impl Cursor {
2653    pub fn new(
2654        origin: Vector2F,
2655        block_width: f32,
2656        line_height: f32,
2657        color: Color,
2658        shape: CursorShape,
2659        block_text: Option<Line>,
2660    ) -> Cursor {
2661        Cursor {
2662            origin,
2663            block_width,
2664            line_height,
2665            color,
2666            shape,
2667            block_text,
2668        }
2669    }
2670
2671    pub fn bounding_rect(&self, origin: Vector2F) -> RectF {
2672        RectF::new(
2673            self.origin + origin,
2674            vec2f(self.block_width, self.line_height),
2675        )
2676    }
2677
2678    pub fn paint(&self, scene: &mut SceneBuilder, origin: Vector2F, cx: &mut WindowContext) {
2679        let bounds = match self.shape {
2680            CursorShape::Bar => RectF::new(self.origin + origin, vec2f(2.0, self.line_height)),
2681            CursorShape::Block | CursorShape::Hollow => RectF::new(
2682                self.origin + origin,
2683                vec2f(self.block_width, self.line_height),
2684            ),
2685            CursorShape::Underscore => RectF::new(
2686                self.origin + origin + Vector2F::new(0.0, self.line_height - 2.0),
2687                vec2f(self.block_width, 2.0),
2688            ),
2689        };
2690
2691        //Draw background or border quad
2692        if matches!(self.shape, CursorShape::Hollow) {
2693            scene.push_quad(Quad {
2694                bounds,
2695                background: None,
2696                border: Border::all(1., self.color),
2697                corner_radius: 0.,
2698            });
2699        } else {
2700            scene.push_quad(Quad {
2701                bounds,
2702                background: Some(self.color),
2703                border: Default::default(),
2704                corner_radius: 0.,
2705            });
2706        }
2707
2708        if let Some(block_text) = &self.block_text {
2709            block_text.paint(scene, self.origin + origin, bounds, self.line_height, cx);
2710        }
2711    }
2712
2713    pub fn shape(&self) -> CursorShape {
2714        self.shape
2715    }
2716}
2717
2718#[derive(Debug)]
2719pub struct HighlightedRange {
2720    pub start_y: f32,
2721    pub line_height: f32,
2722    pub lines: Vec<HighlightedRangeLine>,
2723    pub color: Color,
2724    pub corner_radius: f32,
2725}
2726
2727#[derive(Debug)]
2728pub struct HighlightedRangeLine {
2729    pub start_x: f32,
2730    pub end_x: f32,
2731}
2732
2733impl HighlightedRange {
2734    pub fn paint(&self, bounds: RectF, scene: &mut SceneBuilder) {
2735        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
2736            self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
2737            self.paint_lines(
2738                self.start_y + self.line_height,
2739                &self.lines[1..],
2740                bounds,
2741                scene,
2742            );
2743        } else {
2744            self.paint_lines(self.start_y, &self.lines, bounds, scene);
2745        }
2746    }
2747
2748    fn paint_lines(
2749        &self,
2750        start_y: f32,
2751        lines: &[HighlightedRangeLine],
2752        bounds: RectF,
2753        scene: &mut SceneBuilder,
2754    ) {
2755        if lines.is_empty() {
2756            return;
2757        }
2758
2759        let mut path = PathBuilder::new();
2760        let first_line = lines.first().unwrap();
2761        let last_line = lines.last().unwrap();
2762
2763        let first_top_left = vec2f(first_line.start_x, start_y);
2764        let first_top_right = vec2f(first_line.end_x, start_y);
2765
2766        let curve_height = vec2f(0., self.corner_radius);
2767        let curve_width = |start_x: f32, end_x: f32| {
2768            let max = (end_x - start_x) / 2.;
2769            let width = if max < self.corner_radius {
2770                max
2771            } else {
2772                self.corner_radius
2773            };
2774
2775            vec2f(width, 0.)
2776        };
2777
2778        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
2779        path.reset(first_top_right - top_curve_width);
2780        path.curve_to(first_top_right + curve_height, first_top_right);
2781
2782        let mut iter = lines.iter().enumerate().peekable();
2783        while let Some((ix, line)) = iter.next() {
2784            let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
2785
2786            if let Some((_, next_line)) = iter.peek() {
2787                let next_top_right = vec2f(next_line.end_x, bottom_right.y());
2788
2789                match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
2790                    Ordering::Equal => {
2791                        path.line_to(bottom_right);
2792                    }
2793                    Ordering::Less => {
2794                        let curve_width = curve_width(next_top_right.x(), bottom_right.x());
2795                        path.line_to(bottom_right - curve_height);
2796                        if self.corner_radius > 0. {
2797                            path.curve_to(bottom_right - curve_width, bottom_right);
2798                        }
2799                        path.line_to(next_top_right + curve_width);
2800                        if self.corner_radius > 0. {
2801                            path.curve_to(next_top_right + curve_height, next_top_right);
2802                        }
2803                    }
2804                    Ordering::Greater => {
2805                        let curve_width = curve_width(bottom_right.x(), next_top_right.x());
2806                        path.line_to(bottom_right - curve_height);
2807                        if self.corner_radius > 0. {
2808                            path.curve_to(bottom_right + curve_width, bottom_right);
2809                        }
2810                        path.line_to(next_top_right - curve_width);
2811                        if self.corner_radius > 0. {
2812                            path.curve_to(next_top_right + curve_height, next_top_right);
2813                        }
2814                    }
2815                }
2816            } else {
2817                let curve_width = curve_width(line.start_x, line.end_x);
2818                path.line_to(bottom_right - curve_height);
2819                if self.corner_radius > 0. {
2820                    path.curve_to(bottom_right - curve_width, bottom_right);
2821                }
2822
2823                let bottom_left = vec2f(line.start_x, bottom_right.y());
2824                path.line_to(bottom_left + curve_width);
2825                if self.corner_radius > 0. {
2826                    path.curve_to(bottom_left - curve_height, bottom_left);
2827                }
2828            }
2829        }
2830
2831        if first_line.start_x > last_line.start_x {
2832            let curve_width = curve_width(last_line.start_x, first_line.start_x);
2833            let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
2834            path.line_to(second_top_left + curve_height);
2835            if self.corner_radius > 0. {
2836                path.curve_to(second_top_left + curve_width, second_top_left);
2837            }
2838            let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
2839            path.line_to(first_bottom_left - curve_width);
2840            if self.corner_radius > 0. {
2841                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
2842            }
2843        }
2844
2845        path.line_to(first_top_left + curve_height);
2846        if self.corner_radius > 0. {
2847            path.curve_to(first_top_left + top_curve_width, first_top_left);
2848        }
2849        path.line_to(first_top_right - top_curve_width);
2850
2851        scene.push_path(path.build(self.color, Some(bounds)));
2852    }
2853}
2854
2855fn position_to_display_point(
2856    position: Vector2F,
2857    text_bounds: RectF,
2858    position_map: &PositionMap,
2859) -> Option<DisplayPoint> {
2860    if text_bounds.contains_point(position) {
2861        let (point, target_point) = position_map.point_for_position(text_bounds, position);
2862        if point == target_point {
2863            Some(point)
2864        } else {
2865            None
2866        }
2867    } else {
2868        None
2869    }
2870}
2871
2872fn range_to_bounds(
2873    range: &Range<DisplayPoint>,
2874    content_origin: Vector2F,
2875    scroll_left: f32,
2876    scroll_top: f32,
2877    visible_row_range: &Range<u32>,
2878    line_end_overshoot: f32,
2879    position_map: &PositionMap,
2880) -> impl Iterator<Item = RectF> {
2881    let mut bounds: SmallVec<[RectF; 1]> = SmallVec::new();
2882
2883    if range.start == range.end {
2884        return bounds.into_iter();
2885    }
2886
2887    let start_row = visible_row_range.start;
2888    let end_row = visible_row_range.end;
2889
2890    let row_range = if range.end.column() == 0 {
2891        cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
2892    } else {
2893        cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
2894    };
2895
2896    let first_y =
2897        content_origin.y() + row_range.start as f32 * position_map.line_height - scroll_top;
2898
2899    for (idx, row) in row_range.enumerate() {
2900        let line_layout = &position_map.line_layouts[(row - start_row) as usize].line;
2901
2902        let start_x = if row == range.start.row() {
2903            content_origin.x() + line_layout.x_for_index(range.start.column() as usize)
2904                - scroll_left
2905        } else {
2906            content_origin.x() - scroll_left
2907        };
2908
2909        let end_x = if row == range.end.row() {
2910            content_origin.x() + line_layout.x_for_index(range.end.column() as usize) - scroll_left
2911        } else {
2912            content_origin.x() + line_layout.width() + line_end_overshoot - scroll_left
2913        };
2914
2915        bounds.push(RectF::from_points(
2916            vec2f(start_x, first_y + position_map.line_height * idx as f32),
2917            vec2f(end_x, first_y + position_map.line_height * (idx + 1) as f32),
2918        ))
2919    }
2920
2921    bounds.into_iter()
2922}
2923
2924pub fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
2925    delta.powf(1.5) / 100.0
2926}
2927
2928fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
2929    delta.powf(1.2) / 300.0
2930}
2931
2932#[cfg(test)]
2933mod tests {
2934    use super::*;
2935    use crate::{
2936        display_map::{BlockDisposition, BlockProperties},
2937        editor_tests::{init_test, update_test_language_settings},
2938        Editor, MultiBuffer,
2939    };
2940    use gpui::TestAppContext;
2941    use language::language_settings;
2942    use log::info;
2943    use std::{num::NonZeroU32, sync::Arc};
2944    use util::test::sample_text;
2945
2946    #[gpui::test]
2947    fn test_layout_line_numbers(cx: &mut TestAppContext) {
2948        init_test(cx, |_| {});
2949
2950        let (_, editor) = cx.add_window(|cx| {
2951            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
2952            Editor::new(EditorMode::Full, buffer, None, None, cx)
2953        });
2954        let element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
2955
2956        let layouts = editor.update(cx, |editor, cx| {
2957            let snapshot = editor.snapshot(cx);
2958            element
2959                .layout_line_numbers(0..6, &Default::default(), false, &snapshot, cx)
2960                .0
2961        });
2962        assert_eq!(layouts.len(), 6);
2963    }
2964
2965    #[gpui::test]
2966    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
2967        init_test(cx, |_| {});
2968
2969        let (_, editor) = cx.add_window(|cx| {
2970            let buffer = MultiBuffer::build_simple("", cx);
2971            Editor::new(EditorMode::Full, buffer, None, None, cx)
2972        });
2973
2974        editor.update(cx, |editor, cx| {
2975            editor.set_placeholder_text("hello", cx);
2976            editor.insert_blocks(
2977                [BlockProperties {
2978                    style: BlockStyle::Fixed,
2979                    disposition: BlockDisposition::Above,
2980                    height: 3,
2981                    position: Anchor::min(),
2982                    render: Arc::new(|_| Empty::new().into_any()),
2983                }],
2984                None,
2985                cx,
2986            );
2987
2988            // Blur the editor so that it displays placeholder text.
2989            cx.blur();
2990        });
2991
2992        let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
2993        let (size, mut state) = editor.update(cx, |editor, cx| {
2994            let mut new_parents = Default::default();
2995            let mut notify_views_if_parents_change = Default::default();
2996            let mut layout_cx = LayoutContext::new(
2997                cx,
2998                &mut new_parents,
2999                &mut notify_views_if_parents_change,
3000                false,
3001            );
3002            element.layout(
3003                SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
3004                editor,
3005                &mut layout_cx,
3006            )
3007        });
3008
3009        assert_eq!(state.position_map.line_layouts.len(), 4);
3010        assert_eq!(
3011            state
3012                .line_number_layouts
3013                .iter()
3014                .map(Option::is_some)
3015                .collect::<Vec<_>>(),
3016            &[false, false, false, true]
3017        );
3018
3019        // Don't panic.
3020        let mut scene = SceneBuilder::new(1.0);
3021        let bounds = RectF::new(Default::default(), size);
3022        editor.update(cx, |editor, cx| {
3023            element.paint(&mut scene, bounds, bounds, &mut state, editor, cx);
3024        });
3025    }
3026
3027    #[gpui::test]
3028    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
3029        const TAB_SIZE: u32 = 4;
3030
3031        let input_text = "\t \t|\t| a b";
3032        let expected_invisibles = vec![
3033            Invisible::Tab {
3034                line_start_offset: 0,
3035            },
3036            Invisible::Whitespace {
3037                line_offset: TAB_SIZE as usize,
3038            },
3039            Invisible::Tab {
3040                line_start_offset: TAB_SIZE as usize + 1,
3041            },
3042            Invisible::Tab {
3043                line_start_offset: TAB_SIZE as usize * 2 + 1,
3044            },
3045            Invisible::Whitespace {
3046                line_offset: TAB_SIZE as usize * 3 + 1,
3047            },
3048            Invisible::Whitespace {
3049                line_offset: TAB_SIZE as usize * 3 + 3,
3050            },
3051        ];
3052        assert_eq!(
3053            expected_invisibles.len(),
3054            input_text
3055                .chars()
3056                .filter(|initial_char| initial_char.is_whitespace())
3057                .count(),
3058            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
3059        );
3060
3061        init_test(cx, |s| {
3062            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3063            s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
3064        });
3065
3066        let actual_invisibles =
3067            collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, 500.0);
3068
3069        assert_eq!(expected_invisibles, actual_invisibles);
3070    }
3071
3072    #[gpui::test]
3073    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
3074        init_test(cx, |s| {
3075            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3076            s.defaults.tab_size = NonZeroU32::new(4);
3077        });
3078
3079        for editor_mode_without_invisibles in [
3080            EditorMode::SingleLine,
3081            EditorMode::AutoHeight { max_lines: 100 },
3082        ] {
3083            let invisibles = collect_invisibles_from_new_editor(
3084                cx,
3085                editor_mode_without_invisibles,
3086                "\t\t\t| | a b",
3087                500.0,
3088            );
3089            assert!(invisibles.is_empty(),
3090                "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
3091        }
3092    }
3093
3094    #[gpui::test]
3095    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
3096        let tab_size = 4;
3097        let input_text = "a\tbcd   ".repeat(9);
3098        let repeated_invisibles = [
3099            Invisible::Tab {
3100                line_start_offset: 1,
3101            },
3102            Invisible::Whitespace {
3103                line_offset: tab_size as usize + 3,
3104            },
3105            Invisible::Whitespace {
3106                line_offset: tab_size as usize + 4,
3107            },
3108            Invisible::Whitespace {
3109                line_offset: tab_size as usize + 5,
3110            },
3111        ];
3112        let expected_invisibles = std::iter::once(repeated_invisibles)
3113            .cycle()
3114            .take(9)
3115            .flatten()
3116            .collect::<Vec<_>>();
3117        assert_eq!(
3118            expected_invisibles.len(),
3119            input_text
3120                .chars()
3121                .filter(|initial_char| initial_char.is_whitespace())
3122                .count(),
3123            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
3124        );
3125        info!("Expected invisibles: {expected_invisibles:?}");
3126
3127        init_test(cx, |_| {});
3128
3129        // Put the same string with repeating whitespace pattern into editors of various size,
3130        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
3131        let resize_step = 10.0;
3132        let mut editor_width = 200.0;
3133        while editor_width <= 1000.0 {
3134            update_test_language_settings(cx, |s| {
3135                s.defaults.tab_size = NonZeroU32::new(tab_size);
3136                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3137                s.defaults.preferred_line_length = Some(editor_width as u32);
3138                s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
3139            });
3140
3141            let actual_invisibles =
3142                collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, editor_width);
3143
3144            // Whatever the editor size is, ensure it has the same invisible kinds in the same order
3145            // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
3146            let mut i = 0;
3147            for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
3148                i = actual_index;
3149                match expected_invisibles.get(i) {
3150                    Some(expected_invisible) => match (expected_invisible, actual_invisible) {
3151                        (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
3152                        | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
3153                        _ => {
3154                            panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
3155                        }
3156                    },
3157                    None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
3158                }
3159            }
3160            let missing_expected_invisibles = &expected_invisibles[i + 1..];
3161            assert!(
3162                missing_expected_invisibles.is_empty(),
3163                "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
3164            );
3165
3166            editor_width += resize_step;
3167        }
3168    }
3169
3170    fn collect_invisibles_from_new_editor(
3171        cx: &mut TestAppContext,
3172        editor_mode: EditorMode,
3173        input_text: &str,
3174        editor_width: f32,
3175    ) -> Vec<Invisible> {
3176        info!(
3177            "Creating editor with mode {editor_mode:?}, width {editor_width} and text '{input_text}'"
3178        );
3179        let (_, editor) = cx.add_window(|cx| {
3180            let buffer = MultiBuffer::build_simple(&input_text, cx);
3181            Editor::new(editor_mode, buffer, None, None, cx)
3182        });
3183
3184        let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3185        let (_, layout_state) = editor.update(cx, |editor, cx| {
3186            editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
3187            editor.set_wrap_width(Some(editor_width), cx);
3188
3189            let mut new_parents = Default::default();
3190            let mut notify_views_if_parents_change = Default::default();
3191            let mut layout_cx = LayoutContext::new(
3192                cx,
3193                &mut new_parents,
3194                &mut notify_views_if_parents_change,
3195                false,
3196            );
3197            element.layout(
3198                SizeConstraint::new(vec2f(editor_width, 500.), vec2f(editor_width, 500.)),
3199                editor,
3200                &mut layout_cx,
3201            )
3202        });
3203
3204        layout_state
3205            .position_map
3206            .line_layouts
3207            .iter()
3208            .map(|line_with_invisibles| &line_with_invisibles.invisibles)
3209            .flatten()
3210            .cloned()
3211            .collect()
3212    }
3213}