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