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    Axis, Border, CursorRegion, Drawable, 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                                .boxed()
1451                        })
1452                        .with_cursor_style(CursorStyle::PointingHand)
1453                        .on_click(MouseButton::Left, move |_, _, cx| {
1454                            cx.dispatch_action(jump_action.clone())
1455                        })
1456                        .with_tooltip::<JumpIcon>(
1457                            id.into(),
1458                            "Jump to Buffer".to_string(),
1459                            Some(Box::new(crate::OpenExcerpts)),
1460                            tooltip_style.clone(),
1461                            cx,
1462                        )
1463                        .aligned()
1464                        .flex_float()
1465                        .boxed()
1466                    });
1467
1468                    if *starts_new_buffer {
1469                        let style = &self.style.diagnostic_path_header;
1470                        let font_size =
1471                            (style.text_scale_factor * self.style.text.font_size).round();
1472
1473                        let path = buffer.resolve_file_path(cx, include_root);
1474                        let mut filename = None;
1475                        let mut parent_path = None;
1476                        // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
1477                        if let Some(path) = path {
1478                            filename = path.file_name().map(|f| f.to_string_lossy().to_string());
1479                            parent_path =
1480                                path.parent().map(|p| p.to_string_lossy().to_string() + "/");
1481                        }
1482
1483                        Flex::row()
1484                            .with_child(
1485                                Label::new(
1486                                    filename.unwrap_or_else(|| "untitled".to_string()),
1487                                    style.filename.text.clone().with_font_size(font_size),
1488                                )
1489                                .contained()
1490                                .with_style(style.filename.container)
1491                                .aligned()
1492                                .boxed(),
1493                            )
1494                            .with_children(parent_path.map(|path| {
1495                                Label::new(path, style.path.text.clone().with_font_size(font_size))
1496                                    .contained()
1497                                    .with_style(style.path.container)
1498                                    .aligned()
1499                                    .boxed()
1500                            }))
1501                            .with_children(jump_icon)
1502                            .contained()
1503                            .with_style(style.container)
1504                            .with_padding_left(gutter_padding)
1505                            .with_padding_right(gutter_padding)
1506                            .expanded()
1507                            .named("path header block")
1508                    } else {
1509                        let text_style = self.style.text.clone();
1510                        Flex::row()
1511                            .with_child(Label::new("", text_style).boxed())
1512                            .with_children(jump_icon)
1513                            .contained()
1514                            .with_padding_left(gutter_padding)
1515                            .with_padding_right(gutter_padding)
1516                            .expanded()
1517                            .named("collapsed context")
1518                    }
1519                }
1520            };
1521
1522            element.layout(
1523                SizeConstraint {
1524                    min: Vector2F::zero(),
1525                    max: vec2f(width, block.height() as f32 * line_height),
1526                },
1527                editor,
1528                cx,
1529            );
1530            element
1531        };
1532
1533        let mut fixed_block_max_width = 0f32;
1534        let mut blocks = Vec::new();
1535        for (row, block) in fixed_blocks {
1536            let element = render_block(block, f32::INFINITY);
1537            fixed_block_max_width = fixed_block_max_width.max(element.size().x() + em_width);
1538            blocks.push(BlockLayout {
1539                row,
1540                element,
1541                style: BlockStyle::Fixed,
1542            });
1543        }
1544        for (row, block) in non_fixed_blocks {
1545            let style = match block {
1546                TransformBlock::Custom(block) => block.style(),
1547                TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
1548            };
1549            let width = match style {
1550                BlockStyle::Sticky => editor_width,
1551                BlockStyle::Flex => editor_width
1552                    .max(fixed_block_max_width)
1553                    .max(gutter_width + scroll_width),
1554                BlockStyle::Fixed => unreachable!(),
1555            };
1556            let element = render_block(block, width);
1557            blocks.push(BlockLayout {
1558                row,
1559                element,
1560                style,
1561            });
1562        }
1563        (
1564            scroll_width.max(fixed_block_max_width - gutter_width),
1565            blocks,
1566        )
1567    }
1568}
1569
1570impl Drawable<Editor> for EditorElement {
1571    type LayoutState = LayoutState;
1572    type PaintState = ();
1573
1574    fn layout(
1575        &mut self,
1576        constraint: SizeConstraint,
1577        editor: &mut Editor,
1578        cx: &mut ViewContext<Editor>,
1579    ) -> (Vector2F, Self::LayoutState) {
1580        let mut size = constraint.max;
1581        if size.x().is_infinite() {
1582            unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
1583        }
1584
1585        let snapshot = editor.snapshot(cx);
1586        let style = self.style.clone();
1587        let line_height = style.text.line_height(cx.font_cache());
1588
1589        let gutter_padding;
1590        let gutter_width;
1591        let gutter_margin;
1592        if snapshot.mode == EditorMode::Full {
1593            gutter_padding = style.text.em_width(cx.font_cache()) * style.gutter_padding_factor;
1594            gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
1595            gutter_margin = -style.text.descent(cx.font_cache());
1596        } else {
1597            gutter_padding = 0.0;
1598            gutter_width = 0.0;
1599            gutter_margin = 0.0;
1600        };
1601
1602        let text_width = size.x() - gutter_width;
1603        let em_width = style.text.em_width(cx.font_cache());
1604        let em_advance = style.text.em_advance(cx.font_cache());
1605        let overscroll = vec2f(em_width, 0.);
1606        let snapshot = {
1607            editor.set_visible_line_count(size.y() / line_height);
1608
1609            let editor_width = text_width - gutter_margin - overscroll.x() - em_width;
1610            let wrap_width = match editor.soft_wrap_mode(cx) {
1611                SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
1612                SoftWrap::EditorWidth => editor_width,
1613                SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
1614            };
1615
1616            if editor.set_wrap_width(Some(wrap_width), cx) {
1617                editor.snapshot(cx)
1618            } else {
1619                snapshot
1620            }
1621        };
1622
1623        let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
1624        if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
1625            size.set_y(
1626                scroll_height
1627                    .min(constraint.max_along(Axis::Vertical))
1628                    .max(constraint.min_along(Axis::Vertical))
1629                    .min(line_height * max_lines as f32),
1630            )
1631        } else if let EditorMode::SingleLine = snapshot.mode {
1632            size.set_y(
1633                line_height
1634                    .min(constraint.max_along(Axis::Vertical))
1635                    .max(constraint.min_along(Axis::Vertical)),
1636            )
1637        } else if size.y().is_infinite() {
1638            size.set_y(scroll_height);
1639        }
1640        let gutter_size = vec2f(gutter_width, size.y());
1641        let text_size = vec2f(text_width, size.y());
1642
1643        let autoscroll_horizontally = editor.autoscroll_vertically(size.y(), line_height, cx);
1644        let mut snapshot = editor.snapshot(cx);
1645
1646        let scroll_position = snapshot.scroll_position();
1647        // The scroll position is a fractional point, the whole number of which represents
1648        // the top of the window in terms of display rows.
1649        let start_row = scroll_position.y() as u32;
1650        let height_in_lines = size.y() / line_height;
1651        let max_row = snapshot.max_point().row();
1652
1653        // Add 1 to ensure selections bleed off screen
1654        let end_row = 1 + cmp::min(
1655            (scroll_position.y() + height_in_lines).ceil() as u32,
1656            max_row,
1657        );
1658
1659        let start_anchor = if start_row == 0 {
1660            Anchor::min()
1661        } else {
1662            snapshot
1663                .buffer_snapshot
1664                .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
1665        };
1666        let end_anchor = if end_row > max_row {
1667            Anchor::max()
1668        } else {
1669            snapshot
1670                .buffer_snapshot
1671                .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
1672        };
1673
1674        let mut selections: Vec<(ReplicaId, Vec<SelectionLayout>)> = Vec::new();
1675        let mut active_rows = BTreeMap::new();
1676        let mut fold_ranges = Vec::new();
1677        let is_singleton = editor.is_singleton(cx);
1678
1679        let highlighted_rows = editor.highlighted_rows();
1680        let theme = cx.global::<Settings>().theme.as_ref();
1681        let highlighted_ranges = editor.background_highlights_in_range(
1682            start_anchor..end_anchor,
1683            &snapshot.display_snapshot,
1684            theme,
1685        );
1686
1687        fold_ranges.extend(
1688            snapshot
1689                .folds_in_range(start_anchor..end_anchor)
1690                .map(|anchor| {
1691                    let start = anchor.start.to_point(&snapshot.buffer_snapshot);
1692                    (
1693                        start.row,
1694                        start.to_display_point(&snapshot.display_snapshot)
1695                            ..anchor.end.to_display_point(&snapshot),
1696                    )
1697                }),
1698        );
1699
1700        let mut remote_selections = HashMap::default();
1701        for (replica_id, line_mode, cursor_shape, selection) in snapshot
1702            .buffer_snapshot
1703            .remote_selections_in_range(&(start_anchor..end_anchor))
1704        {
1705            // The local selections match the leader's selections.
1706            if Some(replica_id) == editor.leader_replica_id {
1707                continue;
1708            }
1709            remote_selections
1710                .entry(replica_id)
1711                .or_insert(Vec::new())
1712                .push(SelectionLayout::new(
1713                    selection,
1714                    line_mode,
1715                    cursor_shape,
1716                    &snapshot.display_snapshot,
1717                ));
1718        }
1719        selections.extend(remote_selections);
1720
1721        if editor.show_local_selections {
1722            let mut local_selections = editor
1723                .selections
1724                .disjoint_in_range(start_anchor..end_anchor, cx);
1725            local_selections.extend(editor.selections.pending(cx));
1726            for selection in &local_selections {
1727                let is_empty = selection.start == selection.end;
1728                let selection_start = snapshot.prev_line_boundary(selection.start).1;
1729                let selection_end = snapshot.next_line_boundary(selection.end).1;
1730                for row in cmp::max(selection_start.row(), start_row)
1731                    ..=cmp::min(selection_end.row(), end_row)
1732                {
1733                    let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
1734                    *contains_non_empty_selection |= !is_empty;
1735                }
1736            }
1737
1738            // Render the local selections in the leader's color when following.
1739            let local_replica_id = editor
1740                .leader_replica_id
1741                .unwrap_or_else(|| editor.replica_id(cx));
1742
1743            selections.push((
1744                local_replica_id,
1745                local_selections
1746                    .into_iter()
1747                    .map(|selection| {
1748                        SelectionLayout::new(
1749                            selection,
1750                            editor.selections.line_mode,
1751                            editor.cursor_shape,
1752                            &snapshot.display_snapshot,
1753                        )
1754                    })
1755                    .collect(),
1756            ));
1757        }
1758
1759        let show_scrollbars = editor.scroll_manager.scrollbars_visible();
1760        let include_root = editor
1761            .project
1762            .as_ref()
1763            .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
1764            .unwrap_or_default();
1765
1766        let fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)> = fold_ranges
1767            .into_iter()
1768            .map(|(id, fold)| {
1769                let color = self
1770                    .style
1771                    .folds
1772                    .ellipses
1773                    .background
1774                    .style_for(&mut cx.mouse_state::<FoldMarkers>(id as usize), false)
1775                    .color;
1776
1777                (id, fold, color)
1778            })
1779            .collect();
1780
1781        let (line_number_layouts, fold_statuses) = self.layout_line_numbers(
1782            start_row..end_row,
1783            &active_rows,
1784            is_singleton,
1785            &snapshot,
1786            cx,
1787        );
1788
1789        let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
1790
1791        let scrollbar_row_range = scroll_position.y()..(scroll_position.y() + height_in_lines);
1792
1793        let mut max_visible_line_width = 0.0;
1794        let line_layouts = self.layout_lines(start_row..end_row, &snapshot, cx);
1795        for line in &line_layouts {
1796            if line.width() > max_visible_line_width {
1797                max_visible_line_width = line.width();
1798            }
1799        }
1800
1801        let style = self.style.clone();
1802        let longest_line_width = layout_line(
1803            snapshot.longest_row(),
1804            &snapshot,
1805            &style,
1806            cx.text_layout_cache(),
1807        )
1808        .width();
1809        let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
1810        let em_width = style.text.em_width(cx.font_cache());
1811        let (scroll_width, blocks) = self.layout_blocks(
1812            start_row..end_row,
1813            &snapshot,
1814            size.x(),
1815            scroll_width,
1816            gutter_padding,
1817            gutter_width,
1818            em_width,
1819            gutter_width + gutter_margin,
1820            line_height,
1821            &style,
1822            &line_layouts,
1823            include_root,
1824            editor,
1825            cx,
1826        );
1827
1828        let scroll_max = vec2f(
1829            ((scroll_width - text_size.x()) / em_width).max(0.0),
1830            max_row as f32,
1831        );
1832
1833        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x());
1834
1835        let autoscrolled = if autoscroll_horizontally {
1836            editor.autoscroll_horizontally(
1837                start_row,
1838                text_size.x(),
1839                scroll_width,
1840                em_width,
1841                &line_layouts,
1842                cx,
1843            )
1844        } else {
1845            false
1846        };
1847
1848        if clamped || autoscrolled {
1849            snapshot = editor.snapshot(cx);
1850        }
1851
1852        let newest_selection_head = editor
1853            .selections
1854            .newest::<usize>(cx)
1855            .head()
1856            .to_display_point(&snapshot);
1857        let style = editor.style(cx);
1858
1859        let mut context_menu = None;
1860        let mut code_actions_indicator = None;
1861        if (start_row..end_row).contains(&newest_selection_head.row()) {
1862            if editor.context_menu_visible() {
1863                context_menu = editor.render_context_menu(newest_selection_head, style.clone(), cx);
1864            }
1865
1866            let active = matches!(
1867                editor.context_menu,
1868                Some(crate::ContextMenu::CodeActions(_))
1869            );
1870
1871            code_actions_indicator = editor
1872                .render_code_actions_indicator(&style, active, cx)
1873                .map(|indicator| (newest_selection_head.row(), indicator));
1874        }
1875
1876        let visible_rows = start_row..start_row + line_layouts.len() as u32;
1877        let mut hover = editor
1878            .hover_state
1879            .render(&snapshot, &style, visible_rows, cx);
1880        let mode = editor.mode;
1881
1882        let mut fold_indicators = editor.render_fold_indicators(
1883            fold_statuses,
1884            &style,
1885            editor.gutter_hovered,
1886            line_height,
1887            gutter_margin,
1888            cx,
1889        );
1890
1891        if let Some((_, context_menu)) = context_menu.as_mut() {
1892            context_menu.layout(
1893                SizeConstraint {
1894                    min: Vector2F::zero(),
1895                    max: vec2f(
1896                        cx.window_size().x() * 0.7,
1897                        (12. * line_height).min((size.y() - line_height) / 2.),
1898                    ),
1899                },
1900                editor,
1901                cx,
1902            );
1903        }
1904
1905        if let Some((_, indicator)) = code_actions_indicator.as_mut() {
1906            indicator.layout(
1907                SizeConstraint::strict_along(
1908                    Axis::Vertical,
1909                    line_height * style.code_actions.vertical_scale,
1910                ),
1911                editor,
1912                cx,
1913            );
1914        }
1915
1916        for fold_indicator in fold_indicators.iter_mut() {
1917            if let Some(indicator) = fold_indicator.as_mut() {
1918                indicator.layout(
1919                    SizeConstraint::strict_along(
1920                        Axis::Vertical,
1921                        line_height * style.code_actions.vertical_scale,
1922                    ),
1923                    editor,
1924                    cx,
1925                );
1926            }
1927        }
1928
1929        if let Some((_, hover_popovers)) = hover.as_mut() {
1930            for hover_popover in hover_popovers.iter_mut() {
1931                hover_popover.layout(
1932                    SizeConstraint {
1933                        min: Vector2F::zero(),
1934                        max: vec2f(
1935                            (120. * em_width) // Default size
1936                                .min(size.x() / 2.) // Shrink to half of the editor width
1937                                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
1938                            (16. * line_height) // Default size
1939                                .min(size.y() / 2.) // Shrink to half of the editor height
1940                                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
1941                        ),
1942                    },
1943                    editor,
1944                    cx,
1945                );
1946            }
1947        }
1948
1949        (
1950            size,
1951            LayoutState {
1952                mode,
1953                position_map: Arc::new(PositionMap {
1954                    size,
1955                    scroll_max,
1956                    line_layouts,
1957                    line_height,
1958                    em_width,
1959                    em_advance,
1960                    snapshot,
1961                }),
1962                visible_display_row_range: start_row..end_row,
1963                gutter_size,
1964                gutter_padding,
1965                text_size,
1966                scrollbar_row_range,
1967                show_scrollbars,
1968                max_row,
1969                gutter_margin,
1970                active_rows,
1971                highlighted_rows,
1972                highlighted_ranges,
1973                fold_ranges,
1974                line_number_layouts,
1975                display_hunks,
1976                blocks,
1977                selections,
1978                context_menu,
1979                code_actions_indicator,
1980                fold_indicators,
1981                hover_popovers: hover,
1982            },
1983        )
1984    }
1985
1986    fn paint(
1987        &mut self,
1988        scene: &mut SceneBuilder,
1989        bounds: RectF,
1990        visible_bounds: RectF,
1991        layout: &mut Self::LayoutState,
1992        editor: &mut Editor,
1993        cx: &mut ViewContext<Editor>,
1994    ) -> Self::PaintState {
1995        let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
1996        scene.push_layer(Some(visible_bounds));
1997
1998        let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
1999        let text_bounds = RectF::new(
2000            bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
2001            layout.text_size,
2002        );
2003
2004        Self::attach_mouse_handlers(
2005            scene,
2006            &layout.position_map,
2007            layout.hover_popovers.is_some(),
2008            visible_bounds,
2009            text_bounds,
2010            gutter_bounds,
2011            bounds,
2012            cx,
2013        );
2014
2015        self.paint_background(scene, gutter_bounds, text_bounds, layout);
2016        if layout.gutter_size.x() > 0. {
2017            self.paint_gutter(scene, gutter_bounds, visible_bounds, layout, editor, cx);
2018        }
2019        self.paint_text(scene, text_bounds, visible_bounds, layout, editor, cx);
2020
2021        scene.push_layer(Some(bounds));
2022        if !layout.blocks.is_empty() {
2023            self.paint_blocks(scene, bounds, visible_bounds, layout, editor, cx);
2024        }
2025        self.paint_scrollbar(scene, bounds, layout, cx);
2026        scene.pop_layer();
2027
2028        scene.pop_layer();
2029    }
2030
2031    fn rect_for_text_range(
2032        &self,
2033        range_utf16: Range<usize>,
2034        bounds: RectF,
2035        _: RectF,
2036        layout: &Self::LayoutState,
2037        _: &Self::PaintState,
2038        _: &Editor,
2039        _: &ViewContext<Editor>,
2040    ) -> Option<RectF> {
2041        let text_bounds = RectF::new(
2042            bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
2043            layout.text_size,
2044        );
2045        let content_origin = text_bounds.origin() + vec2f(layout.gutter_margin, 0.);
2046        let scroll_position = layout.position_map.snapshot.scroll_position();
2047        let start_row = scroll_position.y() as u32;
2048        let scroll_top = scroll_position.y() * layout.position_map.line_height;
2049        let scroll_left = scroll_position.x() * layout.position_map.em_width;
2050
2051        let range_start = OffsetUtf16(range_utf16.start)
2052            .to_display_point(&layout.position_map.snapshot.display_snapshot);
2053        if range_start.row() < start_row {
2054            return None;
2055        }
2056
2057        let line = layout
2058            .position_map
2059            .line_layouts
2060            .get((range_start.row() - start_row) as usize)?;
2061        let range_start_x = line.x_for_index(range_start.column() as usize);
2062        let range_start_y = range_start.row() as f32 * layout.position_map.line_height;
2063        Some(RectF::new(
2064            content_origin
2065                + vec2f(
2066                    range_start_x,
2067                    range_start_y + layout.position_map.line_height,
2068                )
2069                - vec2f(scroll_left, scroll_top),
2070            vec2f(
2071                layout.position_map.em_width,
2072                layout.position_map.line_height,
2073            ),
2074        ))
2075    }
2076
2077    fn debug(
2078        &self,
2079        bounds: RectF,
2080        _: &Self::LayoutState,
2081        _: &Self::PaintState,
2082        _: &Editor,
2083        _: &ViewContext<Editor>,
2084    ) -> json::Value {
2085        json!({
2086            "type": "BufferElement",
2087            "bounds": bounds.to_json()
2088        })
2089    }
2090}
2091
2092type BufferRow = u32;
2093
2094pub struct LayoutState {
2095    position_map: Arc<PositionMap>,
2096    gutter_size: Vector2F,
2097    gutter_padding: f32,
2098    gutter_margin: f32,
2099    text_size: Vector2F,
2100    mode: EditorMode,
2101    visible_display_row_range: Range<u32>,
2102    active_rows: BTreeMap<u32, bool>,
2103    highlighted_rows: Option<Range<u32>>,
2104    line_number_layouts: Vec<Option<text_layout::Line>>,
2105    display_hunks: Vec<DisplayDiffHunk>,
2106    blocks: Vec<BlockLayout>,
2107    highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
2108    fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)>,
2109    selections: Vec<(ReplicaId, Vec<SelectionLayout>)>,
2110    scrollbar_row_range: Range<f32>,
2111    show_scrollbars: bool,
2112    max_row: u32,
2113    context_menu: Option<(DisplayPoint, Element<Editor>)>,
2114    code_actions_indicator: Option<(u32, Element<Editor>)>,
2115    hover_popovers: Option<(DisplayPoint, Vec<Element<Editor>>)>,
2116    fold_indicators: Vec<Option<Element<Editor>>>,
2117}
2118
2119pub struct PositionMap {
2120    size: Vector2F,
2121    line_height: f32,
2122    scroll_max: Vector2F,
2123    em_width: f32,
2124    em_advance: f32,
2125    line_layouts: Vec<text_layout::Line>,
2126    snapshot: EditorSnapshot,
2127}
2128
2129impl PositionMap {
2130    /// Returns two display points:
2131    /// 1. The nearest *valid* position in the editor
2132    /// 2. An unclipped, potentially *invalid* position that maps directly to
2133    ///    the given pixel position.
2134    fn point_for_position(
2135        &self,
2136        text_bounds: RectF,
2137        position: Vector2F,
2138    ) -> (DisplayPoint, DisplayPoint) {
2139        let scroll_position = self.snapshot.scroll_position();
2140        let position = position - text_bounds.origin();
2141        let y = position.y().max(0.0).min(self.size.y());
2142        let x = position.x() + (scroll_position.x() * self.em_width);
2143        let row = (y / self.line_height + scroll_position.y()) as u32;
2144        let (column, x_overshoot) = if let Some(line) = self
2145            .line_layouts
2146            .get(row as usize - scroll_position.y() as usize)
2147        {
2148            if let Some(ix) = line.index_for_x(x) {
2149                (ix as u32, 0.0)
2150            } else {
2151                (line.len() as u32, 0f32.max(x - line.width()))
2152            }
2153        } else {
2154            (0, x)
2155        };
2156
2157        let mut target_point = DisplayPoint::new(row, column);
2158        let point = self.snapshot.clip_point(target_point, Bias::Left);
2159        *target_point.column_mut() += (x_overshoot / self.em_advance) as u32;
2160
2161        (point, target_point)
2162    }
2163}
2164
2165struct BlockLayout {
2166    row: u32,
2167    element: Element<Editor>,
2168    style: BlockStyle,
2169}
2170
2171fn layout_line(
2172    row: u32,
2173    snapshot: &EditorSnapshot,
2174    style: &EditorStyle,
2175    layout_cache: &TextLayoutCache,
2176) -> text_layout::Line {
2177    let mut line = snapshot.line(row);
2178
2179    if line.len() > MAX_LINE_LEN {
2180        let mut len = MAX_LINE_LEN;
2181        while !line.is_char_boundary(len) {
2182            len -= 1;
2183        }
2184
2185        line.truncate(len);
2186    }
2187
2188    layout_cache.layout_str(
2189        &line,
2190        style.text.font_size,
2191        &[(
2192            snapshot.line_len(row) as usize,
2193            RunStyle {
2194                font_id: style.text.font_id,
2195                color: Color::black(),
2196                underline: Default::default(),
2197            },
2198        )],
2199    )
2200}
2201
2202#[derive(Debug)]
2203pub struct Cursor {
2204    origin: Vector2F,
2205    block_width: f32,
2206    line_height: f32,
2207    color: Color,
2208    shape: CursorShape,
2209    block_text: Option<Line>,
2210}
2211
2212impl Cursor {
2213    pub fn new(
2214        origin: Vector2F,
2215        block_width: f32,
2216        line_height: f32,
2217        color: Color,
2218        shape: CursorShape,
2219        block_text: Option<Line>,
2220    ) -> Cursor {
2221        Cursor {
2222            origin,
2223            block_width,
2224            line_height,
2225            color,
2226            shape,
2227            block_text,
2228        }
2229    }
2230
2231    pub fn bounding_rect(&self, origin: Vector2F) -> RectF {
2232        RectF::new(
2233            self.origin + origin,
2234            vec2f(self.block_width, self.line_height),
2235        )
2236    }
2237
2238    pub fn paint(&self, scene: &mut SceneBuilder, origin: Vector2F, cx: &mut WindowContext) {
2239        let bounds = match self.shape {
2240            CursorShape::Bar => RectF::new(self.origin + origin, vec2f(2.0, self.line_height)),
2241            CursorShape::Block | CursorShape::Hollow => RectF::new(
2242                self.origin + origin,
2243                vec2f(self.block_width, self.line_height),
2244            ),
2245            CursorShape::Underscore => RectF::new(
2246                self.origin + origin + Vector2F::new(0.0, self.line_height - 2.0),
2247                vec2f(self.block_width, 2.0),
2248            ),
2249        };
2250
2251        //Draw background or border quad
2252        if matches!(self.shape, CursorShape::Hollow) {
2253            scene.push_quad(Quad {
2254                bounds,
2255                background: None,
2256                border: Border::all(1., self.color),
2257                corner_radius: 0.,
2258            });
2259        } else {
2260            scene.push_quad(Quad {
2261                bounds,
2262                background: Some(self.color),
2263                border: Default::default(),
2264                corner_radius: 0.,
2265            });
2266        }
2267
2268        if let Some(block_text) = &self.block_text {
2269            block_text.paint(scene, self.origin + origin, bounds, self.line_height, cx);
2270        }
2271    }
2272
2273    pub fn shape(&self) -> CursorShape {
2274        self.shape
2275    }
2276}
2277
2278#[derive(Debug)]
2279pub struct HighlightedRange {
2280    pub start_y: f32,
2281    pub line_height: f32,
2282    pub lines: Vec<HighlightedRangeLine>,
2283    pub color: Color,
2284    pub corner_radius: f32,
2285}
2286
2287#[derive(Debug)]
2288pub struct HighlightedRangeLine {
2289    pub start_x: f32,
2290    pub end_x: f32,
2291}
2292
2293impl HighlightedRange {
2294    pub fn paint(&self, bounds: RectF, scene: &mut SceneBuilder) {
2295        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
2296            self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
2297            self.paint_lines(
2298                self.start_y + self.line_height,
2299                &self.lines[1..],
2300                bounds,
2301                scene,
2302            );
2303        } else {
2304            self.paint_lines(self.start_y, &self.lines, bounds, scene);
2305        }
2306    }
2307
2308    fn paint_lines(
2309        &self,
2310        start_y: f32,
2311        lines: &[HighlightedRangeLine],
2312        bounds: RectF,
2313        scene: &mut SceneBuilder,
2314    ) {
2315        if lines.is_empty() {
2316            return;
2317        }
2318
2319        let mut path = PathBuilder::new();
2320        let first_line = lines.first().unwrap();
2321        let last_line = lines.last().unwrap();
2322
2323        let first_top_left = vec2f(first_line.start_x, start_y);
2324        let first_top_right = vec2f(first_line.end_x, start_y);
2325
2326        let curve_height = vec2f(0., self.corner_radius);
2327        let curve_width = |start_x: f32, end_x: f32| {
2328            let max = (end_x - start_x) / 2.;
2329            let width = if max < self.corner_radius {
2330                max
2331            } else {
2332                self.corner_radius
2333            };
2334
2335            vec2f(width, 0.)
2336        };
2337
2338        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
2339        path.reset(first_top_right - top_curve_width);
2340        path.curve_to(first_top_right + curve_height, first_top_right);
2341
2342        let mut iter = lines.iter().enumerate().peekable();
2343        while let Some((ix, line)) = iter.next() {
2344            let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
2345
2346            if let Some((_, next_line)) = iter.peek() {
2347                let next_top_right = vec2f(next_line.end_x, bottom_right.y());
2348
2349                match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
2350                    Ordering::Equal => {
2351                        path.line_to(bottom_right);
2352                    }
2353                    Ordering::Less => {
2354                        let curve_width = curve_width(next_top_right.x(), bottom_right.x());
2355                        path.line_to(bottom_right - curve_height);
2356                        if self.corner_radius > 0. {
2357                            path.curve_to(bottom_right - curve_width, bottom_right);
2358                        }
2359                        path.line_to(next_top_right + curve_width);
2360                        if self.corner_radius > 0. {
2361                            path.curve_to(next_top_right + curve_height, next_top_right);
2362                        }
2363                    }
2364                    Ordering::Greater => {
2365                        let curve_width = curve_width(bottom_right.x(), next_top_right.x());
2366                        path.line_to(bottom_right - curve_height);
2367                        if self.corner_radius > 0. {
2368                            path.curve_to(bottom_right + curve_width, bottom_right);
2369                        }
2370                        path.line_to(next_top_right - curve_width);
2371                        if self.corner_radius > 0. {
2372                            path.curve_to(next_top_right + curve_height, next_top_right);
2373                        }
2374                    }
2375                }
2376            } else {
2377                let curve_width = curve_width(line.start_x, line.end_x);
2378                path.line_to(bottom_right - curve_height);
2379                if self.corner_radius > 0. {
2380                    path.curve_to(bottom_right - curve_width, bottom_right);
2381                }
2382
2383                let bottom_left = vec2f(line.start_x, bottom_right.y());
2384                path.line_to(bottom_left + curve_width);
2385                if self.corner_radius > 0. {
2386                    path.curve_to(bottom_left - curve_height, bottom_left);
2387                }
2388            }
2389        }
2390
2391        if first_line.start_x > last_line.start_x {
2392            let curve_width = curve_width(last_line.start_x, first_line.start_x);
2393            let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
2394            path.line_to(second_top_left + curve_height);
2395            if self.corner_radius > 0. {
2396                path.curve_to(second_top_left + curve_width, second_top_left);
2397            }
2398            let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
2399            path.line_to(first_bottom_left - curve_width);
2400            if self.corner_radius > 0. {
2401                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
2402            }
2403        }
2404
2405        path.line_to(first_top_left + curve_height);
2406        if self.corner_radius > 0. {
2407            path.curve_to(first_top_left + top_curve_width, first_top_left);
2408        }
2409        path.line_to(first_top_right - top_curve_width);
2410
2411        scene.push_path(path.build(self.color, Some(bounds)));
2412    }
2413}
2414
2415pub fn position_to_display_point(
2416    position: Vector2F,
2417    text_bounds: RectF,
2418    position_map: &PositionMap,
2419) -> Option<DisplayPoint> {
2420    if text_bounds.contains_point(position) {
2421        let (point, target_point) = position_map.point_for_position(text_bounds, position);
2422        if point == target_point {
2423            Some(point)
2424        } else {
2425            None
2426        }
2427    } else {
2428        None
2429    }
2430}
2431
2432pub fn range_to_bounds(
2433    range: &Range<DisplayPoint>,
2434    content_origin: Vector2F,
2435    scroll_left: f32,
2436    scroll_top: f32,
2437    visible_row_range: &Range<u32>,
2438    line_end_overshoot: f32,
2439    position_map: &PositionMap,
2440) -> impl Iterator<Item = RectF> {
2441    let mut bounds: SmallVec<[RectF; 1]> = SmallVec::new();
2442
2443    if range.start == range.end {
2444        return bounds.into_iter();
2445    }
2446
2447    let start_row = visible_row_range.start;
2448    let end_row = visible_row_range.end;
2449
2450    let row_range = if range.end.column() == 0 {
2451        cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
2452    } else {
2453        cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
2454    };
2455
2456    let first_y =
2457        content_origin.y() + row_range.start as f32 * position_map.line_height - scroll_top;
2458
2459    for (idx, row) in row_range.enumerate() {
2460        let line_layout = &position_map.line_layouts[(row - start_row) as usize];
2461
2462        let start_x = if row == range.start.row() {
2463            content_origin.x() + line_layout.x_for_index(range.start.column() as usize)
2464                - scroll_left
2465        } else {
2466            content_origin.x() - scroll_left
2467        };
2468
2469        let end_x = if row == range.end.row() {
2470            content_origin.x() + line_layout.x_for_index(range.end.column() as usize) - scroll_left
2471        } else {
2472            content_origin.x() + line_layout.width() + line_end_overshoot - scroll_left
2473        };
2474
2475        bounds.push(RectF::from_points(
2476            vec2f(start_x, first_y + position_map.line_height * idx as f32),
2477            vec2f(end_x, first_y + position_map.line_height * (idx + 1) as f32),
2478        ))
2479    }
2480
2481    bounds.into_iter()
2482}
2483
2484pub fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
2485    delta.powf(1.5) / 100.0
2486}
2487
2488fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
2489    delta.powf(1.2) / 300.0
2490}
2491
2492#[cfg(test)]
2493mod tests {
2494    use super::*;
2495    use crate::{
2496        display_map::{BlockDisposition, BlockProperties},
2497        Editor, MultiBuffer,
2498    };
2499    use gpui::TestAppContext;
2500    use settings::Settings;
2501    use std::sync::Arc;
2502    use util::test::sample_text;
2503
2504    #[gpui::test]
2505    fn test_layout_line_numbers(cx: &mut TestAppContext) {
2506        cx.update(|cx| cx.set_global(Settings::test(cx)));
2507        let (_, editor) = cx.add_window(|cx| {
2508            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
2509            Editor::new(EditorMode::Full, buffer, None, None, cx)
2510        });
2511        let element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
2512
2513        let layouts = editor.update(cx, |editor, cx| {
2514            let snapshot = editor.snapshot(cx);
2515            element
2516                .layout_line_numbers(0..6, &Default::default(), false, &snapshot, cx)
2517                .0
2518        });
2519        assert_eq!(layouts.len(), 6);
2520    }
2521
2522    #[gpui::test]
2523    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
2524        cx.update(|cx| cx.set_global(Settings::test(cx)));
2525        let (_, editor) = cx.add_window(|cx| {
2526            let buffer = MultiBuffer::build_simple("", cx);
2527            Editor::new(EditorMode::Full, buffer, None, None, cx)
2528        });
2529
2530        editor.update(cx, |editor, cx| {
2531            editor.set_placeholder_text("hello", cx);
2532            editor.insert_blocks(
2533                [BlockProperties {
2534                    style: BlockStyle::Fixed,
2535                    disposition: BlockDisposition::Above,
2536                    height: 3,
2537                    position: Anchor::min(),
2538                    render: Arc::new(|_| Empty::new().boxed()),
2539                }],
2540                cx,
2541            );
2542
2543            // Blur the editor so that it displays placeholder text.
2544            cx.blur();
2545        });
2546
2547        let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
2548        let (size, mut state) = editor.update(cx, |editor, cx| {
2549            element.layout(
2550                SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
2551                editor,
2552                cx,
2553            )
2554        });
2555
2556        assert_eq!(state.position_map.line_layouts.len(), 4);
2557        assert_eq!(
2558            state
2559                .line_number_layouts
2560                .iter()
2561                .map(Option::is_some)
2562                .collect::<Vec<_>>(),
2563            &[false, false, false, true]
2564        );
2565
2566        // Don't panic.
2567        let mut scene = SceneBuilder::new(1.0);
2568        let bounds = RectF::new(Default::default(), size);
2569        editor.update(cx, |editor, cx| {
2570            element.paint(&mut scene, bounds, bounds, &mut state, editor, cx);
2571        });
2572    }
2573}