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 let EditorMode::SingleLine = snapshot.mode {
 879            size.set_y(
 880                line_height
 881                    .min(constraint.max_along(Axis::Vertical))
 882                    .max(constraint.min_along(Axis::Vertical)),
 883            )
 884        } else if size.y().is_infinite() {
 885            size.set_y(scroll_height);
 886        }
 887        let gutter_size = vec2f(gutter_width, size.y());
 888        let text_size = vec2f(text_width, size.y());
 889
 890        let (autoscroll_horizontally, mut snapshot) = self.update_view(cx.app, |view, cx| {
 891            let autoscroll_horizontally = view.autoscroll_vertically(size.y(), line_height, cx);
 892            let snapshot = view.snapshot(cx);
 893            (autoscroll_horizontally, snapshot)
 894        });
 895
 896        let scroll_position = snapshot.scroll_position();
 897        let start_row = scroll_position.y() as u32;
 898        let scroll_top = scroll_position.y() * line_height;
 899
 900        // Add 1 to ensure selections bleed off screen
 901        let end_row = 1 + cmp::min(
 902            ((scroll_top + size.y()) / line_height).ceil() as u32,
 903            snapshot.max_point().row(),
 904        );
 905
 906        let start_anchor = if start_row == 0 {
 907            Anchor::min()
 908        } else {
 909            snapshot
 910                .buffer_snapshot
 911                .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
 912        };
 913        let end_anchor = if end_row > snapshot.max_point().row() {
 914            Anchor::max()
 915        } else {
 916            snapshot
 917                .buffer_snapshot
 918                .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
 919        };
 920
 921        let mut selections = Vec::new();
 922        let mut active_rows = BTreeMap::new();
 923        let mut highlighted_rows = None;
 924        let mut highlighted_ranges = Vec::new();
 925        self.update_view(cx.app, |view, cx| {
 926            let display_map = view.display_map.update(cx, |map, cx| map.snapshot(cx));
 927
 928            highlighted_rows = view.highlighted_rows();
 929            let theme = cx.global::<Settings>().theme.as_ref();
 930            highlighted_ranges = view.background_highlights_in_range(
 931                start_anchor.clone()..end_anchor.clone(),
 932                &display_map,
 933                theme,
 934            );
 935
 936            let mut remote_selections = HashMap::default();
 937            for (replica_id, selection) in display_map
 938                .buffer_snapshot
 939                .remote_selections_in_range(&(start_anchor.clone()..end_anchor.clone()))
 940            {
 941                // The local selections match the leader's selections.
 942                if Some(replica_id) == view.leader_replica_id {
 943                    continue;
 944                }
 945
 946                remote_selections
 947                    .entry(replica_id)
 948                    .or_insert(Vec::new())
 949                    .push(crate::Selection {
 950                        id: selection.id,
 951                        goal: selection.goal,
 952                        reversed: selection.reversed,
 953                        start: selection.start.to_display_point(&display_map),
 954                        end: selection.end.to_display_point(&display_map),
 955                    });
 956            }
 957            selections.extend(remote_selections);
 958
 959            if view.show_local_selections {
 960                let mut local_selections = view
 961                    .selections
 962                    .disjoint_in_range(start_anchor..end_anchor, cx);
 963                local_selections.extend(view.selections.pending(cx));
 964                for selection in &local_selections {
 965                    let is_empty = selection.start == selection.end;
 966                    let selection_start = snapshot.prev_line_boundary(selection.start).1;
 967                    let selection_end = snapshot.next_line_boundary(selection.end).1;
 968                    for row in cmp::max(selection_start.row(), start_row)
 969                        ..=cmp::min(selection_end.row(), end_row)
 970                    {
 971                        let contains_non_empty_selection =
 972                            active_rows.entry(row).or_insert(!is_empty);
 973                        *contains_non_empty_selection |= !is_empty;
 974                    }
 975                }
 976
 977                // Render the local selections in the leader's color when following.
 978                let local_replica_id = view.leader_replica_id.unwrap_or(view.replica_id(cx));
 979
 980                selections.push((
 981                    local_replica_id,
 982                    local_selections
 983                        .into_iter()
 984                        .map(|selection| crate::Selection {
 985                            id: selection.id,
 986                            goal: selection.goal,
 987                            reversed: selection.reversed,
 988                            start: selection.start.to_display_point(&display_map),
 989                            end: selection.end.to_display_point(&display_map),
 990                        })
 991                        .collect(),
 992                ));
 993            }
 994        });
 995
 996        let line_number_layouts =
 997            self.layout_line_numbers(start_row..end_row, &active_rows, &snapshot, cx);
 998
 999        let mut max_visible_line_width = 0.0;
