element.rs

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