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 scroll_top =
 529            layout.position_map.snapshot.scroll_position().y() * layout.position_map.line_height;
 530        for (ix, line) in layout.line_number_layouts.iter().enumerate() {
 531            if let Some(line) = line {
 532                let line_origin = bounds.origin()
 533                    + vec2f(
 534                        bounds.width() - line.width() - layout.gutter_padding,
 535                        ix as f32 * layout.position_map.line_height
 536                            - (scroll_top % layout.position_map.line_height),
 537                    );
 538                line.paint(
 539                    line_origin,
 540                    visible_bounds,
 541                    layout.position_map.line_height,
 542                    cx,
 543                );
 544            }
 545        }
 546
 547        println!("painting from hunks: {:#?}\n", layout.diff_hunks);
 548        for hunk in &layout.diff_hunks {
 549            let color = match hunk.status() {
 550                DiffHunkStatus::Added => Color::green(),
 551                DiffHunkStatus::Modified => Color::blue(),
 552                _ => continue,
 553            };
 554
 555            let start_row = hunk.buffer_range.start;
 556            let end_row = hunk.buffer_range.end;
 557
 558            let start_y = start_row as f32 * layout.line_height - scroll_top;
 559            let end_y = end_row as f32 * layout.line_height + layout.line_height - scroll_top;
 560
 561            let width = 0.22 * layout.line_height;
 562            let highlight_origin = bounds.origin() + vec2f(-width, start_y);
 563            let highlight_size = vec2f(width * 2., end_y - start_y);
 564            let highlight_bounds = RectF::new(highlight_origin, highlight_size);
 565
 566            cx.scene.push_quad(Quad {
 567                bounds: highlight_bounds,
 568                background: Some(color),
 569                border: Border::new(0., Color::transparent_black()),
 570                corner_radius: 0.2 * layout.line_height,
 571            });
 572        }
 573
 574        if let Some((row, indicator)) = layout.code_actions_indicator.as_mut() {
 575            let mut x = bounds.width() - layout.gutter_padding;
 576            let mut y = *row as f32 * layout.position_map.line_height - scroll_top;
 577            x += ((layout.gutter_padding + layout.gutter_margin) - indicator.size().x()) / 2.;
 578            y += (layout.position_map.line_height - indicator.size().y()) / 2.;
 579            indicator.paint(bounds.origin() + vec2f(x, y), visible_bounds, cx);
 580        }
 581    }
 582
 583    fn paint_text(
 584        &mut self,
 585        bounds: RectF,
 586        visible_bounds: RectF,
 587        layout: &mut LayoutState,
 588        cx: &mut PaintContext,
 589    ) {
 590        let view = self.view(cx.app);
 591        let style = &self.style;
 592        let local_replica_id = view.replica_id(cx);
 593        let scroll_position = layout.position_map.snapshot.scroll_position();
 594        let start_row = scroll_position.y() as u32;
 595        let scroll_top = scroll_position.y() * layout.position_map.line_height;
 596        let end_row =
 597            ((scroll_top + bounds.height()) / layout.position_map.line_height).ceil() as u32 + 1; // Add 1 to ensure selections bleed off screen
 598        let max_glyph_width = layout.position_map.em_width;
 599        let scroll_left = scroll_position.x() * max_glyph_width;
 600        let content_origin = bounds.origin() + vec2f(layout.gutter_margin, 0.);
 601
 602        cx.scene.push_layer(Some(bounds));
 603
 604        cx.scene.push_cursor_region(CursorRegion {
 605            bounds,
 606            style: if !view.link_go_to_definition_state.definitions.is_empty() {
 607                CursorStyle::PointingHand
 608            } else {
 609                CursorStyle::IBeam
 610            },
 611        });
 612
 613        for (range, color) in &layout.highlighted_ranges {
 614            self.paint_highlighted_range(
 615                range.clone(),
 616                start_row,
 617                end_row,
 618                *color,
 619                0.,
 620                0.15 * layout.position_map.line_height,
 621                layout,
 622                content_origin,
 623                scroll_top,
 624                scroll_left,
 625                bounds,
 626                cx,
 627            );
 628        }
 629
 630        let mut cursors = SmallVec::<[Cursor; 32]>::new();
 631        for (replica_id, selections) in &layout.selections {
 632            let selection_style = style.replica_selection_style(*replica_id);
 633            let corner_radius = 0.15 * layout.position_map.line_height;
 634
 635            for selection in selections {
 636                self.paint_highlighted_range(
 637                    selection.range.clone(),
 638                    start_row,
 639                    end_row,
 640                    selection_style.selection,
 641                    corner_radius,
 642                    corner_radius * 2.,
 643                    layout,
 644                    content_origin,
 645                    scroll_top,
 646                    scroll_left,
 647                    bounds,
 648                    cx,
 649                );
 650
 651                if view.show_local_cursors() || *replica_id != local_replica_id {
 652                    let cursor_position = selection.head;
 653                    if (start_row..end_row).contains(&cursor_position.row()) {
 654                        let cursor_row_layout = &layout.position_map.line_layouts
 655                            [(cursor_position.row() - start_row) as usize];
 656                        let cursor_column = cursor_position.column() as usize;
 657
 658                        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 659                        let mut block_width =
 660                            cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
 661                        if block_width == 0.0 {
 662                            block_width = layout.position_map.em_width;
 663                        }
 664                        let block_text = if let CursorShape::Block = self.cursor_shape {
 665                            layout
 666                                .position_map
 667                                .snapshot
 668                                .chars_at(cursor_position)
 669                                .next()
 670                                .and_then(|character| {
 671                                    let font_id =
 672                                        cursor_row_layout.font_for_index(cursor_column)?;
 673                                    let text = character.to_string();
 674
 675                                    Some(cx.text_layout_cache.layout_str(
 676                                        &text,
 677                                        cursor_row_layout.font_size(),
 678                                        &[(
 679                                            text.len(),
 680                                            RunStyle {
 681                                                font_id,
 682                                                color: style.background,
 683                                                underline: Default::default(),
 684                                            },
 685                                        )],
 686                                    ))
 687                                })
 688                        } else {
 689                            None
 690                        };
 691
 692                        let x = cursor_character_x - scroll_left;
 693                        let y = cursor_position.row() as f32 * layout.position_map.line_height
 694                            - scroll_top;
 695                        cursors.push(Cursor {
 696                            color: selection_style.cursor,
 697                            block_width,
 698                            origin: vec2f(x, y),
 699                            line_height: layout.position_map.line_height,
 700                            shape: self.cursor_shape,
 701                            block_text,
 702                        });
 703                    }
 704                }
 705            }
 706        }
 707
 708        if let Some(visible_text_bounds) = bounds.intersection(visible_bounds) {
 709            // Draw glyphs
 710            for (ix, line) in layout.position_map.line_layouts.iter().enumerate() {
 711                let row = start_row + ix as u32;
 712                line.paint(
 713                    content_origin
 714                        + vec2f(
 715                            -scroll_left,
 716                            row as f32 * layout.position_map.line_height - scroll_top,
 717                        ),
 718                    visible_text_bounds,
 719                    layout.position_map.line_height,
 720                    cx,
 721                );
 722            }
 723        }
 724
 725        cx.scene.push_layer(Some(bounds));
 726        for cursor in cursors {
 727            cursor.paint(content_origin, cx);
 728        }
 729        cx.scene.pop_layer();
 730
 731        if let Some((position, context_menu)) = layout.context_menu.as_mut() {
 732            cx.scene.push_stacking_context(None);
 733            let cursor_row_layout =
 734                &layout.position_map.line_layouts[(position.row() - start_row) as usize];
 735            let x = cursor_row_layout.x_for_index(position.column() as usize) - scroll_left;
 736            let y = (position.row() + 1) as f32 * layout.position_map.line_height - scroll_top;
 737            let mut list_origin = content_origin + vec2f(x, y);
 738            let list_width = context_menu.size().x();
 739            let list_height = context_menu.size().y();
 740
 741            // Snap the right edge of the list to the right edge of the window if
 742            // its horizontal bounds overflow.
 743            if list_origin.x() + list_width > cx.window_size.x() {
 744                list_origin.set_x((cx.window_size.x() - list_width).max(0.));
 745            }
 746
 747            if list_origin.y() + list_height > bounds.max_y() {
 748                list_origin.set_y(list_origin.y() - layout.position_map.line_height - list_height);
 749            }
 750
 751            context_menu.paint(
 752                list_origin,
 753                RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
 754                cx,
 755            );
 756
 757            cx.scene.pop_stacking_context();
 758        }
 759
 760        if let Some((position, hover_popovers)) = layout.hover_popovers.as_mut() {
 761            cx.scene.push_stacking_context(None);
 762
 763            // This is safe because we check on layout whether the required row is available
 764            let hovered_row_layout =
 765                &layout.position_map.line_layouts[(position.row() - start_row) as usize];
 766
 767            // Minimum required size: Take the first popover, and add 1.5 times the minimum popover
 768            // height. This is the size we will use to decide whether to render popovers above or below
 769            // the hovered line.
 770            let first_size = hover_popovers[0].size();
 771            let height_to_reserve = first_size.y()
 772                + 1.5 * MIN_POPOVER_LINE_HEIGHT as f32 * layout.position_map.line_height;
 773
 774            // Compute Hovered Point
 775            let x = hovered_row_layout.x_for_index(position.column() as usize) - scroll_left;
 776            let y = position.row() as f32 * layout.position_map.line_height - scroll_top;
 777            let hovered_point = content_origin + vec2f(x, y);
 778
 779            if hovered_point.y() - height_to_reserve > 0.0 {
 780                // There is enough space above. Render popovers above the hovered point
 781                let mut current_y = hovered_point.y();
 782                for hover_popover in hover_popovers {
 783                    let size = hover_popover.size();
 784                    let mut popover_origin = vec2f(hovered_point.x(), current_y - size.y());
 785
 786                    let x_out_of_bounds = bounds.max_x() - (popover_origin.x() + size.x());
 787                    if x_out_of_bounds < 0.0 {
 788                        popover_origin.set_x(popover_origin.x() + x_out_of_bounds);
 789                    }
 790
 791                    hover_popover.paint(
 792                        popover_origin,
 793                        RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
 794                        cx,
 795                    );
 796
 797                    current_y = popover_origin.y() - HOVER_POPOVER_GAP;
 798                }
 799            } else {
 800                // There is not enough space above. Render popovers below the hovered point
 801                let mut current_y = hovered_point.y() + layout.position_map.line_height;
 802                for hover_popover in hover_popovers {
 803                    let size = hover_popover.size();
 804                    let mut popover_origin = vec2f(hovered_point.x(), current_y);
 805
 806                    let x_out_of_bounds = bounds.max_x() - (popover_origin.x() + size.x());
 807                    if x_out_of_bounds < 0.0 {
 808                        popover_origin.set_x(popover_origin.x() + x_out_of_bounds);
 809                    }
 810
 811                    hover_popover.paint(
 812                        popover_origin,
 813                        RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
 814                        cx,
 815                    );
 816
 817                    current_y = popover_origin.y() + size.y() + HOVER_POPOVER_GAP;
 818                }
 819            }
 820
 821            cx.scene.pop_stacking_context();
 822        }
 823
 824        cx.scene.pop_layer();
 825    }
 826
 827    #[allow(clippy::too_many_arguments)]
 828    fn paint_highlighted_range(
 829        &self,
 830        range: Range<DisplayPoint>,
 831        start_row: u32,
 832        end_row: u32,
 833        color: Color,
 834        corner_radius: f32,
 835        line_end_overshoot: f32,
 836        layout: &LayoutState,
 837        content_origin: Vector2F,
 838        scroll_top: f32,
 839        scroll_left: f32,
 840        bounds: RectF,
 841        cx: &mut PaintContext,
 842    ) {
 843        if range.start != range.end {
 844            let row_range = if range.end.column() == 0 {
 845                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
 846            } else {
 847                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
 848            };
 849
 850            let highlighted_range = HighlightedRange {
 851                color,
 852                line_height: layout.position_map.line_height,
 853                corner_radius,
 854                start_y: content_origin.y()
 855                    + row_range.start as f32 * layout.position_map.line_height
 856                    - scroll_top,
 857                lines: row_range
 858                    .into_iter()
 859                    .map(|row| {
 860                        let line_layout =
 861                            &layout.position_map.line_layouts[(row - start_row) as usize];
 862                        HighlightedRangeLine {
 863                            start_x: if row == range.start.row() {
 864                                content_origin.x()
 865                                    + line_layout.x_for_index(range.start.column() as usize)
 866                                    - scroll_left
 867                            } else {
 868                                content_origin.x() - scroll_left
 869                            },
 870                            end_x: if row == range.end.row() {
 871                                content_origin.x()
 872                                    + line_layout.x_for_index(range.end.column() as usize)
 873                                    - scroll_left
 874                            } else {
 875                                content_origin.x() + line_layout.width() + line_end_overshoot
 876                                    - scroll_left
 877                            },
 878                        }
 879                    })
 880                    .collect(),
 881            };
 882
 883            highlighted_range.paint(bounds, cx.scene);
 884        }
 885    }
 886
 887    fn paint_blocks(
 888        &mut self,
 889        bounds: RectF,
 890        visible_bounds: RectF,
 891        layout: &mut LayoutState,
 892        cx: &mut PaintContext,
 893    ) {
 894        let scroll_position = layout.position_map.snapshot.scroll_position();
 895        let scroll_left = scroll_position.x() * layout.position_map.em_width;
 896        let scroll_top = scroll_position.y() * layout.position_map.line_height;
 897
 898        for block in &mut layout.blocks {
 899            let mut origin = bounds.origin()
 900                + vec2f(
 901                    0.,
 902                    block.row as f32 * layout.position_map.line_height - scroll_top,
 903                );
 904            if !matches!(block.style, BlockStyle::Sticky) {
 905                origin += vec2f(-scroll_left, 0.);
 906            }
 907            block.element.paint(origin, visible_bounds, cx);
 908        }
 909    }
 910
 911    fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &LayoutContext) -> f32 {
 912        let digit_count = (snapshot.max_buffer_row() as f32).log10().floor() as usize + 1;
 913        let style = &self.style;
 914
 915        cx.text_layout_cache
 916            .layout_str(
 917                "1".repeat(digit_count).as_str(),
 918                style.text.font_size,
 919                &[(
 920                    digit_count,
 921                    RunStyle {
 922                        font_id: style.text.font_id,
 923                        color: Color::black(),
 924                        underline: Default::default(),
 925                    },
 926                )],
 927            )
 928            .width()
 929    }
 930
 931    fn layout_line_numbers(
 932        &self,
 933        rows: Range<u32>,
 934        active_rows: &BTreeMap<u32, bool>,
 935        snapshot: &EditorSnapshot,
 936        cx: &LayoutContext,
 937    ) -> Vec<Option<text_layout::Line>> {
 938        let style = &self.style;
 939        let include_line_numbers = snapshot.mode == EditorMode::Full;
 940        let mut line_number_layouts = Vec::with_capacity(rows.len());
 941        let mut line_number = String::new();
 942        for (ix, row) in snapshot
 943            .buffer_rows(rows.start)
 944            .take((rows.end - rows.start) as usize)
 945            .enumerate()
 946        {
 947            let display_row = rows.start + ix as u32;
 948            let color = if active_rows.contains_key(&display_row) {
 949                style.line_number_active
 950            } else {
 951                style.line_number
 952            };
 953            if let Some(buffer_row) = row {
 954                if include_line_numbers {
 955                    line_number.clear();
 956                    write!(&mut line_number, "{}", buffer_row + 1).unwrap();
 957                    line_number_layouts.push(Some(cx.text_layout_cache.layout_str(
 958                        &line_number,
 959                        style.text.font_size,
 960                        &[(
 961                            line_number.len(),
 962                            RunStyle {
 963                                font_id: style.text.font_id,
 964                                color,
 965                                underline: Default::default(),
 966                            },
 967                        )],
 968                    )));
 969                }
 970            } else {
 971                line_number_layouts.push(None);
 972            }
 973        }
 974
 975        line_number_layouts
 976    }
 977
 978    fn layout_lines(
 979        &mut self,
 980        rows: Range<u32>,
 981        snapshot: &EditorSnapshot,
 982        cx: &LayoutContext,
 983    ) -> Vec<text_layout::Line> {
 984        if rows.start >= rows.end {
 985            return Vec::new();
 986        }
 987
 988        // When the editor is empty and unfocused, then show the placeholder.
 989        if snapshot.is_empty() && !snapshot.is_focused() {
 990            let placeholder_style = self
 991                .style
 992                .placeholder_text
 993                .as_ref()
 994                .unwrap_or(&self.style.text);
 995            let placeholder_text = snapshot.placeholder_text();
 996            let placeholder_lines = placeholder_text
 997                .as_ref()
 998                .map_or("", AsRef::as_ref)
 999                .split('\n')
1000                .skip(rows.start as usize)
1001                .chain(iter::repeat(""))
1002                .take(rows.len());
1003            placeholder_lines
1004                .map(|line| {
1005                    cx.text_layout_cache.layout_str(
1006                        line,
1007                        placeholder_style.font_size,
1008                        &[(
1009                            line.len(),
1010                            RunStyle {
1011                                font_id: placeholder_style.font_id,
1012                                color: placeholder_style.color,
1013                                underline: Default::default(),
1014                            },
1015                        )],
1016                    )
1017                })
1018                .collect()
1019        } else {
1020            let style = &self.style;
1021            let chunks = snapshot.chunks(rows.clone(), true).map(|chunk| {
1022                let mut highlight_style = chunk
1023                    .syntax_highlight_id
1024                    .and_then(|id| id.style(&style.syntax));
1025
1026                if let Some(chunk_highlight) = chunk.highlight_style {
1027                    if let Some(highlight_style) = highlight_style.as_mut() {
1028                        highlight_style.highlight(chunk_highlight);
1029                    } else {
1030                        highlight_style = Some(chunk_highlight);
1031                    }
1032                }
1033
1034                let mut diagnostic_highlight = HighlightStyle::default();
1035
1036                if chunk.is_unnecessary {
1037                    diagnostic_highlight.fade_out = Some(style.unnecessary_code_fade);
1038                }
1039
1040                if let Some(severity) = chunk.diagnostic_severity {
1041                    // Omit underlines for HINT/INFO diagnostics on 'unnecessary' code.
1042                    if severity <= DiagnosticSeverity::WARNING || !chunk.is_unnecessary {
1043                        let diagnostic_style = super::diagnostic_style(severity, true, style);
1044                        diagnostic_highlight.underline = Some(Underline {
1045                            color: Some(diagnostic_style.message.text.color),
1046                            thickness: 1.0.into(),
1047                            squiggly: true,
1048                        });
1049                    }
1050                }
1051
1052                if let Some(highlight_style) = highlight_style.as_mut() {
1053                    highlight_style.highlight(diagnostic_highlight);
1054                } else {
1055                    highlight_style = Some(diagnostic_highlight);
1056                }
1057
1058                (chunk.text, highlight_style)
1059            });
1060            layout_highlighted_chunks(
1061                chunks,
1062                &style.text,
1063                cx.text_layout_cache,
1064                cx.font_cache,
1065                MAX_LINE_LEN,
1066                rows.len() as usize,
1067            )
1068        }
1069    }
1070
1071    #[allow(clippy::too_many_arguments)]
1072    fn layout_blocks(
1073        &mut self,
1074        rows: Range<u32>,
1075        snapshot: &EditorSnapshot,
1076        editor_width: f32,
1077        scroll_width: f32,
1078        gutter_padding: f32,
1079        gutter_width: f32,
1080        em_width: f32,
1081        text_x: f32,
1082        line_height: f32,
1083        style: &EditorStyle,
1084        line_layouts: &[text_layout::Line],
1085        cx: &mut LayoutContext,
1086    ) -> (f32, Vec<BlockLayout>) {
1087        let editor = if let Some(editor) = self.view.upgrade(cx) {
1088            editor
1089        } else {
1090            return Default::default();
1091        };
1092
1093        let tooltip_style = cx.global::<Settings>().theme.tooltip.clone();
1094        let scroll_x = snapshot.scroll_position.x();
1095        let (fixed_blocks, non_fixed_blocks) = snapshot
1096            .blocks_in_range(rows.clone())
1097            .partition::<Vec<_>, _>(|(_, block)| match block {
1098                TransformBlock::ExcerptHeader { .. } => false,
1099                TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
1100            });
1101        let mut render_block = |block: &TransformBlock, width: f32| {
1102            let mut element = match block {
1103                TransformBlock::Custom(block) => {
1104                    let align_to = block
1105                        .position()
1106                        .to_point(&snapshot.buffer_snapshot)
1107                        .to_display_point(snapshot);
1108                    let anchor_x = text_x
1109                        + if rows.contains(&align_to.row()) {
1110                            line_layouts[(align_to.row() - rows.start) as usize]
1111                                .x_for_index(align_to.column() as usize)
1112                        } else {
1113                            layout_line(align_to.row(), snapshot, style, cx.text_layout_cache)
1114                                .x_for_index(align_to.column() as usize)
1115                        };
1116
1117                    cx.render(&editor, |_, cx| {
1118                        block.render(&mut BlockContext {
1119                            cx,
1120                            anchor_x,
1121                            gutter_padding,
1122                            line_height,
1123                            scroll_x,
1124                            gutter_width,
1125                            em_width,
1126                        })
1127                    })
1128                }
1129                TransformBlock::ExcerptHeader {
1130                    key,
1131                    buffer,
1132                    range,
1133                    starts_new_buffer,
1134                    ..
1135                } => {
1136                    let jump_icon = project::File::from_dyn(buffer.file()).map(|file| {
1137                        let jump_position = range
1138                            .primary
1139                            .as_ref()
1140                            .map_or(range.context.start, |primary| primary.start);
1141                        let jump_action = crate::Jump {
1142                            path: ProjectPath {
1143                                worktree_id: file.worktree_id(cx),
1144                                path: file.path.clone(),
1145                            },
1146                            position: language::ToPoint::to_point(&jump_position, buffer),
1147                            anchor: jump_position,
1148                        };
1149
1150                        enum JumpIcon {}
1151                        cx.render(&editor, |_, cx| {
1152                            MouseEventHandler::<JumpIcon>::new(*key, cx, |state, _| {
1153                                let style = style.jump_icon.style_for(state, false);
1154                                Svg::new("icons/arrow_up_right_8.svg")
1155                                    .with_color(style.color)
1156                                    .constrained()
1157                                    .with_width(style.icon_width)
1158                                    .aligned()
1159                                    .contained()
1160                                    .with_style(style.container)
1161                                    .constrained()
1162                                    .with_width(style.button_width)
1163                                    .with_height(style.button_width)
1164                                    .boxed()
1165                            })
1166                            .with_cursor_style(CursorStyle::PointingHand)
1167                            .on_click(MouseButton::Left, move |_, cx| {
1168                                cx.dispatch_action(jump_action.clone())
1169                            })
1170                            .with_tooltip::<JumpIcon, _>(
1171                                *key,
1172                                "Jump to Buffer".to_string(),
1173                                Some(Box::new(crate::OpenExcerpts)),
1174                                tooltip_style.clone(),
1175                                cx,
1176                            )
1177                            .aligned()
1178                            .flex_float()
1179                            .boxed()
1180                        })
1181                    });
1182
1183                    if *starts_new_buffer {
1184                        let style = &self.style.diagnostic_path_header;
1185                        let font_size =
1186                            (style.text_scale_factor * self.style.text.font_size).round();
1187
1188                        let mut filename = None;
1189                        let mut parent_path = None;
1190                        if let Some(file) = buffer.file() {
1191                            let path = file.path();
1192                            filename = path.file_name().map(|f| f.to_string_lossy().to_string());
1193                            parent_path =
1194                                path.parent().map(|p| p.to_string_lossy().to_string() + "/");
1195                        }
1196
1197                        Flex::row()
1198                            .with_child(
1199                                Label::new(
1200                                    filename.unwrap_or_else(|| "untitled".to_string()),
1201                                    style.filename.text.clone().with_font_size(font_size),
1202                                )
1203                                .contained()
1204                                .with_style(style.filename.container)
1205                                .aligned()
1206                                .boxed(),
1207                            )
1208                            .with_children(parent_path.map(|path| {
1209                                Label::new(path, style.path.text.clone().with_font_size(font_size))
1210                                    .contained()
1211                                    .with_style(style.path.container)
1212                                    .aligned()
1213                                    .boxed()
1214                            }))
1215                            .with_children(jump_icon)
1216                            .contained()
1217                            .with_style(style.container)
1218                            .with_padding_left(gutter_padding)
1219                            .with_padding_right(gutter_padding)
1220                            .expanded()
1221                            .named("path header block")
1222                    } else {
1223                        let text_style = self.style.text.clone();
1224                        Flex::row()
1225                            .with_child(Label::new("".to_string(), text_style).boxed())
1226                            .with_children(jump_icon)
1227                            .contained()
1228                            .with_padding_left(gutter_padding)
1229                            .with_padding_right(gutter_padding)
1230                            .expanded()
1231                            .named("collapsed context")
1232                    }
1233                }
1234            };
1235
1236            element.layout(
1237                SizeConstraint {
1238                    min: Vector2F::zero(),
1239                    max: vec2f(width, block.height() as f32 * line_height),
1240                },
1241                cx,
1242            );
1243            element
1244        };
1245
1246        let mut fixed_block_max_width = 0f32;
1247        let mut blocks = Vec::new();
1248        for (row, block) in fixed_blocks {
1249            let element = render_block(block, f32::INFINITY);
1250            fixed_block_max_width = fixed_block_max_width.max(element.size().x() + em_width);
1251            blocks.push(BlockLayout {
1252                row,
1253                element,
1254                style: BlockStyle::Fixed,
1255            });
1256        }
1257        for (row, block) in non_fixed_blocks {
1258            let style = match block {
1259                TransformBlock::Custom(block) => block.style(),
1260                TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
1261            };
1262            let width = match style {
1263                BlockStyle::Sticky => editor_width,
1264                BlockStyle::Flex => editor_width
1265                    .max(fixed_block_max_width)
1266                    .max(gutter_width + scroll_width),
1267                BlockStyle::Fixed => unreachable!(),
1268            };
1269            let element = render_block(block, width);
1270            blocks.push(BlockLayout {
1271                row,
1272                element,
1273                style,
1274            });
1275        }
1276        (
1277            scroll_width.max(fixed_block_max_width - gutter_width),
1278            blocks,
1279        )
1280    }
1281}
1282
1283impl Element for EditorElement {
1284    type LayoutState = LayoutState;
1285    type PaintState = ();
1286
1287    fn layout(
1288        &mut self,
1289        constraint: SizeConstraint,
1290        cx: &mut LayoutContext,
1291    ) -> (Vector2F, Self::LayoutState) {
1292        let mut size = constraint.max;
1293        if size.x().is_infinite() {
1294            unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
1295        }
1296
1297        let snapshot = self.snapshot(cx.app);
1298        let style = self.style.clone();
1299        let line_height = style.text.line_height(cx.font_cache);
1300
1301        let gutter_padding;
1302        let gutter_width;
1303        let gutter_margin;
1304        if snapshot.mode == EditorMode::Full {
1305            gutter_padding = style.text.em_width(cx.font_cache) * style.gutter_padding_factor;
1306            gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
1307            gutter_margin = -style.text.descent(cx.font_cache);
1308        } else {
1309            gutter_padding = 0.0;
1310            gutter_width = 0.0;
1311            gutter_margin = 0.0;
1312        };
1313
1314        let text_width = size.x() - gutter_width;
1315        let em_width = style.text.em_width(cx.font_cache);
1316        let em_advance = style.text.em_advance(cx.font_cache);
1317        let overscroll = vec2f(em_width, 0.);
1318        let snapshot = self.update_view(cx.app, |view, cx| {
1319            let wrap_width = match view.soft_wrap_mode(cx) {
1320                SoftWrap::None => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
1321                SoftWrap::EditorWidth => {
1322                    Some(text_width - gutter_margin - overscroll.x() - em_width)
1323                }
1324                SoftWrap::Column(column) => Some(column as f32 * em_advance),
1325            };
1326
1327            if view.set_wrap_width(wrap_width, cx) {
1328                view.snapshot(cx)
1329            } else {
1330                snapshot
1331            }
1332        });
1333
1334        let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
1335        if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
1336            size.set_y(
1337                scroll_height
1338                    .min(constraint.max_along(Axis::Vertical))
1339                    .max(constraint.min_along(Axis::Vertical))
1340                    .min(line_height * max_lines as f32),
1341            )
1342        } else if let EditorMode::SingleLine = snapshot.mode {
1343            size.set_y(
1344                line_height
1345                    .min(constraint.max_along(Axis::Vertical))
1346                    .max(constraint.min_along(Axis::Vertical)),
1347            )
1348        } else if size.y().is_infinite() {
1349            size.set_y(scroll_height);
1350        }
1351        let gutter_size = vec2f(gutter_width, size.y());
1352        let text_size = vec2f(text_width, size.y());
1353
1354        let (autoscroll_horizontally, mut snapshot) = self.update_view(cx.app, |view, cx| {
1355            let autoscroll_horizontally = view.autoscroll_vertically(size.y(), line_height, cx);
1356            let snapshot = view.snapshot(cx);
1357            (autoscroll_horizontally, snapshot)
1358        });
1359
1360        let scroll_position = snapshot.scroll_position();
1361        // The scroll position is a fractional point, the whole number of which represents
1362        // the top of the window in terms of display rows.
1363        let start_row = scroll_position.y() as u32;
1364        let scroll_top = scroll_position.y() * line_height;
1365
1366        // Add 1 to ensure selections bleed off screen
1367        let end_row = 1 + cmp::min(
1368            ((scroll_top + size.y()) / line_height).ceil() as u32,
1369            snapshot.max_point().row(),
1370        );
1371
1372        let start_anchor = if start_row == 0 {
1373            Anchor::min()
1374        } else {
1375            snapshot
1376                .buffer_snapshot
1377                .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
1378        };
1379        let end_anchor = if end_row > snapshot.max_point().row() {
1380            Anchor::max()
1381        } else {
1382            snapshot
1383                .buffer_snapshot
1384                .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
1385        };
1386
1387        let mut selections: Vec<(ReplicaId, Vec<SelectionLayout>)> = Vec::new();
1388        let mut active_rows = BTreeMap::new();
1389        let mut highlighted_rows = None;
1390        let mut highlighted_ranges = Vec::new();
1391        self.update_view(cx.app, |view, cx| {
1392            let display_map = view.display_map.update(cx, |map, cx| map.snapshot(cx));
1393
1394            highlighted_rows = view.highlighted_rows();
1395            let theme = cx.global::<Settings>().theme.as_ref();
1396            highlighted_ranges = view.background_highlights_in_range(
1397                start_anchor.clone()..end_anchor.clone(),
1398                &display_map,
1399                theme,
1400            );
1401
1402            let mut remote_selections = HashMap::default();
1403            for (replica_id, line_mode, selection) in display_map
1404                .buffer_snapshot
1405                .remote_selections_in_range(&(start_anchor.clone()..end_anchor.clone()))
1406            {
1407                // The local selections match the leader's selections.
1408                if Some(replica_id) == view.leader_replica_id {
1409                    continue;
1410                }
1411                remote_selections
1412                    .entry(replica_id)
1413                    .or_insert(Vec::new())
1414                    .push(SelectionLayout::new(selection, line_mode, &display_map));
1415            }
1416            selections.extend(remote_selections);
1417
1418            if view.show_local_selections {
1419                let mut local_selections = view
1420                    .selections
1421                    .disjoint_in_range(start_anchor..end_anchor, cx);
1422                local_selections.extend(view.selections.pending(cx));
1423                for selection in &local_selections {
1424                    let is_empty = selection.start == selection.end;
1425                    let selection_start = snapshot.prev_line_boundary(selection.start).1;
1426                    let selection_end = snapshot.next_line_boundary(selection.end).1;
1427                    for row in cmp::max(selection_start.row(), start_row)
1428                        ..=cmp::min(selection_end.row(), end_row)
1429                    {
1430                        let contains_non_empty_selection =
1431                            active_rows.entry(row).or_insert(!is_empty);
1432                        *contains_non_empty_selection |= !is_empty;
1433                    }
1434                }
1435
1436                // Render the local selections in the leader's color when following.
1437                let local_replica_id = view
1438                    .leader_replica_id
1439                    .unwrap_or_else(|| view.replica_id(cx));
1440
1441                selections.push((
1442                    local_replica_id,
1443                    local_selections
1444                        .into_iter()
1445                        .map(|selection| {
1446                            SelectionLayout::new(selection, view.selections.line_mode, &display_map)
1447                        })
1448                        .collect(),
1449                ));
1450            }
1451        });
1452
1453        let line_number_layouts =
1454            self.layout_line_numbers(start_row..end_row, &active_rows, &snapshot, cx);
1455
1456        let diff_hunks = snapshot
1457            .buffer_snapshot
1458            .diff_hunks_in_range(start_row..end_row)
1459            .collect();
1460
1461        let mut max_visible_line_width = 0.0;
1462        let line_layouts = self.layout_lines(start_row..end_row, &snapshot, cx);
1463        for line in &line_layouts {
1464            if line.width() > max_visible_line_width {
1465                max_visible_line_width = line.width();
1466            }
1467        }
1468
1469        let style = self.style.clone();
1470        let longest_line_width = layout_line(
1471            snapshot.longest_row(),
1472            &snapshot,
1473            &style,
1474            cx.text_layout_cache,
1475        )
1476        .width();
1477        let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
1478        let em_width = style.text.em_width(cx.font_cache);
1479        let (scroll_width, blocks) = self.layout_blocks(
1480            start_row..end_row,
1481            &snapshot,
1482            size.x(),
1483            scroll_width,
1484            gutter_padding,
1485            gutter_width,
1486            em_width,
1487            gutter_width + gutter_margin,
1488            line_height,
1489            &style,
1490            &line_layouts,
1491            cx,
1492        );
1493
1494        let max_row = snapshot.max_point().row();
1495        let scroll_max = vec2f(
1496            ((scroll_width - text_size.x()) / em_width).max(0.0),
1497            max_row.saturating_sub(1) as f32,
1498        );
1499
1500        self.update_view(cx.app, |view, cx| {
1501            let clamped = view.clamp_scroll_left(scroll_max.x());
1502
1503            let autoscrolled = if autoscroll_horizontally {
1504                view.autoscroll_horizontally(
1505                    start_row,
1506                    text_size.x(),
1507                    scroll_width,
1508                    em_width,
1509                    &line_layouts,
1510                    cx,
1511                )
1512            } else {
1513                false
1514            };
1515
1516            if clamped || autoscrolled {
1517                snapshot = view.snapshot(cx);
1518            }
1519        });
1520
1521        let mut context_menu = None;
1522        let mut code_actions_indicator = None;
1523        let mut hover = None;
1524        cx.render(&self.view.upgrade(cx).unwrap(), |view, cx| {
1525            let newest_selection_head = view
1526                .selections
1527                .newest::<usize>(cx)
1528                .head()
1529                .to_display_point(&snapshot);
1530
1531            let style = view.style(cx);
1532            if (start_row..end_row).contains(&newest_selection_head.row()) {
1533                if view.context_menu_visible() {
1534                    context_menu =
1535                        view.render_context_menu(newest_selection_head, style.clone(), cx);
1536                }
1537
1538                code_actions_indicator = view
1539                    .render_code_actions_indicator(&style, cx)
1540                    .map(|indicator| (newest_selection_head.row(), indicator));
1541            }
1542
1543            let visible_rows = start_row..start_row + line_layouts.len() as u32;
1544            hover = view.hover_state.render(&snapshot, &style, visible_rows, cx);
1545        });
1546
1547        if let Some((_, context_menu)) = context_menu.as_mut() {
1548            context_menu.layout(
1549                SizeConstraint {
1550                    min: Vector2F::zero(),
1551                    max: vec2f(
1552                        cx.window_size.x() * 0.7,
1553                        (12. * line_height).min((size.y() - line_height) / 2.),
1554                    ),
1555                },
1556                cx,
1557            );
1558        }
1559
1560        if let Some((_, indicator)) = code_actions_indicator.as_mut() {
1561            indicator.layout(
1562                SizeConstraint::strict_along(
1563                    Axis::Vertical,
1564                    line_height * style.code_actions.vertical_scale,
1565                ),
1566                cx,
1567            );
1568        }
1569
1570        if let Some((_, hover_popovers)) = hover.as_mut() {
1571            for hover_popover in hover_popovers.iter_mut() {
1572                hover_popover.layout(
1573                    SizeConstraint {
1574                        min: Vector2F::zero(),
1575                        max: vec2f(
1576                            (120. * em_width) // Default size
1577                                .min(size.x() / 2.) // Shrink to half of the editor width
1578                                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
1579                            (16. * line_height) // Default size
1580                                .min(size.y() / 2.) // Shrink to half of the editor height
1581                                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
1582                        ),
1583                    },
1584                    cx,
1585                );
1586            }
1587        }
1588
1589        (
1590            size,
1591            LayoutState {
1592                position_map: Arc::new(PositionMap {
1593                    size,
1594                    scroll_max,
1595                    line_layouts,
1596                    line_height,
1597                    em_width,
1598                    em_advance,
1599                    snapshot,
1600                }),
1601                gutter_size,
1602                gutter_padding,
1603                text_size,
1604                gutter_margin,
1605                active_rows,
1606                highlighted_rows,
1607                highlighted_ranges,
1608                line_number_layouts,
1609                diff_hunks,
1610                blocks,
1611                selections,
1612                context_menu,
1613                code_actions_indicator,
1614                hover_popovers: hover,
1615            },
1616        )
1617    }
1618
1619    fn paint(
1620        &mut self,
1621        bounds: RectF,
1622        visible_bounds: RectF,
1623        layout: &mut Self::LayoutState,
1624        cx: &mut PaintContext,
1625    ) -> Self::PaintState {
1626        cx.scene.push_layer(Some(bounds));
1627
1628        let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
1629        let text_bounds = RectF::new(
1630            bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
1631            layout.text_size,
1632        );
1633
1634        Self::attach_mouse_handlers(
1635            &self.view,
1636            &layout.position_map,
1637            visible_bounds,
1638            text_bounds,
1639            gutter_bounds,
1640            bounds,
1641            cx,
1642        );
1643
1644        self.paint_background(gutter_bounds, text_bounds, layout, cx);
1645        if layout.gutter_size.x() > 0. {
1646            self.paint_gutter(gutter_bounds, visible_bounds, layout, cx);
1647        }
1648        self.paint_text(text_bounds, visible_bounds, layout, cx);
1649
1650        if !layout.blocks.is_empty() {
1651            cx.scene.push_layer(Some(bounds));
1652            self.paint_blocks(bounds, visible_bounds, layout, cx);
1653            cx.scene.pop_layer();
1654        }
1655
1656        cx.scene.pop_layer();
1657    }
1658
1659    fn dispatch_event(
1660        &mut self,
1661        event: &Event,
1662        _: RectF,
1663        _: RectF,
1664        _: &mut LayoutState,
1665        _: &mut (),
1666        cx: &mut EventContext,
1667    ) -> bool {
1668        if let Event::ModifiersChanged(event) = event {
1669            self.modifiers_changed(*event, cx);
1670        }
1671
1672        false
1673    }
1674
1675    fn rect_for_text_range(
1676        &self,
1677        range_utf16: Range<usize>,
1678        bounds: RectF,
1679        _: RectF,
1680        layout: &Self::LayoutState,
1681        _: &Self::PaintState,
1682        _: &gpui::MeasurementContext,
1683    ) -> Option<RectF> {
1684        let text_bounds = RectF::new(
1685            bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
1686            layout.text_size,
1687        );
1688        let content_origin = text_bounds.origin() + vec2f(layout.gutter_margin, 0.);
1689        let scroll_position = layout.position_map.snapshot.scroll_position();
1690        let start_row = scroll_position.y() as u32;
1691        let scroll_top = scroll_position.y() * layout.position_map.line_height;
1692        let scroll_left = scroll_position.x() * layout.position_map.em_width;
1693
1694        let range_start = OffsetUtf16(range_utf16.start)
1695            .to_display_point(&layout.position_map.snapshot.display_snapshot);
1696        if range_start.row() < start_row {
1697            return None;
1698        }
1699
1700        let line = layout
1701            .position_map
1702            .line_layouts
1703            .get((range_start.row() - start_row) as usize)?;
1704        let range_start_x = line.x_for_index(range_start.column() as usize);
1705        let range_start_y = range_start.row() as f32 * layout.position_map.line_height;
1706        Some(RectF::new(
1707            content_origin
1708                + vec2f(
1709                    range_start_x,
1710                    range_start_y + layout.position_map.line_height,
1711                )
1712                - vec2f(scroll_left, scroll_top),
1713            vec2f(
1714                layout.position_map.em_width,
1715                layout.position_map.line_height,
1716            ),
1717        ))
1718    }
1719
1720    fn debug(
1721        &self,
1722        bounds: RectF,
1723        _: &Self::LayoutState,
1724        _: &Self::PaintState,
1725        _: &gpui::DebugContext,
1726    ) -> json::Value {
1727        json!({
1728            "type": "BufferElement",
1729            "bounds": bounds.to_json()
1730        })
1731    }
1732}
1733
1734pub struct LayoutState {
1735    position_map: Arc<PositionMap>,
1736    gutter_size: Vector2F,
1737    gutter_padding: f32,
1738    gutter_margin: f32,
1739    text_size: Vector2F,
1740    active_rows: BTreeMap<u32, bool>,
1741    highlighted_rows: Option<Range<u32>>,
1742    line_number_layouts: Vec<Option<text_layout::Line>>,
1743    blocks: Vec<BlockLayout>,
1744    highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
1745    selections: Vec<(ReplicaId, Vec<SelectionLayout>)>,
1746    context_menu: Option<(DisplayPoint, ElementBox)>,
1747    diff_hunks: Vec<DiffHunk<u32>>,
1748    code_actions_indicator: Option<(u32, ElementBox)>,
1749    hover_popovers: Option<(DisplayPoint, Vec<ElementBox>)>,
1750}
1751
1752pub struct PositionMap {
1753    size: Vector2F,
1754    line_height: f32,
1755    scroll_max: Vector2F,
1756    em_width: f32,
1757    em_advance: f32,
1758    line_layouts: Vec<text_layout::Line>,
1759    snapshot: EditorSnapshot,
1760}
1761
1762impl PositionMap {
1763    /// Returns two display points:
1764    /// 1. The nearest *valid* position in the editor
1765    /// 2. An unclipped, potentially *invalid* position that maps directly to
1766    ///    the given pixel position.
1767    fn point_for_position(
1768        &self,
1769        text_bounds: RectF,
1770        position: Vector2F,
1771    ) -> (DisplayPoint, DisplayPoint) {
1772        let scroll_position = self.snapshot.scroll_position();
1773        let position = position - text_bounds.origin();
1774        let y = position.y().max(0.0).min(self.size.y());
1775        let x = position.x() + (scroll_position.x() * self.em_width);
1776        let row = (y / self.line_height + scroll_position.y()) as u32;
1777        let (column, x_overshoot) = if let Some(line) = self
1778            .line_layouts
1779            .get(row as usize - scroll_position.y() as usize)
1780        {
1781            if let Some(ix) = line.index_for_x(x) {
1782                (ix as u32, 0.0)
1783            } else {
1784                (line.len() as u32, 0f32.max(x - line.width()))
1785            }
1786        } else {
1787            (0, x)
1788        };
1789
1790        let mut target_point = DisplayPoint::new(row, column);
1791        let point = self.snapshot.clip_point(target_point, Bias::Left);
1792        *target_point.column_mut() += (x_overshoot / self.em_advance) as u32;
1793
1794        (point, target_point)
1795    }
1796}
1797
1798struct BlockLayout {
1799    row: u32,
1800    element: ElementBox,
1801    style: BlockStyle,
1802}
1803
1804fn layout_line(
1805    row: u32,
1806    snapshot: &EditorSnapshot,
1807    style: &EditorStyle,
1808    layout_cache: &TextLayoutCache,
1809) -> text_layout::Line {
1810    let mut line = snapshot.line(row);
1811
1812    if line.len() > MAX_LINE_LEN {
1813        let mut len = MAX_LINE_LEN;
1814        while !line.is_char_boundary(len) {
1815            len -= 1;
1816        }
1817
1818        line.truncate(len);
1819    }
1820
1821    layout_cache.layout_str(
1822        &line,
1823        style.text.font_size,
1824        &[(
1825            snapshot.line_len(row) as usize,
1826            RunStyle {
1827                font_id: style.text.font_id,
1828                color: Color::black(),
1829                underline: Default::default(),
1830            },
1831        )],
1832    )
1833}
1834
1835#[derive(Copy, Clone, PartialEq, Eq, Debug)]
1836pub enum CursorShape {
1837    Bar,
1838    Block,
1839    Underscore,
1840    Hollow,
1841}
1842
1843impl Default for CursorShape {
1844    fn default() -> Self {
1845        CursorShape::Bar
1846    }
1847}
1848
1849#[derive(Debug)]
1850pub struct Cursor {
1851    origin: Vector2F,
1852    block_width: f32,
1853    line_height: f32,
1854    color: Color,
1855    shape: CursorShape,
1856    block_text: Option<Line>,
1857}
1858
1859impl Cursor {
1860    pub fn new(
1861        origin: Vector2F,
1862        block_width: f32,
1863        line_height: f32,
1864        color: Color,
1865        shape: CursorShape,
1866        block_text: Option<Line>,
1867    ) -> Cursor {
1868        Cursor {
1869            origin,
1870            block_width,
1871            line_height,
1872            color,
1873            shape,
1874            block_text,
1875        }
1876    }
1877
1878    pub fn bounding_rect(&self, origin: Vector2F) -> RectF {
1879        RectF::new(
1880            self.origin + origin,
1881            vec2f(self.block_width, self.line_height),
1882        )
1883    }
1884
1885    pub fn paint(&self, origin: Vector2F, cx: &mut PaintContext) {
1886        let bounds = match self.shape {
1887            CursorShape::Bar => RectF::new(self.origin + origin, vec2f(2.0, self.line_height)),
1888            CursorShape::Block | CursorShape::Hollow => RectF::new(
1889                self.origin + origin,
1890                vec2f(self.block_width, self.line_height),
1891            ),
1892            CursorShape::Underscore => RectF::new(
1893                self.origin + origin + Vector2F::new(0.0, self.line_height - 2.0),
1894                vec2f(self.block_width, 2.0),
1895            ),
1896        };
1897
1898        //Draw background or border quad
1899        if matches!(self.shape, CursorShape::Hollow) {
1900            cx.scene.push_quad(Quad {
1901                bounds,
1902                background: None,
1903                border: Border::all(1., self.color),
1904                corner_radius: 0.,
1905            });
1906        } else {
1907            cx.scene.push_quad(Quad {
1908                bounds,
1909                background: Some(self.color),
1910                border: Default::default(),
1911                corner_radius: 0.,
1912            });
1913        }
1914
1915        if let Some(block_text) = &self.block_text {
1916            block_text.paint(self.origin + origin, bounds, self.line_height, cx);
1917        }
1918    }
1919
1920    pub fn shape(&self) -> CursorShape {
1921        self.shape
1922    }
1923}
1924
1925#[derive(Debug)]
1926pub struct HighlightedRange {
1927    pub start_y: f32,
1928    pub line_height: f32,
1929    pub lines: Vec<HighlightedRangeLine>,
1930    pub color: Color,
1931    pub corner_radius: f32,
1932}
1933
1934#[derive(Debug)]
1935pub struct HighlightedRangeLine {
1936    pub start_x: f32,
1937    pub end_x: f32,
1938}
1939
1940impl HighlightedRange {
1941    pub fn paint(&self, bounds: RectF, scene: &mut Scene) {
1942        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
1943            self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
1944            self.paint_lines(
1945                self.start_y + self.line_height,
1946                &self.lines[1..],
1947                bounds,
1948                scene,
1949            );
1950        } else {
1951            self.paint_lines(self.start_y, &self.lines, bounds, scene);
1952        }
1953    }
1954
1955    fn paint_lines(
1956        &self,
1957        start_y: f32,
1958        lines: &[HighlightedRangeLine],
1959        bounds: RectF,
1960        scene: &mut Scene,
1961    ) {
1962        if lines.is_empty() {
1963            return;
1964        }
1965
1966        let mut path = PathBuilder::new();
1967        let first_line = lines.first().unwrap();
1968        let last_line = lines.last().unwrap();
1969
1970        let first_top_left = vec2f(first_line.start_x, start_y);
1971        let first_top_right = vec2f(first_line.end_x, start_y);
1972
1973        let curve_height = vec2f(0., self.corner_radius);
1974        let curve_width = |start_x: f32, end_x: f32| {
1975            let max = (end_x - start_x) / 2.;
1976            let width = if max < self.corner_radius {
1977                max
1978            } else {
1979                self.corner_radius
1980            };
1981
1982            vec2f(width, 0.)
1983        };
1984
1985        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
1986        path.reset(first_top_right - top_curve_width);
1987        path.curve_to(first_top_right + curve_height, first_top_right);
1988
1989        let mut iter = lines.iter().enumerate().peekable();
1990        while let Some((ix, line)) = iter.next() {
1991            let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
1992
1993            if let Some((_, next_line)) = iter.peek() {
1994                let next_top_right = vec2f(next_line.end_x, bottom_right.y());
1995
1996                match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
1997                    Ordering::Equal => {
1998                        path.line_to(bottom_right);
1999                    }
2000                    Ordering::Less => {
2001                        let curve_width = curve_width(next_top_right.x(), bottom_right.x());
2002                        path.line_to(bottom_right - curve_height);
2003                        if self.corner_radius > 0. {
2004                            path.curve_to(bottom_right - curve_width, bottom_right);
2005                        }
2006                        path.line_to(next_top_right + curve_width);
2007                        if self.corner_radius > 0. {
2008                            path.curve_to(next_top_right + curve_height, next_top_right);
2009                        }
2010                    }
2011                    Ordering::Greater => {
2012                        let curve_width = curve_width(bottom_right.x(), next_top_right.x());
2013                        path.line_to(bottom_right - curve_height);
2014                        if self.corner_radius > 0. {
2015                            path.curve_to(bottom_right + curve_width, bottom_right);
2016                        }
2017                        path.line_to(next_top_right - curve_width);
2018                        if self.corner_radius > 0. {
2019                            path.curve_to(next_top_right + curve_height, next_top_right);
2020                        }
2021                    }
2022                }
2023            } else {
2024                let curve_width = curve_width(line.start_x, line.end_x);
2025                path.line_to(bottom_right - curve_height);
2026                if self.corner_radius > 0. {
2027                    path.curve_to(bottom_right - curve_width, bottom_right);
2028                }
2029
2030                let bottom_left = vec2f(line.start_x, bottom_right.y());
2031                path.line_to(bottom_left + curve_width);
2032                if self.corner_radius > 0. {
2033                    path.curve_to(bottom_left - curve_height, bottom_left);
2034                }
2035            }
2036        }
2037
2038        if first_line.start_x > last_line.start_x {
2039            let curve_width = curve_width(last_line.start_x, first_line.start_x);
2040            let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
2041            path.line_to(second_top_left + curve_height);
2042            if self.corner_radius > 0. {
2043                path.curve_to(second_top_left + curve_width, second_top_left);
2044            }
2045            let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
2046            path.line_to(first_bottom_left - curve_width);
2047            if self.corner_radius > 0. {
2048                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
2049            }
2050        }
2051
2052        path.line_to(first_top_left + curve_height);
2053        if self.corner_radius > 0. {
2054            path.curve_to(first_top_left + top_curve_width, first_top_left);
2055        }
2056        path.line_to(first_top_right - top_curve_width);
2057
2058        scene.push_path(path.build(self.color, Some(bounds)));
2059    }
2060}
2061
2062pub fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
2063    delta.powf(1.5) / 100.0
2064}
2065
2066fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
2067    delta.powf(1.2) / 300.0
2068}
2069
2070#[cfg(test)]
2071mod tests {
2072    use std::sync::Arc;
2073
2074    use super::*;
2075    use crate::{
2076        display_map::{BlockDisposition, BlockProperties},
2077        Editor, MultiBuffer,
2078    };
2079    use settings::Settings;
2080    use util::test::sample_text;
2081
2082    #[gpui::test]
2083    fn test_layout_line_numbers(cx: &mut gpui::MutableAppContext) {
2084        cx.set_global(Settings::test(cx));
2085        let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
2086        let (window_id, editor) = cx.add_window(Default::default(), |cx| {
2087            Editor::new(EditorMode::Full, buffer, None, None, cx)
2088        });
2089        let element = EditorElement::new(
2090            editor.downgrade(),
2091            editor.read(cx).style(cx),
2092            CursorShape::Bar,
2093        );
2094
2095        let layouts = editor.update(cx, |editor, cx| {
2096            let snapshot = editor.snapshot(cx);
2097            let mut presenter = cx.build_presenter(window_id, 30., Default::default());
2098            let layout_cx = presenter.build_layout_context(Vector2F::zero(), false, cx);
2099            element.layout_line_numbers(0..6, &Default::default(), &snapshot, &layout_cx)
2100        });
2101        assert_eq!(layouts.len(), 6);
2102    }
2103
2104    #[gpui::test]
2105    fn test_layout_with_placeholder_text_and_blocks(cx: &mut gpui::MutableAppContext) {
2106        cx.set_global(Settings::test(cx));
2107        let buffer = MultiBuffer::build_simple("", cx);
2108        let (window_id, editor) = cx.add_window(Default::default(), |cx| {
2109            Editor::new(EditorMode::Full, buffer, None, None, cx)
2110        });
2111
2112        editor.update(cx, |editor, cx| {
2113            editor.set_placeholder_text("hello", cx);
2114            editor.insert_blocks(
2115                [BlockProperties {
2116                    style: BlockStyle::Fixed,
2117                    disposition: BlockDisposition::Above,
2118                    height: 3,
2119                    position: Anchor::min(),
2120                    render: Arc::new(|_| Empty::new().boxed()),
2121                }],
2122                cx,
2123            );
2124
2125            // Blur the editor so that it displays placeholder text.
2126            cx.blur();
2127        });
2128
2129        let mut element = EditorElement::new(
2130            editor.downgrade(),
2131            editor.read(cx).style(cx),
2132            CursorShape::Bar,
2133        );
2134
2135        let mut scene = Scene::new(1.0);
2136        let mut presenter = cx.build_presenter(window_id, 30., Default::default());
2137        let mut layout_cx = presenter.build_layout_context(Vector2F::zero(), false, cx);
2138        let (size, mut state) = element.layout(
2139            SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
2140            &mut layout_cx,
2141        );
2142
2143        assert_eq!(state.position_map.line_layouts.len(), 4);
2144        assert_eq!(
2145            state
2146                .line_number_layouts
2147                .iter()
2148                .map(Option::is_some)
2149                .collect::<Vec<_>>(),
2150            &[false, false, false, true]
2151        );
2152
2153        // Don't panic.
2154        let bounds = RectF::new(Default::default(), size);
2155        let mut paint_cx = presenter.build_paint_context(&mut scene, bounds.size(), cx);
2156        element.paint(bounds, bounds, &mut state, &mut paint_cx);
2157    }
2158}