1000        let line_layouts = self.layout_lines(start_row..end_row, &snapshot, cx);
1001        for line in &line_layouts {
1002            if line.width() > max_visible_line_width {
1003                max_visible_line_width = line.width();
1004            }
1005        }
1006
1007        let style = self.style.clone();
1008        let longest_line_width = layout_line(
1009            snapshot.longest_row(),
1010            &snapshot,
1011            &style,
1012            cx.text_layout_cache,
1013        )
1014        .width();
1015        let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
1016        let em_width = style.text.em_width(cx.font_cache);
1017        let max_row = snapshot.max_point().row();
1018        let scroll_max = vec2f(
1019            ((scroll_width - text_size.x()) / em_width).max(0.0),
1020            max_row.saturating_sub(1) as f32,
1021        );
1022
1023        let mut context_menu = None;
1024        let mut code_actions_indicator = None;
1025        self.update_view(cx.app, |view, cx| {
1026            let clamped = view.clamp_scroll_left(scroll_max.x());
1027            let autoscrolled;
1028            if autoscroll_horizontally {
1029                autoscrolled = view.autoscroll_horizontally(
1030                    start_row,
1031                    text_size.x(),
1032                    scroll_width,
1033                    em_width,
1034                    &line_layouts,
1035                    cx,
1036                );
1037            } else {
1038                autoscrolled = false;
1039            }
1040
1041            if clamped || autoscrolled {
1042                snapshot = view.snapshot(cx);
1043            }
1044
1045            let newest_selection_head = view
1046                .selections
1047                .newest::<usize>(cx)
1048                .head()
1049                .to_display_point(&snapshot);
1050
1051            if (start_row..end_row).contains(&newest_selection_head.row()) {
1052                let style = view.style(cx);
1053                if view.context_menu_visible() {
1054                    context_menu =
1055                        view.render_context_menu(newest_selection_head, style.clone(), cx);
1056                }
1057
1058                code_actions_indicator = view
1059                    .render_code_actions_indicator(&style, cx)
1060                    .map(|indicator| (newest_selection_head.row(), indicator));
1061            }
1062        });
1063
1064        if let Some((_, context_menu)) = context_menu.as_mut() {
1065            context_menu.layout(
1066                SizeConstraint {
1067                    min: Vector2F::zero(),
1068                    max: vec2f(
1069                        f32::INFINITY,
1070                        (12. * line_height).min((size.y() - line_height) / 2.),
1071                    ),
1072                },
1073                cx,
1074            );
1075        }
1076
1077        if let Some((_, indicator)) = code_actions_indicator.as_mut() {
1078            indicator.layout(
1079                SizeConstraint::strict_along(Axis::Vertical, line_height * 0.618),
1080                cx,
1081            );
1082        }
1083
1084        let blocks = self.layout_blocks(
1085            start_row..end_row,
1086            &snapshot,
1087            size.x().max(scroll_width + gutter_width),
1088            gutter_padding,
1089            gutter_width,
1090            em_width,
1091            gutter_width + gutter_margin,
1092            line_height,
1093            &style,
1094            &line_layouts,
1095            cx,
1096        );
1097
1098        (
1099            size,
1100            LayoutState {
1101                size,
1102                scroll_max,
1103                gutter_size,
1104                gutter_padding,
1105                text_size,
1106                gutter_margin,
1107                snapshot,
1108                active_rows,
1109                highlighted_rows,
1110                highlighted_ranges,
1111                line_layouts,
1112                line_number_layouts,
1113                blocks,
1114                line_height,
1115                em_width,
1116                em_advance,
1117                selections,
1118                context_menu,
1119                code_actions_indicator,
1120            },
1121        )
1122    }
1123
1124    fn paint(
1125        &mut self,
1126        bounds: RectF,
1127        visible_bounds: RectF,
1128        layout: &mut Self::LayoutState,
1129        cx: &mut PaintContext,
1130    ) -> Self::PaintState {
1131        cx.scene.push_layer(Some(bounds));
1132
1133        let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
1134        let text_bounds = RectF::new(
1135            bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
1136            layout.text_size,
1137        );
1138
1139        self.paint_background(gutter_bounds, text_bounds, layout, cx);
1140        if layout.gutter_size.x() > 0. {
1141            self.paint_gutter(gutter_bounds, visible_bounds, layout, cx);
1142        }
1143        self.paint_text(text_bounds, visible_bounds, layout, cx);
1144
1145        if !layout.blocks.is_empty() {
1146            cx.scene.push_layer(Some(bounds));
1147            self.paint_blocks(bounds, visible_bounds, layout, cx);
1148            cx.scene.pop_layer();
1149        }
1150
1151        cx.scene.pop_layer();
1152
1153        PaintState {
1154            bounds,
1155            gutter_bounds,
1156            text_bounds,
1157        }
1158    }
1159
1160    fn dispatch_event(
1161        &mut self,
1162        event: &Event,
1163        _: RectF,
1164        _: RectF,
1165        layout: &mut LayoutState,
1166        paint: &mut PaintState,
1167        cx: &mut EventContext,
1168    ) -> bool {
1169        if let Some((_, context_menu)) = &mut layout.context_menu {
1170            if context_menu.dispatch_event(event, cx) {
1171                return true;
1172            }
1173        }
1174
1175        if let Some((_, indicator)) = &mut layout.code_actions_indicator {
1176            if indicator.dispatch_event(event, cx) {
1177                return true;
1178            }
1179        }
1180
1181        for (_, block) in &mut layout.blocks {
1182            if block.dispatch_event(event, cx) {
1183                return true;
1184            }
1185        }
1186
1187        match event {
1188            Event::LeftMouseDown {
1189                position,
1190                alt,
1191                shift,
1192                click_count,
1193                ..
1194            } => self.mouse_down(*position, *alt, *shift, *click_count, layout, paint, cx),
1195            Event::LeftMouseUp { position, .. } => self.mouse_up(*position, cx),
1196            Event::LeftMouseDragged { position } => {
1197                self.mouse_dragged(*position, layout, paint, cx)
1198            }
1199            Event::ScrollWheel {
1200                position,
1201                delta,
1202                precise,
1203            } => self.scroll(*position, *delta, *precise, layout, paint, cx),
1204            Event::KeyDown { input, .. } => self.key_down(input.as_deref(), cx),
1205            _ => false,
1206        }
1207    }
1208
1209    fn debug(
1210        &self,
1211        bounds: RectF,
1212        _: &Self::LayoutState,
1213        _: &Self::PaintState,
1214        _: &gpui::DebugContext,
1215    ) -> json::Value {
1216        json!({
1217            "type": "BufferElement",
1218            "bounds": bounds.to_json()
1219        })
1220    }
1221}
1222
1223pub struct LayoutState {
1224    size: Vector2F,
1225    scroll_max: Vector2F,
1226    gutter_size: Vector2F,
1227    gutter_padding: f32,
1228    gutter_margin: f32,
1229    text_size: Vector2F,
1230    snapshot: EditorSnapshot,
1231    active_rows: BTreeMap<u32, bool>,
1232    highlighted_rows: Option<Range<u32>>,
1233    line_layouts: Vec<text_layout::Line>,
1234    line_number_layouts: Vec<Option<text_layout::Line>>,
1235    blocks: Vec<(u32, ElementBox)>,
1236    line_height: f32,
1237    em_width: f32,
1238    em_advance: f32,
1239    highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
1240    selections: Vec<(ReplicaId, Vec<text::Selection<DisplayPoint>>)>,
1241    context_menu: Option<(DisplayPoint, ElementBox)>,
1242    code_actions_indicator: Option<(u32, ElementBox)>,
1243}
1244
1245fn layout_line(
1246    row: u32,
1247    snapshot: &EditorSnapshot,
1248    style: &EditorStyle,
1249    layout_cache: &TextLayoutCache,
1250) -> text_layout::Line {
1251    let mut line = snapshot.line(row);
1252
1253    if line.len() > MAX_LINE_LEN {
1254        let mut len = MAX_LINE_LEN;
1255        while !line.is_char_boundary(len) {
1256            len -= 1;
1257        }
1258
1259        line.truncate(len);
1260    }
1261
1262    layout_cache.layout_str(
1263        &line,
1264        style.text.font_size,
1265        &[(
1266            snapshot.line_len(row) as usize,
1267            RunStyle {
1268                font_id: style.text.font_id,
1269                color: Color::black(),
1270                underline: Default::default(),
1271            },
1272        )],
1273    )
1274}
1275
1276pub struct PaintState {
1277    bounds: RectF,
1278    gutter_bounds: RectF,
1279    text_bounds: RectF,
1280}
1281
1282impl PaintState {
1283    fn point_for_position(
1284        &self,
1285        snapshot: &EditorSnapshot,
1286        layout: &LayoutState,
1287        position: Vector2F,
1288    ) -> (DisplayPoint, u32) {
1289        let scroll_position = snapshot.scroll_position();
1290        let position = position - self.text_bounds.origin();
1291        let y = position.y().max(0.0).min(layout.size.y());
1292        let row = ((y / layout.line_height) + scroll_position.y()) as u32;
1293        let row = cmp::min(row, snapshot.max_point().row());
1294        let line = &layout.line_layouts[(row - scroll_position.y() as u32) as usize];
1295        let x = position.x() + (scroll_position.x() * layout.em_width);
1296
1297        let column = if x >= 0.0 {
1298            line.index_for_x(x)
1299                .map(|ix| ix as u32)
1300                .unwrap_or_else(|| snapshot.line_len(row))
1301        } else {
1302            0
1303        };
1304        let overshoot = (0f32.max(x - line.width()) / layout.em_advance) as u32;
1305
1306        (DisplayPoint::new(row, column), overshoot)
1307    }
1308}
1309
1310#[derive(Copy, Clone, PartialEq, Eq)]
1311pub enum CursorShape {
1312    Bar,
1313    Block,
1314    Underscore,
1315}
1316
1317impl Default for CursorShape {
1318    fn default() -> Self {
1319        CursorShape::Bar
1320    }
1321}
1322
1323struct Cursor {
1324    origin: Vector2F,
1325    block_width: f32,
1326    line_height: f32,
1327    color: Color,
1328    shape: CursorShape,
1329    block_text: Option<Line>,
1330}
1331
1332impl Cursor {
1333    fn paint(&self, cx: &mut PaintContext) {
1334        let bounds = match self.shape {
1335            CursorShape::Bar => RectF::new(self.origin, vec2f(2.0, self.line_height)),
1336            CursorShape::Block => {
1337                RectF::new(self.origin, vec2f(self.block_width, self.line_height))
1338            }
1339            CursorShape::Underscore => RectF::new(
1340                self.origin + Vector2F::new(0.0, self.line_height - 2.0),
1341                vec2f(self.block_width, 2.0),
1342            ),
1343        };
1344
1345        cx.scene.push_quad(Quad {
1346            bounds,
1347            background: Some(self.color),
1348            border: Border::new(0., Color::black()),
1349            corner_radius: 0.,
1350        });
1351
1352        if let Some(block_text) = &self.block_text {
1353            block_text.paint(self.origin, bounds, self.line_height, cx);
1354        }
1355    }
1356}
1357
1358#[derive(Debug)]
1359struct HighlightedRange {
1360    start_y: f32,
1361    line_height: f32,
1362    lines: Vec<HighlightedRangeLine>,
1363    color: Color,
1364    corner_radius: f32,
1365}
1366
1367#[derive(Debug)]
1368struct HighlightedRangeLine {
1369    start_x: f32,
1370    end_x: f32,
1371}
1372
1373impl HighlightedRange {
1374    fn paint(&self, bounds: RectF, scene: &mut Scene) {
1375        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
1376            self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
1377            self.paint_lines(
1378                self.start_y + self.line_height,
1379                &self.lines[1..],
1380                bounds,
1381                scene,
1382            );
1383        } else {
1384            self.paint_lines(self.start_y, &self.lines, bounds, scene);
1385        }
1386    }
1387
1388    fn paint_lines(
1389        &self,
1390        start_y: f32,
1391        lines: &[HighlightedRangeLine],
1392        bounds: RectF,
1393        scene: &mut Scene,
1394    ) {
1395        if lines.is_empty() {
1396            return;
1397        }
1398
1399        let mut path = PathBuilder::new();
1400        let first_line = lines.first().unwrap();
1401        let last_line = lines.last().unwrap();
1402
1403        let first_top_left = vec2f(first_line.start_x, start_y);
1404        let first_top_right = vec2f(first_line.end_x, start_y);
1405
1406        let curve_height = vec2f(0., self.corner_radius);
1407        let curve_width = |start_x: f32, end_x: f32| {
1408            let max = (end_x - start_x) / 2.;
1409            let width = if max < self.corner_radius {
1410                max
1411            } else {
1412                self.corner_radius
1413            };
1414
1415            vec2f(width, 0.)
1416        };
1417
1418        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
1419        path.reset(first_top_right - top_curve_width);
1420        path.curve_to(first_top_right + curve_height, first_top_right);
1421
1422        let mut iter = lines.iter().enumerate().peekable();
1423        while let Some((ix, line)) = iter.next() {
1424            let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
1425
1426            if let Some((_, next_line)) = iter.peek() {
1427                let next_top_right = vec2f(next_line.end_x, bottom_right.y());
1428
1429                match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
1430                    Ordering::Equal => {
1431                        path.line_to(bottom_right);
1432                    }
1433                    Ordering::Less => {
1434                        let curve_width = curve_width(next_top_right.x(), bottom_right.x());
1435                        path.line_to(bottom_right - curve_height);
1436                        if self.corner_radius > 0. {
1437                            path.curve_to(bottom_right - curve_width, bottom_right);
1438                        }
1439                        path.line_to(next_top_right + curve_width);
1440                        if self.corner_radius > 0. {
1441                            path.curve_to(next_top_right + curve_height, next_top_right);
1442                        }
1443                    }
1444                    Ordering::Greater => {
1445                        let curve_width = curve_width(bottom_right.x(), next_top_right.x());
1446                        path.line_to(bottom_right - curve_height);
1447                        if self.corner_radius > 0. {
1448                            path.curve_to(bottom_right + curve_width, bottom_right);
1449                        }
1450                        path.line_to(next_top_right - curve_width);
1451                        if self.corner_radius > 0. {
1452                            path.curve_to(next_top_right + curve_height, next_top_right);
1453                        }
1454                    }
1455                }
1456            } else {
1457                let curve_width = curve_width(line.start_x, line.end_x);
1458                path.line_to(bottom_right - curve_height);
1459                if self.corner_radius > 0. {
1460                    path.curve_to(bottom_right - curve_width, bottom_right);
1461                }
1462
1463                let bottom_left = vec2f(line.start_x, bottom_right.y());
1464                path.line_to(bottom_left + curve_width);
1465                if self.corner_radius > 0. {
1466                    path.curve_to(bottom_left - curve_height, bottom_left);
1467                }
1468            }
1469        }
1470
1471        if first_line.start_x > last_line.start_x {
1472            let curve_width = curve_width(last_line.start_x, first_line.start_x);
1473            let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
1474            path.line_to(second_top_left + curve_height);
1475            if self.corner_radius > 0. {
1476                path.curve_to(second_top_left + curve_width, second_top_left);
1477            }
1478            let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
1479            path.line_to(first_bottom_left - curve_width);
1480            if self.corner_radius > 0. {
1481                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
1482            }
1483        }
1484
1485        path.line_to(first_top_left + curve_height);
1486        if self.corner_radius > 0. {
1487            path.curve_to(first_top_left + top_curve_width, first_top_left);
1488        }
1489        path.line_to(first_top_right - top_curve_width);
1490
1491        scene.push_path(path.build(self.color, Some(bounds)));
1492    }
1493}
1494
1495fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
1496    delta.powf(1.5) / 100.0
1497}
1498
1499fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
1500    delta.powf(1.2) / 300.0
1501}
1502
1503#[cfg(test)]
1504mod tests {
1505    use std::sync::Arc;
1506
1507    use super::*;
1508    use crate::{
1509        display_map::{BlockDisposition, BlockProperties},
1510        Editor, MultiBuffer,
1511    };
1512    use settings::Settings;
1513    use util::test::sample_text;
1514
1515    #[gpui::test]
1516    fn test_layout_line_numbers(cx: &mut gpui::MutableAppContext) {
1517        cx.set_global(Settings::test(cx));
1518        let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
1519        let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1520            Editor::new(EditorMode::Full, buffer, None, None, None, cx)
1521        });
1522        let element = EditorElement::new(
1523            editor.downgrade(),
1524            editor.read(cx).style(cx),
1525            CursorShape::Bar,
1526        );
1527
1528        let layouts = editor.update(cx, |editor, cx| {
1529            let snapshot = editor.snapshot(cx);
1530            let mut presenter = cx.build_presenter(window_id, 30.);
1531            let mut layout_cx = presenter.build_layout_context(false, cx);
1532            element.layout_line_numbers(0..6, &Default::default(), &snapshot, &mut layout_cx)
1533        });
1534        assert_eq!(layouts.len(), 6);
1535    }
1536
1537    #[gpui::test]
1538    fn test_layout_with_placeholder_text_and_blocks(cx: &mut gpui::MutableAppContext) {
1539        cx.set_global(Settings::test(cx));
1540        let buffer = MultiBuffer::build_simple("", cx);
1541        let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1542            Editor::new(EditorMode::Full, buffer, None, None, None, cx)
1543        });
1544
1545        editor.update(cx, |editor, cx| {
1546            editor.set_placeholder_text("hello", cx);
1547            editor.insert_blocks(
1548                [BlockProperties {
1549                    disposition: BlockDisposition::Above,
1550                    height: 3,
1551                    position: Anchor::min(),
1552                    render: Arc::new(|_| Empty::new().boxed()),
1553                }],
1554                cx,
1555            );
1556
1557            // Blur the editor so that it displays placeholder text.
1558            cx.blur();
1559        });
1560
1561        let mut element = EditorElement::new(
1562            editor.downgrade(),
1563            editor.read(cx).style(cx),
1564            CursorShape::Bar,
1565        );
1566
1567        let mut scene = Scene::new(1.0);
1568        let mut presenter = cx.build_presenter(window_id, 30.);
1569        let mut layout_cx = presenter.build_layout_context(false, cx);
1570        let (size, mut state) = element.layout(
1571            SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
1572            &mut layout_cx,
1573        );
1574
1575        assert_eq!(state.line_layouts.len(), 4);
1576        assert_eq!(
1577            state
1578                .line_number_layouts
1579                .iter()
1580                .map(Option::is_some)
1581                .collect::<Vec<_>>(),
1582            &[false, false, false, true]
1583        );
1584
1585        // Don't panic.
1586        let bounds = RectF::new(Default::default(), size);
1587        let mut paint_cx = presenter.build_paint_context(&mut scene, cx);
1588        element.paint(bounds, bounds, &mut state, &mut paint_cx);
1589    }
1590}