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