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