element.rs

   1use super::{
   2    display_map::{BlockContext, ToDisplayPoint},
   3    Anchor, DisplayPoint, Editor, EditorMode, EditorSnapshot, Input, Scroll, Select, SelectPhase,
   4    SoftWrap, ToPoint, MAX_LINE_LEN,
   5};
   6use crate::{display_map::TransformBlock, EditorStyle};
   7use clock::ReplicaId;
   8use collections::{BTreeMap, HashMap};
   9use gpui::{
  10    color::Color,
  11    elements::*,
  12    fonts::{HighlightStyle, Underline},
  13    geometry::{
  14        rect::RectF,
  15        vector::{vec2f, Vector2F},
  16        PathBuilder,
  17    },
  18    json::{self, ToJson},
  19    text_layout::{self, Line, RunStyle, TextLayoutCache},
  20    AppContext, Axis, Border, Element, ElementBox, Event, EventContext, LayoutContext,
  21    MutableAppContext, PaintContext, Quad, Scene, SizeConstraint, ViewContext, WeakViewHandle,
  22};
  23use json::json;
  24use language::{Bias, DiagnosticSeverity};
  25use smallvec::SmallVec;
  26use std::{
  27    cmp::{self, Ordering},
  28    fmt::Write,
  29    iter,
  30    ops::Range,
  31};
  32
  33pub struct EditorElement {
  34    view: WeakViewHandle<Editor>,
  35    style: EditorStyle,
  36    cursor_shape: CursorShape,
  37}
  38
  39impl EditorElement {
  40    pub fn new(
  41        view: WeakViewHandle<Editor>,
  42        style: EditorStyle,
  43        cursor_shape: CursorShape,
  44    ) -> Self {
  45        Self {
  46            view,
  47            style,
  48            cursor_shape,
  49        }
  50    }
  51
  52    fn view<'a>(&self, cx: &'a AppContext) -> &'a Editor {
  53        self.view.upgrade(cx).unwrap().read(cx)
  54    }
  55
  56    fn update_view<F, T>(&self, cx: &mut MutableAppContext, f: F) -> T
  57    where
  58        F: FnOnce(&mut Editor, &mut ViewContext<Editor>) -> T,
  59    {
  60        self.view.upgrade(cx).unwrap().update(cx, f)
  61    }
  62
  63    fn snapshot(&self, cx: &mut MutableAppContext) -> EditorSnapshot {
  64        self.update_view(cx, |view, cx| view.snapshot(cx))
  65    }
  66
  67    fn mouse_down(
  68        &self,
  69        position: Vector2F,
  70        alt: bool,
  71        shift: bool,
  72        mut click_count: usize,
  73        layout: &mut LayoutState,
  74        paint: &mut PaintState,
  75        cx: &mut EventContext,
  76    ) -> bool {
  77        if paint.gutter_bounds.contains_point(position) {
  78            click_count = 3; // Simulate triple-click when clicking the gutter to select lines
  79        } else if !paint.text_bounds.contains_point(position) {
  80            return false;
  81        }
  82
  83        let snapshot = self.snapshot(cx.app);
  84        let (position, overshoot) = paint.point_for_position(&snapshot, layout, position);
  85
  86        if shift && alt {
  87            cx.dispatch_action(Select(SelectPhase::BeginColumnar {
  88                position,
  89                overshoot,
  90            }));
  91        } else if shift {
  92            cx.dispatch_action(Select(SelectPhase::Extend {
  93                position,
  94                click_count,
  95            }));
  96        } else {
  97            cx.dispatch_action(Select(SelectPhase::Begin {
  98                position,
  99                add: alt,
 100                click_count,
 101            }));
 102        }
 103
 104        true
 105    }
 106
 107    fn mouse_up(&self, _position: Vector2F, cx: &mut EventContext) -> bool {
 108        if self.view(cx.app.as_ref()).is_selecting() {
 109            cx.dispatch_action(Select(SelectPhase::End));
 110            true
 111        } else {
 112            false
 113        }
 114    }
 115
 116    fn mouse_dragged(
 117        &self,
 118        position: Vector2F,
 119        layout: &mut LayoutState,
 120        paint: &mut PaintState,
 121        cx: &mut EventContext,
 122    ) -> bool {
 123        let view = self.view(cx.app.as_ref());
 124
 125        if view.is_selecting() {
 126            let rect = paint.text_bounds;
 127            let mut scroll_delta = Vector2F::zero();
 128
 129            let vertical_margin = layout.line_height.min(rect.height() / 3.0);
 130            let top = rect.origin_y() + vertical_margin;
 131            let bottom = rect.lower_left().y() - vertical_margin;
 132            if position.y() < top {
 133                scroll_delta.set_y(-scale_vertical_mouse_autoscroll_delta(top - position.y()))
 134            }
 135            if position.y() > bottom {
 136                scroll_delta.set_y(scale_vertical_mouse_autoscroll_delta(position.y() - bottom))
 137            }
 138
 139            let horizontal_margin = layout.line_height.min(rect.width() / 3.0);
 140            let left = rect.origin_x() + horizontal_margin;
 141            let right = rect.upper_right().x() - horizontal_margin;
 142            if position.x() < left {
 143                scroll_delta.set_x(-scale_horizontal_mouse_autoscroll_delta(
 144                    left - position.x(),
 145                ))
 146            }
 147            if position.x() > right {
 148                scroll_delta.set_x(scale_horizontal_mouse_autoscroll_delta(
 149                    position.x() - right,
 150                ))
 151            }
 152
 153            let snapshot = self.snapshot(cx.app);
 154            let (position, overshoot) = paint.point_for_position(&snapshot, layout, position);
 155
 156            cx.dispatch_action(Select(SelectPhase::Update {
 157                position,
 158                overshoot,
 159                scroll_position: (snapshot.scroll_position() + scroll_delta)
 160                    .clamp(Vector2F::zero(), layout.scroll_max),
 161            }));
 162            true
 163        } else {
 164            false
 165        }
 166    }
 167
 168    fn key_down(&self, input: Option<&str>, cx: &mut EventContext) -> bool {
 169        let view = self.view.upgrade(cx.app).unwrap();
 170
 171        if view.is_focused(cx.app) {
 172            if let Some(input) = input {
 173                cx.dispatch_action(Input(input.to_string()));
 174                true
 175            } else {
 176                false
 177            }
 178        } else {
 179            false
 180        }
 181    }
 182
 183    fn scroll(
 184        &self,
 185        position: Vector2F,
 186        mut delta: Vector2F,
 187        precise: bool,
 188        layout: &mut LayoutState,
 189        paint: &mut PaintState,
 190        cx: &mut EventContext,
 191    ) -> bool {
 192        if !paint.bounds.contains_point(position) {
 193            return false;
 194        }
 195
 196        let snapshot = self.snapshot(cx.app);
 197        let max_glyph_width = layout.em_width;
 198        if !precise {
 199            delta *= vec2f(max_glyph_width, layout.line_height);
 200        }
 201
 202        let scroll_position = snapshot.scroll_position();
 203        let x = (scroll_position.x() * max_glyph_width - delta.x()) / max_glyph_width;
 204        let y = (scroll_position.y() * layout.line_height - delta.y()) / layout.line_height;
 205        let scroll_position = vec2f(x, y).clamp(Vector2F::zero(), layout.scroll_max);
 206
 207        cx.dispatch_action(Scroll(scroll_position));
 208
 209        true
 210    }
 211
 212    fn paint_background(
 213        &self,
 214        gutter_bounds: RectF,
 215        text_bounds: RectF,
 216        layout: &LayoutState,
 217        cx: &mut PaintContext,
 218    ) {
 219        let bounds = gutter_bounds.union_rect(text_bounds);
 220        let scroll_top = layout.snapshot.scroll_position().y() * layout.line_height;
 221        let editor = self.view(cx.app);
 222        cx.scene.push_quad(Quad {
 223            bounds: gutter_bounds,
 224            background: Some(self.style.gutter_background),
 225            border: Border::new(0., Color::transparent_black()),
 226            corner_radius: 0.,
 227        });
 228        cx.scene.push_quad(Quad {
 229            bounds: text_bounds,
 230            background: Some(self.style.background),
 231            border: Border::new(0., Color::transparent_black()),
 232            corner_radius: 0.,
 233        });
 234
 235        if let EditorMode::Full = editor.mode {
 236            let mut active_rows = layout.active_rows.iter().peekable();
 237            while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
 238                let mut end_row = *start_row;
 239                while active_rows.peek().map_or(false, |r| {
 240                    *r.0 == end_row + 1 && r.1 == contains_non_empty_selection
 241                }) {
 242                    active_rows.next().unwrap();
 243                    end_row += 1;
 244                }
 245
 246                if !contains_non_empty_selection {
 247                    let origin = vec2f(
 248                        bounds.origin_x(),
 249                        bounds.origin_y() + (layout.line_height * *start_row as f32) - scroll_top,
 250                    );
 251                    let size = vec2f(
 252                        bounds.width(),
 253                        layout.line_height * (end_row - start_row + 1) as f32,
 254                    );
 255                    cx.scene.push_quad(Quad {
 256                        bounds: RectF::new(origin, size),
 257                        background: Some(self.style.active_line_background),
 258                        border: Border::default(),
 259                        corner_radius: 0.,
 260                    });
 261                }
 262            }
 263
 264            if let Some(highlighted_rows) = &layout.highlighted_rows {
 265                let origin = vec2f(
 266                    bounds.origin_x(),
 267                    bounds.origin_y() + (layout.line_height * highlighted_rows.start as f32)
 268                        - scroll_top,
 269                );
 270                let size = vec2f(
 271                    bounds.width(),
 272                    layout.line_height * highlighted_rows.len() as f32,
 273                );
 274                cx.scene.push_quad(Quad {
 275                    bounds: RectF::new(origin, size),
 276                    background: Some(self.style.highlighted_line_background),
 277                    border: Border::default(),
 278                    corner_radius: 0.,
 279                });
 280            }
 281        }
 282    }
 283
 284    fn paint_gutter(
 285        &mut self,
 286        bounds: RectF,
 287        visible_bounds: RectF,
 288        layout: &mut LayoutState,
 289        cx: &mut PaintContext,
 290    ) {
 291        let scroll_top = layout.snapshot.scroll_position().y() * layout.line_height;
 292        for (ix, line) in layout.line_number_layouts.iter().enumerate() {
 293            if let Some(line) = line {
 294                let line_origin = bounds.origin()
 295                    + vec2f(
 296                        bounds.width() - line.width() - layout.gutter_padding,
 297                        ix as f32 * layout.line_height - (scroll_top % layout.line_height),
 298                    );
 299                line.paint(line_origin, visible_bounds, layout.line_height, cx);
 300            }
 301        }
 302
 303        if let Some((row, indicator)) = layout.code_actions_indicator.as_mut() {
 304            let mut x = bounds.width() - layout.gutter_padding;
 305            let mut y = *row as f32 * layout.line_height - scroll_top;
 306            x += ((layout.gutter_padding + layout.gutter_margin) - indicator.size().x()) / 2.;
 307            y += (layout.line_height - indicator.size().y()) / 2.;
 308            indicator.paint(bounds.origin() + vec2f(x, y), visible_bounds, cx);
 309        }
 310    }
 311
 312    fn paint_text(
 313        &mut self,
 314        bounds: RectF,
 315        visible_bounds: RectF,
 316        layout: &mut LayoutState,
 317        cx: &mut PaintContext,
 318    ) {
 319        let view = self.view(cx.app);
 320        let style = &self.style;
 321        let local_replica_id = view.replica_id(cx);
 322        let scroll_position = layout.snapshot.scroll_position();
 323        let start_row = scroll_position.y() as u32;
 324        let scroll_top = scroll_position.y() * layout.line_height;
 325        let end_row = ((scroll_top + bounds.height()) / layout.line_height).ceil() as u32 + 1; // Add 1 to ensure selections bleed off screen
 326        let max_glyph_width = layout.em_width;
 327        let scroll_left = scroll_position.x() * max_glyph_width;
 328        let content_origin = bounds.origin() + vec2f(layout.gutter_margin, 0.);
 329
 330        cx.scene.push_layer(Some(bounds));
 331
 332        for (range, color) in &layout.highlighted_ranges {
 333            self.paint_highlighted_range(
 334                range.clone(),
 335                start_row,
 336                end_row,
 337                *color,
 338                0.,
 339                0.15 * layout.line_height,
 340                layout,
 341                content_origin,
 342                scroll_top,
 343                scroll_left,
 344                bounds,
 345                cx,
 346            );
 347        }
 348
 349        let mut cursors = SmallVec::<[Cursor; 32]>::new();
 350        for (replica_id, selections) in &layout.selections {
 351            let selection_style = style.replica_selection_style(*replica_id);
 352            let corner_radius = 0.15 * layout.line_height;
 353
 354            for selection in selections {
 355                self.paint_highlighted_range(
 356                    selection.start..selection.end,
 357                    start_row,
 358                    end_row,
 359                    selection_style.selection,
 360                    corner_radius,
 361                    corner_radius * 2.,
 362                    layout,
 363                    content_origin,
 364                    scroll_top,
 365                    scroll_left,
 366                    bounds,
 367                    cx,
 368                );
 369
 370                if view.show_local_cursors() || *replica_id != local_replica_id {
 371                    let cursor_position = selection.head();
 372                    if (start_row..end_row).contains(&cursor_position.row()) {
 373                        let cursor_row_layout =
 374                            &layout.line_layouts[(cursor_position.row() - start_row) as usize];
 375                        let cursor_column = cursor_position.column() as usize;
 376
 377                        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 378                        let mut block_width =
 379                            cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
 380                        if block_width == 0.0 {
 381                            block_width = layout.em_width;
 382                        }
 383
 384                        let block_text =
 385                            if matches!(self.cursor_shape, CursorShape::Block) {
 386                                layout.snapshot.chars_at(cursor_position).next().and_then(
 387                                    |character| {
 388                                        let font_id =
 389                                            cursor_row_layout.font_for_index(cursor_column)?;
 390                                        let text = character.to_string();
 391
 392                                        Some(cx.text_layout_cache.layout_str(
 393                                            &text,
 394                                            cursor_row_layout.font_size(),
 395                                            &[(
 396                                                text.len(),
 397                                                RunStyle {
 398                                                    font_id,
 399                                                    color: style.background,
 400                                                    underline: Default::default(),
 401                                                },
 402                                            )],
 403                                        ))
 404                                    },
 405                                )
 406                            } else {
 407                                None
 408                            };
 409
 410                        let x = cursor_character_x - scroll_left;
 411                        let y = cursor_position.row() as f32 * layout.line_height - scroll_top;
 412                        cursors.push(Cursor {
 413                            color: selection_style.cursor,
 414                            block_width,
 415                            origin: content_origin + vec2f(x, y),
 416                            line_height: layout.line_height,
 417                            shape: self.cursor_shape,
 418                            block_text,
 419                        });
 420                    }
 421                }
 422            }
 423        }
 424
 425        if let Some(visible_text_bounds) = bounds.intersection(visible_bounds) {
 426            // Draw glyphs
 427            for (ix, line) in layout.line_layouts.iter().enumerate() {
 428                let row = start_row + ix as u32;
 429                line.paint(
 430                    content_origin
 431                        + vec2f(-scroll_left, row as f32 * layout.line_height - scroll_top),
 432                    visible_text_bounds,
 433                    layout.line_height,
 434                    cx,
 435                );
 436            }
 437        }
 438
 439        cx.scene.push_layer(Some(bounds));
 440        for cursor in cursors {
 441            cursor.paint(cx);
 442        }
 443        cx.scene.pop_layer();
 444
 445        if let Some((position, context_menu)) = layout.context_menu.as_mut() {
 446            cx.scene.push_stacking_context(None);
 447
 448            let cursor_row_layout = &layout.line_layouts[(position.row() - start_row) as usize];
 449            let x = cursor_row_layout.x_for_index(position.column() as usize) - scroll_left;
 450            let y = (position.row() + 1) as f32 * layout.line_height - scroll_top;
 451            let mut list_origin = content_origin + vec2f(x, y);
 452            let list_height = context_menu.size().y();
 453
 454            if list_origin.y() + list_height > bounds.lower_left().y() {
 455                list_origin.set_y(list_origin.y() - layout.line_height - list_height);
 456            }
 457
 458            context_menu.paint(
 459                list_origin,
 460                RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
 461                cx,
 462            );
 463
 464            cx.scene.pop_stacking_context();
 465        }
 466
 467        cx.scene.pop_layer();
 468    }
 469
 470    fn paint_highlighted_range(
 471        &self,
 472        range: Range<DisplayPoint>,
 473        start_row: u32,
 474        end_row: u32,
 475        color: Color,
 476        corner_radius: f32,
 477        line_end_overshoot: f32,
 478        layout: &LayoutState,
 479        content_origin: Vector2F,
 480        scroll_top: f32,
 481        scroll_left: f32,
 482        bounds: RectF,
 483        cx: &mut PaintContext,
 484    ) {
 485        if range.start != range.end {
 486            let row_range = if range.end.column() == 0 {
 487                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
 488            } else {
 489                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
 490            };
 491
 492            let highlighted_range = HighlightedRange {
 493                color,
 494                line_height: layout.line_height,
 495                corner_radius,
 496                start_y: content_origin.y() + row_range.start as f32 * layout.line_height
 497                    - scroll_top,
 498                lines: row_range
 499                    .into_iter()
 500                    .map(|row| {
 501                        let line_layout = &layout.line_layouts[(row - start_row) as usize];
 502                        HighlightedRangeLine {
 503                            start_x: if row == range.start.row() {
 504                                content_origin.x()
 505                                    + line_layout.x_for_index(range.start.column() as usize)
 506                                    - scroll_left
 507                            } else {
 508                                content_origin.x() - scroll_left
 509                            },
 510                            end_x: if row == range.end.row() {
 511                                content_origin.x()
 512                                    + line_layout.x_for_index(range.end.column() as usize)
 513                                    - scroll_left
 514                            } else {
 515                                content_origin.x() + line_layout.width() + line_end_overshoot
 516                                    - scroll_left
 517                            },
 518                        }
 519                    })
 520                    .collect(),
 521            };
 522
 523            highlighted_range.paint(bounds, cx.scene);
 524        }
 525    }
 526
 527    fn paint_blocks(
 528        &mut self,
 529        bounds: RectF,
 530        visible_bounds: RectF,
 531        layout: &mut LayoutState,
 532        cx: &mut PaintContext,
 533    ) {
 534        let scroll_position = layout.snapshot.scroll_position();
 535        let scroll_left = scroll_position.x() * layout.em_width;
 536        let scroll_top = scroll_position.y() * layout.line_height;
 537
 538        for (row, element) in &mut layout.blocks {
 539            let origin = bounds.origin()
 540                + vec2f(-scroll_left, *row as f32 * layout.line_height - scroll_top);
 541            element.paint(origin, visible_bounds, cx);
 542        }
 543    }
 544
 545    fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &LayoutContext) -> f32 {
 546        let digit_count = (snapshot.max_buffer_row() as f32).log10().floor() as usize + 1;
 547        let style = &self.style;
 548
 549        cx.text_layout_cache
 550            .layout_str(
 551                "1".repeat(digit_count).as_str(),
 552                style.text.font_size,
 553                &[(
 554                    digit_count,
 555                    RunStyle {
 556                        font_id: style.text.font_id,
 557                        color: Color::black(),
 558                        underline: Default::default(),
 559                    },
 560                )],
 561            )
 562            .width()
 563    }
 564
 565    fn layout_line_numbers(
 566        &self,
 567        rows: Range<u32>,
 568        active_rows: &BTreeMap<u32, bool>,
 569        snapshot: &EditorSnapshot,
 570        cx: &LayoutContext,
 571    ) -> Vec<Option<text_layout::Line>> {
 572        let style = &self.style;
 573        let include_line_numbers = snapshot.mode == EditorMode::Full;
 574        let mut line_number_layouts = Vec::with_capacity(rows.len());
 575        let mut line_number = String::new();
 576        for (ix, row) in snapshot
 577            .buffer_rows(rows.start)
 578            .take((rows.end - rows.start) as usize)
 579            .enumerate()
 580        {
 581            let display_row = rows.start + ix as u32;
 582            let color = if active_rows.contains_key(&display_row) {
 583                style.line_number_active
 584            } else {
 585                style.line_number
 586            };
 587            if let Some(buffer_row) = row {
 588                if include_line_numbers {
 589                    line_number.clear();
 590                    write!(&mut line_number, "{}", buffer_row + 1).unwrap();
 591                    line_number_layouts.push(Some(cx.text_layout_cache.layout_str(
 592                        &line_number,
 593                        style.text.font_size,
 594                        &[(
 595                            line_number.len(),
 596                            RunStyle {
 597                                font_id: style.text.font_id,
 598                                color,
 599                                underline: Default::default(),
 600                            },
 601                        )],
 602                    )));
 603                }
 604            } else {
 605                line_number_layouts.push(None);
 606            }
 607        }
 608
 609        line_number_layouts
 610    }
 611
 612    fn layout_lines(
 613        &mut self,
 614        rows: Range<u32>,
 615        snapshot: &EditorSnapshot,
 616        cx: &LayoutContext,
 617    ) -> Vec<text_layout::Line> {
 618        if rows.start >= rows.end {
 619            return Vec::new();
 620        }
 621
 622        // When the editor is empty and unfocused, then show the placeholder.
 623        if snapshot.is_empty() && !snapshot.is_focused() {
 624            let placeholder_style = self
 625                .style
 626                .placeholder_text
 627                .as_ref()
 628                .unwrap_or_else(|| &self.style.text);
 629            let placeholder_text = snapshot.placeholder_text();
 630            let placeholder_lines = placeholder_text
 631                .as_ref()
 632                .map_or("", AsRef::as_ref)
 633                .split('\n')
 634                .skip(rows.start as usize)
 635                .chain(iter::repeat(""))
 636                .take(rows.len());
 637            return placeholder_lines
 638                .map(|line| {
 639                    cx.text_layout_cache.layout_str(
 640                        line,
 641                        placeholder_style.font_size,
 642                        &[(
 643                            line.len(),
 644                            RunStyle {
 645                                font_id: placeholder_style.font_id,
 646                                color: placeholder_style.color,
 647                                underline: Default::default(),
 648                            },
 649                        )],
 650                    )
 651                })
 652                .collect();
 653        } else {
 654            let style = &self.style;
 655            let chunks = snapshot.chunks(rows.clone(), true).map(|chunk| {
 656                let mut highlight_style = chunk
 657                    .syntax_highlight_id
 658                    .and_then(|id| id.style(&style.syntax));
 659
 660                if let Some(chunk_highlight) = chunk.highlight_style {
 661                    if let Some(highlight_style) = highlight_style.as_mut() {
 662                        highlight_style.highlight(chunk_highlight);
 663                    } else {
 664                        highlight_style = Some(chunk_highlight);
 665                    }
 666                }
 667
 668                let mut diagnostic_highlight = HighlightStyle::default();
 669
 670                if chunk.is_unnecessary {
 671                    diagnostic_highlight.fade_out = Some(style.unnecessary_code_fade);
 672                }
 673
 674                if let Some(severity) = chunk.diagnostic_severity {
 675                    // Omit underlines for HINT/INFO diagnostics on 'unnecessary' code.
 676                    if severity <= DiagnosticSeverity::WARNING || !chunk.is_unnecessary {
 677                        let diagnostic_style = super::diagnostic_style(severity, true, style);
 678                        diagnostic_highlight.underline = Some(Underline {
 679                            color: Some(diagnostic_style.message.text.color),
 680                            thickness: 1.0.into(),
 681                            squiggly: true,
 682                        });
 683                    }
 684                }
 685
 686                if let Some(highlight_style) = highlight_style.as_mut() {
 687                    highlight_style.highlight(diagnostic_highlight);
 688                } else {
 689                    highlight_style = Some(diagnostic_highlight);
 690                }
 691
 692                (chunk.text, highlight_style)
 693            });
 694            layout_highlighted_chunks(
 695                chunks,
 696                &style.text,
 697                &cx.text_layout_cache,
 698                &cx.font_cache,
 699                MAX_LINE_LEN,
 700                rows.len() as usize,
 701            )
 702        }
 703    }
 704
 705    fn layout_blocks(
 706        &mut self,
 707        rows: Range<u32>,
 708        snapshot: &EditorSnapshot,
 709        width: f32,
 710        gutter_padding: f32,
 711        gutter_width: f32,
 712        em_width: f32,
 713        text_x: f32,
 714        line_height: f32,
 715        style: &EditorStyle,
 716        line_layouts: &[text_layout::Line],
 717        cx: &mut LayoutContext,
 718    ) -> Vec<(u32, ElementBox)> {
 719        let scroll_x = snapshot.scroll_position.x();
 720        snapshot
 721            .blocks_in_range(rows.clone())
 722            .map(|(block_row, block)| {
 723                let mut element = match block {
 724                    TransformBlock::Custom(block) => {
 725                        let align_to = block
 726                            .position()
 727                            .to_point(&snapshot.buffer_snapshot)
 728                            .to_display_point(snapshot);
 729                        let anchor_x = text_x
 730                            + if rows.contains(&align_to.row()) {
 731                                line_layouts[(align_to.row() - rows.start) as usize]
 732                                    .x_for_index(align_to.column() as usize)
 733                            } else {
 734                                layout_line(align_to.row(), snapshot, style, cx.text_layout_cache)
 735                                    .x_for_index(align_to.column() as usize)
 736                            };
 737
 738                        block.render(&BlockContext {
 739                            cx,
 740                            anchor_x,
 741                            gutter_padding,
 742                            line_height,
 743                            scroll_x,
 744                            gutter_width,
 745                            em_width,
 746                        })
 747                    }
 748                    TransformBlock::ExcerptHeader {
 749                        buffer,
 750                        starts_new_buffer,
 751                        ..
 752                    } => {
 753                        if *starts_new_buffer {
 754                            let style = &self.style.diagnostic_path_header;
 755                            let font_size =
 756                                (style.text_scale_factor * self.style.text.font_size).round();
 757
 758                            let mut filename = None;
 759                            let mut parent_path = None;
 760                            if let Some(path) = buffer.path() {
 761                                filename =
 762                                    path.file_name().map(|f| f.to_string_lossy().to_string());
 763                                parent_path =
 764                                    path.parent().map(|p| p.to_string_lossy().to_string() + "/");
 765                            }
 766
 767                            Flex::row()
 768                                .with_child(
 769                                    Label::new(
 770                                        filename.unwrap_or_else(|| "untitled".to_string()),
 771                                        style.filename.text.clone().with_font_size(font_size),
 772                                    )
 773                                    .contained()
 774                                    .with_style(style.filename.container)
 775                                    .boxed(),
 776                                )
 777                                .with_children(parent_path.map(|path| {
 778                                    Label::new(
 779                                        path,
 780                                        style.path.text.clone().with_font_size(font_size),
 781                                    )
 782                                    .contained()
 783                                    .with_style(style.path.container)
 784                                    .boxed()
 785                                }))
 786                                .aligned()
 787                                .left()
 788                                .contained()
 789                                .with_style(style.container)
 790                                .with_padding_left(gutter_padding + scroll_x * em_width)
 791                                .expanded()
 792                                .named("path header block")
 793                        } else {
 794                            let text_style = self.style.text.clone();
 795                            Label::new("".to_string(), text_style)
 796                                .contained()
 797                                .with_padding_left(gutter_padding + scroll_x * em_width)
 798                                .named("collapsed context")
 799                        }
 800                    }
 801                };
 802
 803                element.layout(
 804                    SizeConstraint {
 805                        min: Vector2F::zero(),
 806                        max: vec2f(width, block.height() as f32 * line_height),
 807                    },
 808                    cx,
 809                );
 810                (block_row, element)
 811            })
 812            .collect()
 813    }
 814}
 815
 816impl Element for EditorElement {
 817    type LayoutState = LayoutState;
 818    type PaintState = PaintState;
 819
 820    fn layout(
 821        &mut self,
 822        constraint: SizeConstraint,
 823        cx: &mut LayoutContext,
 824    ) -> (Vector2F, Self::LayoutState) {
 825        let mut size = constraint.max;
 826        if size.x().is_infinite() {
 827            unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
 828        }
 829
 830        let snapshot = self.snapshot(cx.app);
 831        let style = self.style.clone();
 832        let line_height = style.text.line_height(cx.font_cache);
 833
 834        let gutter_padding;
 835        let gutter_width;
 836        let gutter_margin;
 837        if snapshot.mode == EditorMode::Full {
 838            gutter_padding = style.text.em_width(cx.font_cache) * style.gutter_padding_factor;
 839            gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
 840            gutter_margin = -style.text.descent(cx.font_cache);
 841        } else {
 842            gutter_padding = 0.0;
 843            gutter_width = 0.0;
 844            gutter_margin = 0.0;
 845        };
 846
 847        let text_width = size.x() - gutter_width;
 848        let em_width = style.text.em_width(cx.font_cache);
 849        let em_advance = style.text.em_advance(cx.font_cache);
 850        let overscroll = vec2f(em_width, 0.);
 851        let snapshot = self.update_view(cx.app, |view, cx| {
 852            let wrap_width = match view.soft_wrap_mode(cx) {
 853                SoftWrap::None => None,
 854                SoftWrap::EditorWidth => {
 855                    Some(text_width - gutter_margin - overscroll.x() - em_width)
 856                }
 857                SoftWrap::Column(column) => Some(column as f32 * em_advance),
 858            };
 859
 860            if view.set_wrap_width(wrap_width, cx) {
 861                view.snapshot(cx)
 862            } else {
 863                snapshot
 864            }
 865        });
 866
 867        let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
 868        if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
 869            size.set_y(
 870                scroll_height
 871                    .min(constraint.max_along(Axis::Vertical))
 872                    .max(constraint.min_along(Axis::Vertical))
 873                    .min(line_height * max_lines as f32),
 874            )
 875        } else if size.y().is_infinite() {
 876            size.set_y(scroll_height);
 877        }
 878        let gutter_size = vec2f(gutter_width, size.y());
 879        let text_size = vec2f(text_width, size.y());
 880
 881        let (autoscroll_horizontally, mut snapshot) = self.update_view(cx.app, |view, cx| {
 882            let autoscroll_horizontally = view.autoscroll_vertically(size.y(), line_height, cx);
 883            let snapshot = view.snapshot(cx);
 884            (autoscroll_horizontally, snapshot)
 885        });
 886
 887        let scroll_position = snapshot.scroll_position();
 888        let start_row = scroll_position.y() as u32;
 889        let scroll_top = scroll_position.y() * line_height;
 890
 891        // Add 1 to ensure selections bleed off screen
 892        let end_row = 1 + cmp::min(
 893            ((scroll_top + size.y()) / line_height).ceil() as u32,
 894            snapshot.max_point().row(),
 895        );
 896
 897        let start_anchor = if start_row == 0 {
 898            Anchor::min()
 899        } else {
 900            snapshot
 901                .buffer_snapshot
 902                .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
 903        };
 904        let end_anchor = if end_row > snapshot.max_point().row() {
 905            Anchor::max()
 906        } else {
 907            snapshot
 908                .buffer_snapshot
 909                .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
 910        };
 911
 912        let mut selections = HashMap::default();
 913        let mut active_rows = BTreeMap::new();
 914        let mut highlighted_rows = None;
 915        let mut highlighted_ranges = Vec::new();
 916        self.update_view(cx.app, |view, cx| {
 917            let display_map = view.display_map.update(cx, |map, cx| map.snapshot(cx));
 918
 919            highlighted_rows = view.highlighted_rows();
 920            highlighted_ranges = view.background_highlights_in_range(
 921                start_anchor.clone()..end_anchor.clone(),
 922                &display_map,
 923            );
 924
 925            if view.show_local_selections {
 926                let local_selections = view.local_selections_in_range(
 927                    start_anchor.clone()..end_anchor.clone(),
 928                    &display_map,
 929                );
 930                for selection in &local_selections {
 931                    let is_empty = selection.start == selection.end;
 932                    let selection_start = snapshot.prev_line_boundary(selection.start).1;
 933                    let selection_end = snapshot.next_line_boundary(selection.end).1;
 934                    for row in cmp::max(selection_start.row(), start_row)
 935                        ..=cmp::min(selection_end.row(), end_row)
 936                    {
 937                        let contains_non_empty_selection =
 938                            active_rows.entry(row).or_insert(!is_empty);
 939                        *contains_non_empty_selection |= !is_empty;
 940                    }
 941                }
 942                selections.insert(
 943                    view.replica_id(cx),
 944                    local_selections
 945                        .into_iter()
 946                        .map(|selection| crate::Selection {
 947                            id: selection.id,
 948                            goal: selection.goal,
 949                            reversed: selection.reversed,
 950                            start: selection.start.to_display_point(&display_map),
 951                            end: selection.end.to_display_point(&display_map),
 952                        })
 953                        .collect(),
 954                );
 955            }
 956
 957            for (replica_id, selection) in display_map
 958                .buffer_snapshot
 959                .remote_selections_in_range(&(start_anchor..end_anchor))
 960            {
 961                selections
 962                    .entry(replica_id)
 963                    .or_insert(Vec::new())
 964                    .push(crate::Selection {
 965                        id: selection.id,
 966                        goal: selection.goal,
 967                        reversed: selection.reversed,
 968                        start: selection.start.to_display_point(&display_map),
 969                        end: selection.end.to_display_point(&display_map),
 970                    });
 971            }
 972        });
 973
 974        let line_number_layouts =
 975            self.layout_line_numbers(start_row..end_row, &active_rows, &snapshot, cx);
 976
 977        let mut max_visible_line_width = 0.0;
 978        let line_layouts = self.layout_lines(start_row..end_row, &snapshot, cx);
 979        for line in &line_layouts {
 980            if line.width() > max_visible_line_width {
 981                max_visible_line_width = line.width();
 982            }
 983        }
 984
 985        let style = self.style.clone();
 986        let longest_line_width = layout_line(
 987            snapshot.longest_row(),
 988            &snapshot,
 989            &style,
 990            cx.text_layout_cache,
 991        )
 992        .width();
 993        let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
 994        let em_width = style.text.em_width(cx.font_cache);
 995        let max_row = snapshot.max_point().row();
 996        let scroll_max = vec2f(
 997            ((scroll_width - text_size.x()) / em_width).max(0.0),
 998            max_row.saturating_sub(1) as f32,
 999        );
1000
1001        let mut context_menu = None;
1002        let mut code_actions_indicator = None;
1003        self.update_view(cx.app, |view, cx| {
1004            let clamped = view.clamp_scroll_left(scroll_max.x());
1005            let autoscrolled;
1006            if autoscroll_horizontally {
1007                autoscrolled = view.autoscroll_horizontally(
1008                    start_row,
1009                    text_size.x(),
1010                    scroll_width,
1011                    em_width,
1012                    &line_layouts,
1013                    cx,
1014                );
1015            } else {
1016                autoscrolled = false;
1017            }
1018
1019            if clamped || autoscrolled {
1020                snapshot = view.snapshot(cx);
1021            }
1022
1023            let newest_selection_head = view
1024                .newest_selection_with_snapshot::<usize>(&snapshot.buffer_snapshot)
1025                .head()
1026                .to_display_point(&snapshot);
1027
1028            if (start_row..end_row).contains(&newest_selection_head.row()) {
1029                let style = view.style(cx);
1030                if view.context_menu_visible() {
1031                    context_menu =
1032                        view.render_context_menu(newest_selection_head, style.clone(), cx);
1033                }
1034
1035                code_actions_indicator = view
1036                    .render_code_actions_indicator(&style, cx)
1037                    .map(|indicator| (newest_selection_head.row(), indicator));
1038            }
1039        });
1040
1041        if let Some((_, context_menu)) = context_menu.as_mut() {
1042            context_menu.layout(
1043                SizeConstraint {
1044                    min: Vector2F::zero(),
1045                    max: vec2f(
1046                        f32::INFINITY,
1047                        (12. * line_height).min((size.y() - line_height) / 2.),
1048                    ),
1049                },
1050                cx,
1051            );
1052        }
1053
1054        if let Some((_, indicator)) = code_actions_indicator.as_mut() {
1055            indicator.layout(
1056                SizeConstraint::strict_along(Axis::Vertical, line_height * 0.618),
1057                cx,
1058            );
1059        }
1060
1061        let blocks = self.layout_blocks(
1062            start_row..end_row,
1063            &snapshot,
1064            size.x().max(scroll_width + gutter_width),
1065            gutter_padding,
1066            gutter_width,
1067            em_width,
1068            gutter_width + gutter_margin,
1069            line_height,
1070            &style,
1071            &line_layouts,
1072            cx,
1073        );
1074
1075        (
1076            size,
1077            LayoutState {
1078                size,
1079                scroll_max,
1080                gutter_size,
1081                gutter_padding,
1082                text_size,
1083                gutter_margin,
1084                snapshot,
1085                active_rows,
1086                highlighted_rows,
1087                highlighted_ranges,
1088                line_layouts,
1089                line_number_layouts,
1090                blocks,
1091                line_height,
1092                em_width,
1093                em_advance,
1094                selections,
1095                context_menu,
1096                code_actions_indicator,
1097            },
1098        )
1099    }
1100
1101    fn paint(
1102        &mut self,
1103        bounds: RectF,
1104        visible_bounds: RectF,
1105        layout: &mut Self::LayoutState,
1106        cx: &mut PaintContext,
1107    ) -> Self::PaintState {
1108        cx.scene.push_layer(Some(bounds));
1109
1110        let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
1111        let text_bounds = RectF::new(
1112            bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
1113            layout.text_size,
1114        );
1115
1116        self.paint_background(gutter_bounds, text_bounds, layout, cx);
1117        if layout.gutter_size.x() > 0. {
1118            self.paint_gutter(gutter_bounds, visible_bounds, layout, cx);
1119        }
1120        self.paint_text(text_bounds, visible_bounds, layout, cx);
1121
1122        if !layout.blocks.is_empty() {
1123            cx.scene.push_layer(Some(bounds));
1124            self.paint_blocks(bounds, visible_bounds, layout, cx);
1125            cx.scene.pop_layer();
1126        }
1127
1128        cx.scene.pop_layer();
1129
1130        PaintState {
1131            bounds,
1132            gutter_bounds,
1133            text_bounds,
1134        }
1135    }
1136
1137    fn dispatch_event(
1138        &mut self,
1139        event: &Event,
1140        _: RectF,
1141        layout: &mut LayoutState,
1142        paint: &mut PaintState,
1143        cx: &mut EventContext,
1144    ) -> bool {
1145        if let Some((_, context_menu)) = &mut layout.context_menu {
1146            if context_menu.dispatch_event(event, cx) {
1147                return true;
1148            }
1149        }
1150
1151        if let Some((_, indicator)) = &mut layout.code_actions_indicator {
1152            if indicator.dispatch_event(event, cx) {
1153                return true;
1154            }
1155        }
1156
1157        for (_, block) in &mut layout.blocks {
1158            if block.dispatch_event(event, cx) {
1159                return true;
1160            }
1161        }
1162
1163        match event {
1164            Event::LeftMouseDown {
1165                position,
1166                alt,
1167                shift,
1168                click_count,
1169                ..
1170            } => self.mouse_down(*position, *alt, *shift, *click_count, layout, paint, cx),
1171            Event::LeftMouseUp { position } => self.mouse_up(*position, cx),
1172            Event::LeftMouseDragged { position } => {
1173                self.mouse_dragged(*position, layout, paint, cx)
1174            }
1175            Event::ScrollWheel {
1176                position,
1177                delta,
1178                precise,
1179            } => self.scroll(*position, *delta, *precise, layout, paint, cx),
1180            Event::KeyDown { input, .. } => self.key_down(input.as_deref(), cx),
1181            _ => false,
1182        }
1183    }
1184
1185    fn debug(
1186        &self,
1187        bounds: RectF,
1188        _: &Self::LayoutState,
1189        _: &Self::PaintState,
1190        _: &gpui::DebugContext,
1191    ) -> json::Value {
1192        json!({
1193            "type": "BufferElement",
1194            "bounds": bounds.to_json()
1195        })
1196    }
1197}
1198
1199pub struct LayoutState {
1200    size: Vector2F,
1201    scroll_max: Vector2F,
1202    gutter_size: Vector2F,
1203    gutter_padding: f32,
1204    gutter_margin: f32,
1205    text_size: Vector2F,
1206    snapshot: EditorSnapshot,
1207    active_rows: BTreeMap<u32, bool>,
1208    highlighted_rows: Option<Range<u32>>,
1209    line_layouts: Vec<text_layout::Line>,
1210    line_number_layouts: Vec<Option<text_layout::Line>>,
1211    blocks: Vec<(u32, ElementBox)>,
1212    line_height: f32,
1213    em_width: f32,
1214    em_advance: f32,
1215    highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
1216    selections: HashMap<ReplicaId, Vec<text::Selection<DisplayPoint>>>,
1217    context_menu: Option<(DisplayPoint, ElementBox)>,
1218    code_actions_indicator: Option<(u32, ElementBox)>,
1219}
1220
1221fn layout_line(
1222    row: u32,
1223    snapshot: &EditorSnapshot,
1224    style: &EditorStyle,
1225    layout_cache: &TextLayoutCache,
1226) -> text_layout::Line {
1227    let mut line = snapshot.line(row);
1228
1229    if line.len() > MAX_LINE_LEN {
1230        let mut len = MAX_LINE_LEN;
1231        while !line.is_char_boundary(len) {
1232            len -= 1;
1233        }
1234
1235        line.truncate(len);
1236    }
1237
1238    layout_cache.layout_str(
1239        &line,
1240        style.text.font_size,
1241        &[(
1242            snapshot.line_len(row) as usize,
1243            RunStyle {
1244                font_id: style.text.font_id,
1245                color: Color::black(),
1246                underline: Default::default(),
1247            },
1248        )],
1249    )
1250}
1251
1252pub struct PaintState {
1253    bounds: RectF,
1254    gutter_bounds: RectF,
1255    text_bounds: RectF,
1256}
1257
1258impl PaintState {
1259    fn point_for_position(
1260        &self,
1261        snapshot: &EditorSnapshot,
1262        layout: &LayoutState,
1263        position: Vector2F,
1264    ) -> (DisplayPoint, u32) {
1265        let scroll_position = snapshot.scroll_position();
1266        let position = position - self.text_bounds.origin();
1267        let y = position.y().max(0.0).min(layout.size.y());
1268        let row = ((y / layout.line_height) + scroll_position.y()) as u32;
1269        let row = cmp::min(row, snapshot.max_point().row());
1270        let line = &layout.line_layouts[(row - scroll_position.y() as u32) as usize];
1271        let x = position.x() + (scroll_position.x() * layout.em_width);
1272
1273        let column = if x >= 0.0 {
1274            line.index_for_x(x)
1275                .map(|ix| ix as u32)
1276                .unwrap_or_else(|| snapshot.line_len(row))
1277        } else {
1278            0
1279        };
1280        let overshoot = (0f32.max(x - line.width()) / layout.em_advance) as u32;
1281
1282        (DisplayPoint::new(row, column), overshoot)
1283    }
1284}
1285
1286#[derive(Copy, Clone)]
1287pub enum CursorShape {
1288    Bar,
1289    Block,
1290    Underscore,
1291}
1292
1293impl Default for CursorShape {
1294    fn default() -> Self {
1295        CursorShape::Bar
1296    }
1297}
1298
1299struct Cursor {
1300    origin: Vector2F,
1301    block_width: f32,
1302    line_height: f32,
1303    color: Color,
1304    shape: CursorShape,
1305    block_text: Option<Line>,
1306}
1307
1308impl Cursor {
1309    fn paint(&self, cx: &mut PaintContext) {
1310        let bounds = match self.shape {
1311            CursorShape::Bar => RectF::new(self.origin, vec2f(2.0, self.line_height)),
1312            CursorShape::Block => {
1313                RectF::new(self.origin, vec2f(self.block_width, self.line_height))
1314            }
1315            CursorShape::Underscore => RectF::new(
1316                self.origin + Vector2F::new(0.0, self.line_height - 2.0),
1317                vec2f(self.block_width, 2.0),
1318            ),
1319        };
1320
1321        cx.scene.push_quad(Quad {
1322            bounds,
1323            background: Some(self.color),
1324            border: Border::new(0., Color::black()),
1325            corner_radius: 0.,
1326        });
1327
1328        if let Some(block_text) = &self.block_text {
1329            block_text.paint(self.origin, bounds, self.line_height, cx);
1330        }
1331    }
1332}
1333
1334#[derive(Debug)]
1335struct HighlightedRange {
1336    start_y: f32,
1337    line_height: f32,
1338    lines: Vec<HighlightedRangeLine>,
1339    color: Color,
1340    corner_radius: f32,
1341}
1342
1343#[derive(Debug)]
1344struct HighlightedRangeLine {
1345    start_x: f32,
1346    end_x: f32,
1347}
1348
1349impl HighlightedRange {
1350    fn paint(&self, bounds: RectF, scene: &mut Scene) {
1351        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
1352            self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
1353            self.paint_lines(
1354                self.start_y + self.line_height,
1355                &self.lines[1..],
1356                bounds,
1357                scene,
1358            );
1359        } else {
1360            self.paint_lines(self.start_y, &self.lines, bounds, scene);
1361        }
1362    }
1363
1364    fn paint_lines(
1365        &self,
1366        start_y: f32,
1367        lines: &[HighlightedRangeLine],
1368        bounds: RectF,
1369        scene: &mut Scene,
1370    ) {
1371        if lines.is_empty() {
1372            return;
1373        }
1374
1375        let mut path = PathBuilder::new();
1376        let first_line = lines.first().unwrap();
1377        let last_line = lines.last().unwrap();
1378
1379        let first_top_left = vec2f(first_line.start_x, start_y);
1380        let first_top_right = vec2f(first_line.end_x, start_y);
1381
1382        let curve_height = vec2f(0., self.corner_radius);
1383        let curve_width = |start_x: f32, end_x: f32| {
1384            let max = (end_x - start_x) / 2.;
1385            let width = if max < self.corner_radius {
1386                max
1387            } else {
1388                self.corner_radius
1389            };
1390
1391            vec2f(width, 0.)
1392        };
1393
1394        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
1395        path.reset(first_top_right - top_curve_width);
1396        path.curve_to(first_top_right + curve_height, first_top_right);
1397
1398        let mut iter = lines.iter().enumerate().peekable();
1399        while let Some((ix, line)) = iter.next() {
1400            let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
1401
1402            if let Some((_, next_line)) = iter.peek() {
1403                let next_top_right = vec2f(next_line.end_x, bottom_right.y());
1404
1405                match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
1406                    Ordering::Equal => {
1407                        path.line_to(bottom_right);
1408                    }
1409                    Ordering::Less => {
1410                        let curve_width = curve_width(next_top_right.x(), bottom_right.x());
1411                        path.line_to(bottom_right - curve_height);
1412                        if self.corner_radius > 0. {
1413                            path.curve_to(bottom_right - curve_width, bottom_right);
1414                        }
1415                        path.line_to(next_top_right + curve_width);
1416                        if self.corner_radius > 0. {
1417                            path.curve_to(next_top_right + curve_height, next_top_right);
1418                        }
1419                    }
1420                    Ordering::Greater => {
1421                        let curve_width = curve_width(bottom_right.x(), next_top_right.x());
1422                        path.line_to(bottom_right - curve_height);
1423                        if self.corner_radius > 0. {
1424                            path.curve_to(bottom_right + curve_width, bottom_right);
1425                        }
1426                        path.line_to(next_top_right - curve_width);
1427                        if self.corner_radius > 0. {
1428                            path.curve_to(next_top_right + curve_height, next_top_right);
1429                        }
1430                    }
1431                }
1432            } else {
1433                let curve_width = curve_width(line.start_x, line.end_x);
1434                path.line_to(bottom_right - curve_height);
1435                if self.corner_radius > 0. {
1436                    path.curve_to(bottom_right - curve_width, bottom_right);
1437                }
1438
1439                let bottom_left = vec2f(line.start_x, bottom_right.y());
1440                path.line_to(bottom_left + curve_width);
1441                if self.corner_radius > 0. {
1442                    path.curve_to(bottom_left - curve_height, bottom_left);
1443                }
1444            }
1445        }
1446
1447        if first_line.start_x > last_line.start_x {
1448            let curve_width = curve_width(last_line.start_x, first_line.start_x);
1449            let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
1450            path.line_to(second_top_left + curve_height);
1451            if self.corner_radius > 0. {
1452                path.curve_to(second_top_left + curve_width, second_top_left);
1453            }
1454            let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
1455            path.line_to(first_bottom_left - curve_width);
1456            if self.corner_radius > 0. {
1457                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
1458            }
1459        }
1460
1461        path.line_to(first_top_left + curve_height);
1462        if self.corner_radius > 0. {
1463            path.curve_to(first_top_left + top_curve_width, first_top_left);
1464        }
1465        path.line_to(first_top_right - top_curve_width);
1466
1467        scene.push_path(path.build(self.color, Some(bounds)));
1468    }
1469}
1470
1471fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
1472    delta.powf(1.5) / 100.0
1473}
1474
1475fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
1476    delta.powf(1.2) / 300.0
1477}
1478
1479#[cfg(test)]
1480mod tests {
1481    use std::sync::Arc;
1482
1483    use super::*;
1484    use crate::{
1485        display_map::{BlockDisposition, BlockProperties},
1486        Editor, MultiBuffer,
1487    };
1488    use util::test::sample_text;
1489    use workspace::Settings;
1490
1491    #[gpui::test]
1492    fn test_layout_line_numbers(cx: &mut gpui::MutableAppContext) {
1493        cx.set_global(Settings::test(cx));
1494        let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
1495        let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1496            Editor::new(EditorMode::Full, buffer, None, None, cx)
1497        });
1498        let element = EditorElement::new(
1499            editor.downgrade(),
1500            editor.read(cx).style(cx),
1501            CursorShape::Bar,
1502        );
1503
1504        let layouts = editor.update(cx, |editor, cx| {
1505            let snapshot = editor.snapshot(cx);
1506            let mut presenter = cx.build_presenter(window_id, 30.);
1507            let mut layout_cx = presenter.build_layout_context(false, cx);
1508            element.layout_line_numbers(0..6, &Default::default(), &snapshot, &mut layout_cx)
1509        });
1510        assert_eq!(layouts.len(), 6);
1511    }
1512
1513    #[gpui::test]
1514    fn test_layout_with_placeholder_text_and_blocks(cx: &mut gpui::MutableAppContext) {
1515        cx.set_global(Settings::test(cx));
1516        let buffer = MultiBuffer::build_simple("", cx);
1517        let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1518            Editor::new(EditorMode::Full, buffer, None, None, cx)
1519        });
1520
1521        editor.update(cx, |editor, cx| {
1522            editor.set_placeholder_text("hello", cx);
1523            editor.insert_blocks(
1524                [BlockProperties {
1525                    disposition: BlockDisposition::Above,
1526                    height: 3,
1527                    position: Anchor::min(),
1528                    render: Arc::new(|_| Empty::new().boxed()),
1529                }],
1530                cx,
1531            );
1532
1533            // Blur the editor so that it displays placeholder text.
1534            cx.blur();
1535        });
1536
1537        let mut element = EditorElement::new(
1538            editor.downgrade(),
1539            editor.read(cx).style(cx),
1540            CursorShape::Bar,
1541        );
1542
1543        let mut scene = Scene::new(1.0);
1544        let mut presenter = cx.build_presenter(window_id, 30.);
1545        let mut layout_cx = presenter.build_layout_context(false, cx);
1546        let (size, mut state) = element.layout(
1547            SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
1548            &mut layout_cx,
1549        );
1550
1551        assert_eq!(state.line_layouts.len(), 4);
1552        assert_eq!(
1553            state
1554                .line_number_layouts
1555                .iter()
1556                .map(Option::is_some)
1557                .collect::<Vec<_>>(),
1558            &[false, false, false, true]
1559        );
1560
1561        // Don't panic.
1562        let bounds = RectF::new(Default::default(), size);
1563        let mut paint_cx = presenter.build_paint_context(&mut scene, cx);
1564        element.paint(bounds, bounds, &mut state, &mut paint_cx);
1565    }
1566}