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;
  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: None,
 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: None,
 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: None,
 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: None,
 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                if let Some(severity) = chunk.diagnostic {
 669                    let diagnostic_style = super::diagnostic_style(severity, true, style);
 670                    let diagnostic_highlight = HighlightStyle {
 671                        underline: Some(Underline {
 672                            color: diagnostic_style.message.text.color,
 673                            thickness: 1.0.into(),
 674                            squiggly: true,
 675                        }),
 676                        ..Default::default()
 677                    };
 678
 679                    if let Some(highlight_style) = highlight_style.as_mut() {
 680                        highlight_style.highlight(diagnostic_highlight);
 681                    } else {
 682                        highlight_style = Some(diagnostic_highlight);
 683                    }
 684                }
 685
 686                (chunk.text, highlight_style)
 687            });
 688            layout_highlighted_chunks(
 689                chunks,
 690                &style.text,
 691                &cx.text_layout_cache,
 692                &cx.font_cache,
 693                MAX_LINE_LEN,
 694                rows.len() as usize,
 695            )
 696        }
 697    }
 698
 699    fn layout_blocks(
 700        &mut self,
 701        rows: Range<u32>,
 702        snapshot: &EditorSnapshot,
 703        width: f32,
 704        gutter_padding: f32,
 705        gutter_width: f32,
 706        em_width: f32,
 707        text_x: f32,
 708        line_height: f32,
 709        style: &EditorStyle,
 710        line_layouts: &[text_layout::Line],
 711        cx: &mut LayoutContext,
 712    ) -> Vec<(u32, ElementBox)> {
 713        let scroll_x = snapshot.scroll_position.x();
 714        snapshot
 715            .blocks_in_range(rows.clone())
 716            .map(|(block_row, block)| {
 717                let mut element = match block {
 718                    TransformBlock::Custom(block) => {
 719                        let align_to = block
 720                            .position()
 721                            .to_point(&snapshot.buffer_snapshot)
 722                            .to_display_point(snapshot);
 723                        let anchor_x = text_x
 724                            + if rows.contains(&align_to.row()) {
 725                                line_layouts[(align_to.row() - rows.start) as usize]
 726                                    .x_for_index(align_to.column() as usize)
 727                            } else {
 728                                layout_line(align_to.row(), snapshot, style, cx.text_layout_cache)
 729                                    .x_for_index(align_to.column() as usize)
 730                            };
 731
 732                        block.render(&BlockContext {
 733                            cx,
 734                            anchor_x,
 735                            gutter_padding,
 736                            line_height,
 737                            scroll_x,
 738                            gutter_width,
 739                            em_width,
 740                        })
 741                    }
 742                    TransformBlock::ExcerptHeader {
 743                        buffer,
 744                        starts_new_buffer,
 745                        ..
 746                    } => {
 747                        if *starts_new_buffer {
 748                            let style = &self.style.diagnostic_path_header;
 749                            let font_size =
 750                                (style.text_scale_factor * self.style.text.font_size).round();
 751
 752                            let mut filename = None;
 753                            let mut parent_path = None;
 754                            if let Some(path) = buffer.path() {
 755                                filename =
 756                                    path.file_name().map(|f| f.to_string_lossy().to_string());
 757                                parent_path =
 758                                    path.parent().map(|p| p.to_string_lossy().to_string() + "/");
 759                            }
 760
 761                            Flex::row()
 762                                .with_child(
 763                                    Label::new(
 764                                        filename.unwrap_or_else(|| "untitled".to_string()),
 765                                        style.filename.text.clone().with_font_size(font_size),
 766                                    )
 767                                    .contained()
 768                                    .with_style(style.filename.container)
 769                                    .boxed(),
 770                                )
 771                                .with_children(parent_path.map(|path| {
 772                                    Label::new(
 773                                        path,
 774                                        style.path.text.clone().with_font_size(font_size),
 775                                    )
 776                                    .contained()
 777                                    .with_style(style.path.container)
 778                                    .boxed()
 779                                }))
 780                                .aligned()
 781                                .left()
 782                                .contained()
 783                                .with_style(style.container)
 784                                .with_padding_left(gutter_padding + scroll_x * em_width)
 785                                .expanded()
 786                                .named("path header block")
 787                        } else {
 788                            let text_style = self.style.text.clone();
 789                            Label::new("".to_string(), text_style)
 790                                .contained()
 791                                .with_padding_left(gutter_padding + scroll_x * em_width)
 792                                .named("collapsed context")
 793                        }
 794                    }
 795                };
 796
 797                element.layout(
 798                    SizeConstraint {
 799                        min: Vector2F::zero(),
 800                        max: vec2f(width, block.height() as f32 * line_height),
 801                    },
 802                    cx,
 803                );
 804                (block_row, element)
 805            })
 806            .collect()
 807    }
 808}
 809
 810impl Element for EditorElement {
 811    type LayoutState = LayoutState;
 812    type PaintState = PaintState;
 813
 814    fn layout(
 815        &mut self,
 816        constraint: SizeConstraint,
 817        cx: &mut LayoutContext,
 818    ) -> (Vector2F, Self::LayoutState) {
 819        let mut size = constraint.max;
 820        if size.x().is_infinite() {
 821            unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
 822        }
 823
 824        let snapshot = self.snapshot(cx.app);
 825        let style = self.style.clone();
 826        let line_height = style.text.line_height(cx.font_cache);
 827
 828        let gutter_padding;
 829        let gutter_width;
 830        let gutter_margin;
 831        if snapshot.mode == EditorMode::Full {
 832            gutter_padding = style.text.em_width(cx.font_cache) * style.gutter_padding_factor;
 833            gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
 834            gutter_margin = -style.text.descent(cx.font_cache);
 835        } else {
 836            gutter_padding = 0.0;
 837            gutter_width = 0.0;
 838            gutter_margin = 0.0;
 839        };
 840
 841        let text_width = size.x() - gutter_width;
 842        let em_width = style.text.em_width(cx.font_cache);
 843        let em_advance = style.text.em_advance(cx.font_cache);
 844        let overscroll = vec2f(em_width, 0.);
 845        let snapshot = self.update_view(cx.app, |view, cx| {
 846            let wrap_width = match view.soft_wrap_mode(cx) {
 847                SoftWrap::None => None,
 848                SoftWrap::EditorWidth => {
 849                    Some(text_width - gutter_margin - overscroll.x() - em_width)
 850                }
 851                SoftWrap::Column(column) => Some(column as f32 * em_advance),
 852            };
 853
 854            if view.set_wrap_width(wrap_width, cx) {
 855                view.snapshot(cx)
 856            } else {
 857                snapshot
 858            }
 859        });
 860
 861        let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
 862        if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
 863            size.set_y(
 864                scroll_height
 865                    .min(constraint.max_along(Axis::Vertical))
 866                    .max(constraint.min_along(Axis::Vertical))
 867                    .min(line_height * max_lines as f32),
 868            )
 869        } else if size.y().is_infinite() {
 870            size.set_y(scroll_height);
 871        }
 872        let gutter_size = vec2f(gutter_width, size.y());
 873        let text_size = vec2f(text_width, size.y());
 874
 875        let (autoscroll_horizontally, mut snapshot) = self.update_view(cx.app, |view, cx| {
 876            let autoscroll_horizontally = view.autoscroll_vertically(size.y(), line_height, cx);
 877            let snapshot = view.snapshot(cx);
 878            (autoscroll_horizontally, snapshot)
 879        });
 880
 881        let scroll_position = snapshot.scroll_position();
 882        let start_row = scroll_position.y() as u32;
 883        let scroll_top = scroll_position.y() * line_height;
 884
 885        // Add 1 to ensure selections bleed off screen
 886        let end_row = 1 + cmp::min(
 887            ((scroll_top + size.y()) / line_height).ceil() as u32,
 888            snapshot.max_point().row(),
 889        );
 890
 891        let start_anchor = if start_row == 0 {
 892            Anchor::min()
 893        } else {
 894            snapshot
 895                .buffer_snapshot
 896                .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
 897        };
 898        let end_anchor = if end_row > snapshot.max_point().row() {
 899            Anchor::max()
 900        } else {
 901            snapshot
 902                .buffer_snapshot
 903                .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
 904        };
 905
 906        let mut selections = HashMap::default();
 907        let mut active_rows = BTreeMap::new();
 908        let mut highlighted_rows = None;
 909        let mut highlighted_ranges = Vec::new();
 910        self.update_view(cx.app, |view, cx| {
 911            let display_map = view.display_map.update(cx, |map, cx| map.snapshot(cx));
 912
 913            highlighted_rows = view.highlighted_rows();
 914            highlighted_ranges = view.background_highlights_in_range(
 915                start_anchor.clone()..end_anchor.clone(),
 916                &display_map,
 917            );
 918
 919            if view.show_local_selections {
 920                let local_selections = view.local_selections_in_range(
 921                    start_anchor.clone()..end_anchor.clone(),
 922                    &display_map,
 923                );
 924                for selection in &local_selections {
 925                    let is_empty = selection.start == selection.end;
 926                    let selection_start = snapshot.prev_line_boundary(selection.start).1;
 927                    let selection_end = snapshot.next_line_boundary(selection.end).1;
 928                    for row in cmp::max(selection_start.row(), start_row)
 929                        ..=cmp::min(selection_end.row(), end_row)
 930                    {
 931                        let contains_non_empty_selection =
 932                            active_rows.entry(row).or_insert(!is_empty);
 933                        *contains_non_empty_selection |= !is_empty;
 934                    }
 935                }
 936                selections.insert(
 937                    view.replica_id(cx),
 938                    local_selections
 939                        .into_iter()
 940                        .map(|selection| crate::Selection {
 941                            id: selection.id,
 942                            goal: selection.goal,
 943                            reversed: selection.reversed,
 944                            start: selection.start.to_display_point(&display_map),
 945                            end: selection.end.to_display_point(&display_map),
 946                        })
 947                        .collect(),
 948                );
 949            }
 950
 951            for (replica_id, selection) in display_map
 952                .buffer_snapshot
 953                .remote_selections_in_range(&(start_anchor..end_anchor))
 954            {
 955                selections
 956                    .entry(replica_id)
 957                    .or_insert(Vec::new())
 958                    .push(crate::Selection {
 959                        id: selection.id,
 960                        goal: selection.goal,
 961                        reversed: selection.reversed,
 962                        start: selection.start.to_display_point(&display_map),
 963                        end: selection.end.to_display_point(&display_map),
 964                    });
 965            }
 966        });
 967
 968        let line_number_layouts =
 969            self.layout_line_numbers(start_row..end_row, &active_rows, &snapshot, cx);
 970
 971        let mut max_visible_line_width = 0.0;
 972        let line_layouts = self.layout_lines(start_row..end_row, &snapshot, cx);
 973        for line in &line_layouts {
 974            if line.width() > max_visible_line_width {
 975                max_visible_line_width = line.width();
 976            }
 977        }
 978
 979        let style = self.style.clone();
 980        let longest_line_width = layout_line(
 981            snapshot.longest_row(),
 982            &snapshot,
 983            &style,
 984            cx.text_layout_cache,
 985        )
 986        .width();
 987        let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
 988        let em_width = style.text.em_width(cx.font_cache);
 989        let max_row = snapshot.max_point().row();
 990        let scroll_max = vec2f(
 991            ((scroll_width - text_size.x()) / em_width).max(0.0),
 992            max_row.saturating_sub(1) as f32,
 993        );
 994
 995        let mut context_menu = None;
 996        let mut code_actions_indicator = None;
 997        self.update_view(cx.app, |view, cx| {
 998            let clamped = view.clamp_scroll_left(scroll_max.x());
 999            let autoscrolled;
1000            if autoscroll_horizontally {
1001                autoscrolled = view.autoscroll_horizontally(
1002                    start_row,
1003                    text_size.x(),
1004                    scroll_width,
1005                    em_width,
1006                    &line_layouts,
1007                    cx,
1008                );
1009            } else {
1010                autoscrolled = false;
1011            }
1012
1013            if clamped || autoscrolled {
1014                snapshot = view.snapshot(cx);
1015            }
1016
1017            let newest_selection_head = view
1018                .newest_selection_with_snapshot::<usize>(&snapshot.buffer_snapshot)
1019                .head()
1020                .to_display_point(&snapshot);
1021
1022            if (start_row..end_row).contains(&newest_selection_head.row()) {
1023                let style = view.style(cx);
1024                if view.context_menu_visible() {
1025                    context_menu =
1026                        view.render_context_menu(newest_selection_head, style.clone(), cx);
1027                }
1028
1029                code_actions_indicator = view
1030                    .render_code_actions_indicator(&style, cx)
1031                    .map(|indicator| (newest_selection_head.row(), indicator));
1032            }
1033        });
1034
1035        if let Some((_, context_menu)) = context_menu.as_mut() {
1036            context_menu.layout(
1037                SizeConstraint {
1038                    min: Vector2F::zero(),
1039                    max: vec2f(
1040                        f32::INFINITY,
1041                        (12. * line_height).min((size.y() - line_height) / 2.),
1042                    ),
1043                },
1044                cx,
1045            );
1046        }
1047
1048        if let Some((_, indicator)) = code_actions_indicator.as_mut() {
1049            indicator.layout(
1050                SizeConstraint::strict_along(Axis::Vertical, line_height * 0.618),
1051                cx,
1052            );
1053        }
1054
1055        let blocks = self.layout_blocks(
1056            start_row..end_row,
1057            &snapshot,
1058            size.x().max(scroll_width + gutter_width),
1059            gutter_padding,
1060            gutter_width,
1061            em_width,
1062            gutter_width + gutter_margin,
1063            line_height,
1064            &style,
1065            &line_layouts,
1066            cx,
1067        );
1068
1069        (
1070            size,
1071            LayoutState {
1072                size,
1073                scroll_max,
1074                gutter_size,
1075                gutter_padding,
1076                text_size,
1077                gutter_margin,
1078                snapshot,
1079                active_rows,
1080                highlighted_rows,
1081                highlighted_ranges,
1082                line_layouts,
1083                line_number_layouts,
1084                blocks,
1085                line_height,
1086                em_width,
1087                em_advance,
1088                selections,
1089                context_menu,
1090                code_actions_indicator,
1091            },
1092        )
1093    }
1094
1095    fn paint(
1096        &mut self,
1097        bounds: RectF,
1098        visible_bounds: RectF,
1099        layout: &mut Self::LayoutState,
1100        cx: &mut PaintContext,
1101    ) -> Self::PaintState {
1102        cx.scene.push_layer(Some(bounds));
1103
1104        let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
1105        let text_bounds = RectF::new(
1106            bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
1107            layout.text_size,
1108        );
1109
1110        self.paint_background(gutter_bounds, text_bounds, layout, cx);
1111        if layout.gutter_size.x() > 0. {
1112            self.paint_gutter(gutter_bounds, visible_bounds, layout, cx);
1113        }
1114        self.paint_text(text_bounds, visible_bounds, layout, cx);
1115
1116        if !layout.blocks.is_empty() {
1117            cx.scene.push_layer(Some(bounds));
1118            self.paint_blocks(bounds, visible_bounds, layout, cx);
1119            cx.scene.pop_layer();
1120        }
1121
1122        cx.scene.pop_layer();
1123
1124        PaintState {
1125            bounds,
1126            gutter_bounds,
1127            text_bounds,
1128        }
1129    }
1130
1131    fn dispatch_event(
1132        &mut self,
1133        event: &Event,
1134        _: RectF,
1135        layout: &mut LayoutState,
1136        paint: &mut PaintState,
1137        cx: &mut EventContext,
1138    ) -> bool {
1139        if let Some((_, context_menu)) = &mut layout.context_menu {
1140            if context_menu.dispatch_event(event, cx) {
1141                return true;
1142            }
1143        }
1144
1145        if let Some((_, indicator)) = &mut layout.code_actions_indicator {
1146            if indicator.dispatch_event(event, cx) {
1147                return true;
1148            }
1149        }
1150
1151        for (_, block) in &mut layout.blocks {
1152            if block.dispatch_event(event, cx) {
1153                return true;
1154            }
1155        }
1156
1157        match event {
1158            Event::LeftMouseDown {
1159                position,
1160                alt,
1161                shift,
1162                click_count,
1163                ..
1164            } => self.mouse_down(*position, *alt, *shift, *click_count, layout, paint, cx),
1165            Event::LeftMouseUp { position } => self.mouse_up(*position, cx),
1166            Event::LeftMouseDragged { position } => {
1167                self.mouse_dragged(*position, layout, paint, cx)
1168            }
1169            Event::ScrollWheel {
1170                position,
1171                delta,
1172                precise,
1173            } => self.scroll(*position, *delta, *precise, layout, paint, cx),
1174            Event::KeyDown { input, .. } => self.key_down(input.as_deref(), cx),
1175            _ => false,
1176        }
1177    }
1178
1179    fn debug(
1180        &self,
1181        bounds: RectF,
1182        _: &Self::LayoutState,
1183        _: &Self::PaintState,
1184        _: &gpui::DebugContext,
1185    ) -> json::Value {
1186        json!({
1187            "type": "BufferElement",
1188            "bounds": bounds.to_json()
1189        })
1190    }
1191}
1192
1193pub struct LayoutState {
1194    size: Vector2F,
1195    scroll_max: Vector2F,
1196    gutter_size: Vector2F,
1197    gutter_padding: f32,
1198    gutter_margin: f32,
1199    text_size: Vector2F,
1200    snapshot: EditorSnapshot,
1201    active_rows: BTreeMap<u32, bool>,
1202    highlighted_rows: Option<Range<u32>>,
1203    line_layouts: Vec<text_layout::Line>,
1204    line_number_layouts: Vec<Option<text_layout::Line>>,
1205    blocks: Vec<(u32, ElementBox)>,
1206    line_height: f32,
1207    em_width: f32,
1208    em_advance: f32,
1209    highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
1210    selections: HashMap<ReplicaId, Vec<text::Selection<DisplayPoint>>>,
1211    context_menu: Option<(DisplayPoint, ElementBox)>,
1212    code_actions_indicator: Option<(u32, ElementBox)>,
1213}
1214
1215fn layout_line(
1216    row: u32,
1217    snapshot: &EditorSnapshot,
1218    style: &EditorStyle,
1219    layout_cache: &TextLayoutCache,
1220) -> text_layout::Line {
1221    let mut line = snapshot.line(row);
1222
1223    if line.len() > MAX_LINE_LEN {
1224        let mut len = MAX_LINE_LEN;
1225        while !line.is_char_boundary(len) {
1226            len -= 1;
1227        }
1228
1229        line.truncate(len);
1230    }
1231
1232    layout_cache.layout_str(
1233        &line,
1234        style.text.font_size,
1235        &[(
1236            snapshot.line_len(row) as usize,
1237            RunStyle {
1238                font_id: style.text.font_id,
1239                color: Color::black(),
1240                underline: None,
1241            },
1242        )],
1243    )
1244}
1245
1246pub struct PaintState {
1247    bounds: RectF,
1248    gutter_bounds: RectF,
1249    text_bounds: RectF,
1250}
1251
1252impl PaintState {
1253    fn point_for_position(
1254        &self,
1255        snapshot: &EditorSnapshot,
1256        layout: &LayoutState,
1257        position: Vector2F,
1258    ) -> (DisplayPoint, u32) {
1259        let scroll_position = snapshot.scroll_position();
1260        let position = position - self.text_bounds.origin();
1261        let y = position.y().max(0.0).min(layout.size.y());
1262        let row = ((y / layout.line_height) + scroll_position.y()) as u32;
1263        let row = cmp::min(row, snapshot.max_point().row());
1264        let line = &layout.line_layouts[(row - scroll_position.y() as u32) as usize];
1265        let x = position.x() + (scroll_position.x() * layout.em_width);
1266
1267        let column = if x >= 0.0 {
1268            line.index_for_x(x)
1269                .map(|ix| ix as u32)
1270                .unwrap_or_else(|| snapshot.line_len(row))
1271        } else {
1272            0
1273        };
1274        let overshoot = (0f32.max(x - line.width()) / layout.em_advance) as u32;
1275
1276        (DisplayPoint::new(row, column), overshoot)
1277    }
1278}
1279
1280#[derive(Copy, Clone)]
1281pub enum CursorShape {
1282    Bar,
1283    Block,
1284    Underscore,
1285}
1286
1287impl Default for CursorShape {
1288    fn default() -> Self {
1289        CursorShape::Bar
1290    }
1291}
1292
1293struct Cursor {
1294    origin: Vector2F,
1295    block_width: f32,
1296    line_height: f32,
1297    color: Color,
1298    shape: CursorShape,
1299    block_text: Option<Line>,
1300}
1301
1302impl Cursor {
1303    fn paint(&self, cx: &mut PaintContext) {
1304        let bounds = match self.shape {
1305            CursorShape::Bar => RectF::new(self.origin, vec2f(2.0, self.line_height)),
1306            CursorShape::Block => {
1307                RectF::new(self.origin, vec2f(self.block_width, self.line_height))
1308            }
1309            CursorShape::Underscore => RectF::new(
1310                self.origin + Vector2F::new(0.0, self.line_height - 2.0),
1311                vec2f(self.block_width, 2.0),
1312            ),
1313        };
1314
1315        cx.scene.push_quad(Quad {
1316            bounds,
1317            background: Some(self.color),
1318            border: Border::new(0., Color::black()),
1319            corner_radius: 0.,
1320        });
1321
1322        if let Some(block_text) = &self.block_text {
1323            block_text.paint(self.origin, bounds, self.line_height, cx);
1324        }
1325    }
1326}
1327
1328#[derive(Debug)]
1329struct HighlightedRange {
1330    start_y: f32,
1331    line_height: f32,
1332    lines: Vec<HighlightedRangeLine>,
1333    color: Color,
1334    corner_radius: f32,
1335}
1336
1337#[derive(Debug)]
1338struct HighlightedRangeLine {
1339    start_x: f32,
1340    end_x: f32,
1341}
1342
1343impl HighlightedRange {
1344    fn paint(&self, bounds: RectF, scene: &mut Scene) {
1345        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
1346            self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
1347            self.paint_lines(
1348                self.start_y + self.line_height,
1349                &self.lines[1..],
1350                bounds,
1351                scene,
1352            );
1353        } else {
1354            self.paint_lines(self.start_y, &self.lines, bounds, scene);
1355        }
1356    }
1357
1358    fn paint_lines(
1359        &self,
1360        start_y: f32,
1361        lines: &[HighlightedRangeLine],
1362        bounds: RectF,
1363        scene: &mut Scene,
1364    ) {
1365        if lines.is_empty() {
1366            return;
1367        }
1368
1369        let mut path = PathBuilder::new();
1370        let first_line = lines.first().unwrap();
1371        let last_line = lines.last().unwrap();
1372
1373        let first_top_left = vec2f(first_line.start_x, start_y);
1374        let first_top_right = vec2f(first_line.end_x, start_y);
1375
1376        let curve_height = vec2f(0., self.corner_radius);
1377        let curve_width = |start_x: f32, end_x: f32| {
1378            let max = (end_x - start_x) / 2.;
1379            let width = if max < self.corner_radius {
1380                max
1381            } else {
1382                self.corner_radius
1383            };
1384
1385            vec2f(width, 0.)
1386        };
1387
1388        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
1389        path.reset(first_top_right - top_curve_width);
1390        path.curve_to(first_top_right + curve_height, first_top_right);
1391
1392        let mut iter = lines.iter().enumerate().peekable();
1393        while let Some((ix, line)) = iter.next() {
1394            let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
1395
1396            if let Some((_, next_line)) = iter.peek() {
1397                let next_top_right = vec2f(next_line.end_x, bottom_right.y());
1398
1399                match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
1400                    Ordering::Equal => {
1401                        path.line_to(bottom_right);
1402                    }
1403                    Ordering::Less => {
1404                        let curve_width = curve_width(next_top_right.x(), bottom_right.x());
1405                        path.line_to(bottom_right - curve_height);
1406                        if self.corner_radius > 0. {
1407                            path.curve_to(bottom_right - curve_width, bottom_right);
1408                        }
1409                        path.line_to(next_top_right + curve_width);
1410                        if self.corner_radius > 0. {
1411                            path.curve_to(next_top_right + curve_height, next_top_right);
1412                        }
1413                    }
1414                    Ordering::Greater => {
1415                        let curve_width = curve_width(bottom_right.x(), next_top_right.x());
1416                        path.line_to(bottom_right - curve_height);
1417                        if self.corner_radius > 0. {
1418                            path.curve_to(bottom_right + curve_width, bottom_right);
1419                        }
1420                        path.line_to(next_top_right - curve_width);
1421                        if self.corner_radius > 0. {
1422                            path.curve_to(next_top_right + curve_height, next_top_right);
1423                        }
1424                    }
1425                }
1426            } else {
1427                let curve_width = curve_width(line.start_x, line.end_x);
1428                path.line_to(bottom_right - curve_height);
1429                if self.corner_radius > 0. {
1430                    path.curve_to(bottom_right - curve_width, bottom_right);
1431                }
1432
1433                let bottom_left = vec2f(line.start_x, bottom_right.y());
1434                path.line_to(bottom_left + curve_width);
1435                if self.corner_radius > 0. {
1436                    path.curve_to(bottom_left - curve_height, bottom_left);
1437                }
1438            }
1439        }
1440
1441        if first_line.start_x > last_line.start_x {
1442            let curve_width = curve_width(last_line.start_x, first_line.start_x);
1443            let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
1444            path.line_to(second_top_left + curve_height);
1445            if self.corner_radius > 0. {
1446                path.curve_to(second_top_left + curve_width, second_top_left);
1447            }
1448            let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
1449            path.line_to(first_bottom_left - curve_width);
1450            if self.corner_radius > 0. {
1451                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
1452            }
1453        }
1454
1455        path.line_to(first_top_left + curve_height);
1456        if self.corner_radius > 0. {
1457            path.curve_to(first_top_left + top_curve_width, first_top_left);
1458        }
1459        path.line_to(first_top_right - top_curve_width);
1460
1461        scene.push_path(path.build(self.color, Some(bounds)));
1462    }
1463}
1464
1465fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
1466    delta.powf(1.5) / 100.0
1467}
1468
1469fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
1470    delta.powf(1.2) / 300.0
1471}
1472
1473#[cfg(test)]
1474mod tests {
1475    use std::sync::Arc;
1476
1477    use super::*;
1478    use crate::{
1479        display_map::{BlockDisposition, BlockProperties},
1480        Editor, MultiBuffer,
1481    };
1482    use util::test::sample_text;
1483    use workspace::Settings;
1484
1485    #[gpui::test]
1486    fn test_layout_line_numbers(cx: &mut gpui::MutableAppContext) {
1487        cx.add_app_state(Settings::test(cx));
1488        let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
1489        let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1490            Editor::new(EditorMode::Full, buffer, None, None, cx)
1491        });
1492        let element = EditorElement::new(
1493            editor.downgrade(),
1494            editor.read(cx).style(cx),
1495            CursorShape::Bar,
1496        );
1497
1498        let layouts = editor.update(cx, |editor, cx| {
1499            let snapshot = editor.snapshot(cx);
1500            let mut presenter = cx.build_presenter(window_id, 30.);
1501            let mut layout_cx = presenter.build_layout_context(false, cx);
1502            element.layout_line_numbers(0..6, &Default::default(), &snapshot, &mut layout_cx)
1503        });
1504        assert_eq!(layouts.len(), 6);
1505    }
1506
1507    #[gpui::test]
1508    fn test_layout_with_placeholder_text_and_blocks(cx: &mut gpui::MutableAppContext) {
1509        cx.add_app_state(Settings::test(cx));
1510        let buffer = MultiBuffer::build_simple("", cx);
1511        let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1512            Editor::new(EditorMode::Full, buffer, None, None, cx)
1513        });
1514
1515        editor.update(cx, |editor, cx| {
1516            editor.set_placeholder_text("hello", cx);
1517            editor.insert_blocks(
1518                [BlockProperties {
1519                    disposition: BlockDisposition::Above,
1520                    height: 3,
1521                    position: Anchor::min(),
1522                    render: Arc::new(|_| Empty::new().boxed()),
1523                }],
1524                cx,
1525            );
1526
1527            // Blur the editor so that it displays placeholder text.
1528            cx.blur();
1529        });
1530
1531        let mut element = EditorElement::new(
1532            editor.downgrade(),
1533            editor.read(cx).style(cx),
1534            CursorShape::Bar,
1535        );
1536
1537        let mut scene = Scene::new(1.0);
1538        let mut presenter = cx.build_presenter(window_id, 30.);
1539        let mut layout_cx = presenter.build_layout_context(false, cx);
1540        let (size, mut state) = element.layout(
1541            SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
1542            &mut layout_cx,
1543        );
1544
1545        assert_eq!(state.line_layouts.len(), 4);
1546        assert_eq!(
1547            state
1548                .line_number_layouts
1549                .iter()
1550                .map(Option::is_some)
1551                .collect::<Vec<_>>(),
1552            &[false, false, false, true]
1553        );
1554
1555        // Don't panic.
1556        let bounds = RectF::new(Default::default(), size);
1557        let mut paint_cx = presenter.build_paint_context(&mut scene, cx);
1558        element.paint(bounds, bounds, &mut state, &mut paint_cx);
1559    }
1560}