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