element.rs

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