element.rs

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