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