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