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