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