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