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