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