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