element.rs

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