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