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