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