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