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