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