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