element.rs

   1use super::{
   2    display_map::{BlockContext, ToDisplayPoint},
   3    Anchor, DisplayPoint, Editor, EditorMode, EditorSettings, EditorSnapshot, EditorStyle, Input,
   4    Scroll, Select, SelectPhase, SoftWrap, ToPoint, MAX_LINE_LEN,
   5};
   6use clock::ReplicaId;
   7use collections::{BTreeMap, HashMap};
   8use gpui::{
   9    color::Color,
  10    elements::layout_highlighted_chunks,
  11    fonts::{HighlightStyle, Underline},
  12    geometry::{
  13        rect::RectF,
  14        vector::{vec2f, Vector2F},
  15        PathBuilder,
  16    },
  17    json::{self, ToJson},
  18    keymap::Keystroke,
  19    text_layout::{self, RunStyle, TextLayoutCache},
  20    AppContext, Axis, Border, Element, ElementBox, Event, EventContext, LayoutContext,
  21    MutableAppContext, PaintContext, Quad, Scene, SizeConstraint, ViewContext, WeakViewHandle,
  22};
  23use json::json;
  24use language::Bias;
  25use smallvec::SmallVec;
  26use std::{
  27    cmp::{self, Ordering},
  28    fmt::Write,
  29    ops::Range,
  30};
  31
  32pub struct EditorElement {
  33    view: WeakViewHandle<Editor>,
  34    settings: EditorSettings,
  35}
  36
  37impl EditorElement {
  38    pub fn new(view: WeakViewHandle<Editor>, settings: EditorSettings) -> Self {
  39        Self { view, settings }
  40    }
  41
  42    fn view<'a>(&self, cx: &'a AppContext) -> &'a Editor {
  43        self.view.upgrade(cx).unwrap().read(cx)
  44    }
  45
  46    fn update_view<F, T>(&self, cx: &mut MutableAppContext, f: F) -> T
  47    where
  48        F: FnOnce(&mut Editor, &mut ViewContext<Editor>) -> T,
  49    {
  50        self.view.upgrade(cx).unwrap().update(cx, f)
  51    }
  52
  53    fn snapshot(&self, cx: &mut MutableAppContext) -> EditorSnapshot {
  54        self.update_view(cx, |view, cx| view.snapshot(cx))
  55    }
  56
  57    fn mouse_down(
  58        &self,
  59        position: Vector2F,
  60        alt: bool,
  61        shift: bool,
  62        mut click_count: usize,
  63        layout: &mut LayoutState,
  64        paint: &mut PaintState,
  65        cx: &mut EventContext,
  66    ) -> bool {
  67        if paint.gutter_bounds.contains_point(position) {
  68            click_count = 3; // Simulate triple-click when clicking the gutter to select lines
  69        } else if !paint.text_bounds.contains_point(position) {
  70            return false;
  71        }
  72
  73        let snapshot = self.snapshot(cx.app);
  74        let (position, overshoot) = paint.point_for_position(&snapshot, layout, position);
  75
  76        if shift && alt {
  77            cx.dispatch_action(Select(SelectPhase::BeginColumnar {
  78                position,
  79                overshoot,
  80            }));
  81        } else if shift {
  82            cx.dispatch_action(Select(SelectPhase::Extend {
  83                position,
  84                click_count,
  85            }));
  86        } else {
  87            cx.dispatch_action(Select(SelectPhase::Begin {
  88                position,
  89                add: alt,
  90                click_count,
  91            }));
  92        }
  93
  94        true
  95    }
  96
  97    fn mouse_up(&self, _position: Vector2F, cx: &mut EventContext) -> bool {
  98        if self.view(cx.app.as_ref()).is_selecting() {
  99            cx.dispatch_action(Select(SelectPhase::End));
 100            true
 101        } else {
 102            false
 103        }
 104    }
 105
 106    fn mouse_dragged(
 107        &self,
 108        position: Vector2F,
 109        layout: &mut LayoutState,
 110        paint: &mut PaintState,
 111        cx: &mut EventContext,
 112    ) -> bool {
 113        let view = self.view(cx.app.as_ref());
 114
 115        if view.is_selecting() {
 116            let rect = paint.text_bounds;
 117            let mut scroll_delta = Vector2F::zero();
 118
 119            let vertical_margin = layout.line_height.min(rect.height() / 3.0);
 120            let top = rect.origin_y() + vertical_margin;
 121            let bottom = rect.lower_left().y() - vertical_margin;
 122            if position.y() < top {
 123                scroll_delta.set_y(-scale_vertical_mouse_autoscroll_delta(top - position.y()))
 124            }
 125            if position.y() > bottom {
 126                scroll_delta.set_y(scale_vertical_mouse_autoscroll_delta(position.y() - bottom))
 127            }
 128
 129            let horizontal_margin = layout.line_height.min(rect.width() / 3.0);
 130            let left = rect.origin_x() + horizontal_margin;
 131            let right = rect.upper_right().x() - horizontal_margin;
 132            if position.x() < left {
 133                scroll_delta.set_x(-scale_horizontal_mouse_autoscroll_delta(
 134                    left - position.x(),
 135                ))
 136            }
 137            if position.x() > right {
 138                scroll_delta.set_x(scale_horizontal_mouse_autoscroll_delta(
 139                    position.x() - right,
 140                ))
 141            }
 142
 143            let snapshot = self.snapshot(cx.app);
 144            let (position, overshoot) = paint.point_for_position(&snapshot, layout, position);
 145
 146            cx.dispatch_action(Select(SelectPhase::Update {
 147                position,
 148                overshoot,
 149                scroll_position: (snapshot.scroll_position() + scroll_delta)
 150                    .clamp(Vector2F::zero(), layout.scroll_max),
 151            }));
 152            true
 153        } else {
 154            false
 155        }
 156    }
 157
 158    fn key_down(&self, chars: &str, keystroke: &Keystroke, cx: &mut EventContext) -> bool {
 159        let view = self.view.upgrade(cx.app).unwrap();
 160
 161        if view.is_focused(cx.app) {
 162            if chars.is_empty() {
 163                false
 164            } else {
 165                if chars.chars().any(|c| c.is_control()) || keystroke.cmd || keystroke.ctrl {
 166                    false
 167                } else {
 168                    cx.dispatch_action(Input(chars.to_string()));
 169                    true
 170                }
 171            }
 172        } else {
 173            false
 174        }
 175    }
 176
 177    fn scroll(
 178        &self,
 179        position: Vector2F,
 180        mut delta: Vector2F,
 181        precise: bool,
 182        layout: &mut LayoutState,
 183        paint: &mut PaintState,
 184        cx: &mut EventContext,
 185    ) -> bool {
 186        if !paint.bounds.contains_point(position) {
 187            return false;
 188        }
 189
 190        let snapshot = self.snapshot(cx.app);
 191        let max_glyph_width = layout.em_width;
 192        if !precise {
 193            delta *= vec2f(max_glyph_width, layout.line_height);
 194        }
 195
 196        let scroll_position = snapshot.scroll_position();
 197        let x = (scroll_position.x() * max_glyph_width - delta.x()) / max_glyph_width;
 198        let y = (scroll_position.y() * layout.line_height - delta.y()) / layout.line_height;
 199        let scroll_position = vec2f(x, y).clamp(Vector2F::zero(), layout.scroll_max);
 200
 201        cx.dispatch_action(Scroll(scroll_position));
 202
 203        true
 204    }
 205
 206    fn paint_background(
 207        &self,
 208        gutter_bounds: RectF,
 209        text_bounds: RectF,
 210        layout: &LayoutState,
 211        cx: &mut PaintContext,
 212    ) {
 213        let bounds = gutter_bounds.union_rect(text_bounds);
 214        let scroll_top = layout.snapshot.scroll_position().y() * layout.line_height;
 215        let editor = self.view(cx.app);
 216        let style = &self.settings.style;
 217        cx.scene.push_quad(Quad {
 218            bounds: gutter_bounds,
 219            background: Some(style.gutter_background),
 220            border: Border::new(0., Color::transparent_black()),
 221            corner_radius: 0.,
 222        });
 223        cx.scene.push_quad(Quad {
 224            bounds: text_bounds,
 225            background: Some(style.background),
 226            border: Border::new(0., Color::transparent_black()),
 227            corner_radius: 0.,
 228        });
 229
 230        if let EditorMode::Full = editor.mode {
 231            let mut active_rows = layout.active_rows.iter().peekable();
 232            while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
 233                let mut end_row = *start_row;
 234                while active_rows.peek().map_or(false, |r| {
 235                    *r.0 == end_row + 1 && r.1 == contains_non_empty_selection
 236                }) {
 237                    active_rows.next().unwrap();
 238                    end_row += 1;
 239                }
 240
 241                if !contains_non_empty_selection {
 242                    let origin = vec2f(
 243                        bounds.origin_x(),
 244                        bounds.origin_y() + (layout.line_height * *start_row as f32) - scroll_top,
 245                    );
 246                    let size = vec2f(
 247                        bounds.width(),
 248                        layout.line_height * (end_row - start_row + 1) as f32,
 249                    );
 250                    cx.scene.push_quad(Quad {
 251                        bounds: RectF::new(origin, size),
 252                        background: Some(style.active_line_background),
 253                        border: Border::default(),
 254                        corner_radius: 0.,
 255                    });
 256                }
 257            }
 258
 259            if let Some(highlighted_rows) = &layout.highlighted_rows {
 260                let origin = vec2f(
 261                    bounds.origin_x(),
 262                    bounds.origin_y() + (layout.line_height * highlighted_rows.start as f32)
 263                        - scroll_top,
 264                );
 265                let size = vec2f(
 266                    bounds.width(),
 267                    layout.line_height * highlighted_rows.len() as f32,
 268                );
 269                cx.scene.push_quad(Quad {
 270                    bounds: RectF::new(origin, size),
 271                    background: Some(style.highlighted_line_background),
 272                    border: Border::default(),
 273                    corner_radius: 0.,
 274                });
 275            }
 276        }
 277    }
 278
 279    fn paint_gutter(
 280        &mut self,
 281        bounds: RectF,
 282        visible_bounds: RectF,
 283        layout: &LayoutState,
 284        cx: &mut PaintContext,
 285    ) {
 286        let scroll_top = layout.snapshot.scroll_position().y() * layout.line_height;
 287        for (ix, line) in layout.line_number_layouts.iter().enumerate() {
 288            if let Some(line) = line {
 289                let line_origin = bounds.origin()
 290                    + vec2f(
 291                        bounds.width() - line.width() - layout.gutter_padding,
 292                        ix as f32 * layout.line_height - (scroll_top % layout.line_height),
 293                    );
 294                line.paint(line_origin, visible_bounds, layout.line_height, cx);
 295            }
 296        }
 297    }
 298
 299    fn paint_text(
 300        &mut self,
 301        bounds: RectF,
 302        visible_bounds: RectF,
 303        layout: &LayoutState,
 304        cx: &mut PaintContext,
 305    ) {
 306        let view = self.view(cx.app);
 307        let style = &self.settings.style;
 308        let local_replica_id = view.replica_id(cx);
 309        let scroll_position = layout.snapshot.scroll_position();
 310        let start_row = scroll_position.y() as u32;
 311        let scroll_top = scroll_position.y() * layout.line_height;
 312        let end_row = ((scroll_top + bounds.height()) / layout.line_height).ceil() as u32 + 1; // Add 1 to ensure selections bleed off screen
 313        let max_glyph_width = layout.em_width;
 314        let scroll_left = scroll_position.x() * max_glyph_width;
 315        let content_origin = bounds.origin() + layout.text_offset;
 316
 317        cx.scene.push_layer(Some(bounds));
 318
 319        for (color, range) in &layout.highlighted_ranges {
 320            self.paint_highlighted_range(
 321                range.clone(),
 322                start_row,
 323                end_row,
 324                *color,
 325                0.,
 326                layout,
 327                content_origin,
 328                scroll_top,
 329                scroll_left,
 330                bounds,
 331                cx,
 332            );
 333        }
 334
 335        let mut cursors = SmallVec::<[Cursor; 32]>::new();
 336        for (replica_id, selections) in &layout.selections {
 337            let style = style.replica_selection_style(*replica_id);
 338            let corner_radius = 0.15 * layout.line_height;
 339
 340            for selection in selections {
 341                self.paint_highlighted_range(
 342                    selection.start..selection.end,
 343                    start_row,
 344                    end_row,
 345                    style.selection,
 346                    corner_radius,
 347                    layout,
 348                    content_origin,
 349                    scroll_top,
 350                    scroll_left,
 351                    bounds,
 352                    cx,
 353                );
 354
 355                if view.show_local_cursors() || *replica_id != local_replica_id {
 356                    let cursor_position = selection.head();
 357                    if (start_row..end_row).contains(&cursor_position.row()) {
 358                        let cursor_row_layout =
 359                            &layout.line_layouts[(cursor_position.row() - start_row) as usize];
 360                        let x = cursor_row_layout.x_for_index(cursor_position.column() as usize)
 361                            - scroll_left;
 362                        let y = cursor_position.row() as f32 * layout.line_height - scroll_top;
 363                        cursors.push(Cursor {
 364                            color: style.cursor,
 365                            origin: content_origin + vec2f(x, y),
 366                            line_height: layout.line_height,
 367                        });
 368                    }
 369                }
 370            }
 371        }
 372
 373        if let Some(visible_text_bounds) = bounds.intersection(visible_bounds) {
 374            // Draw glyphs
 375            for (ix, line) in layout.line_layouts.iter().enumerate() {
 376                let row = start_row + ix as u32;
 377                line.paint(
 378                    content_origin
 379                        + vec2f(-scroll_left, row as f32 * layout.line_height - scroll_top),
 380                    visible_text_bounds,
 381                    layout.line_height,
 382                    cx,
 383                );
 384            }
 385        }
 386
 387        cx.scene.push_layer(Some(bounds));
 388        for cursor in cursors {
 389            cursor.paint(cx);
 390        }
 391        cx.scene.pop_layer();
 392
 393        cx.scene.pop_layer();
 394    }
 395
 396    fn paint_highlighted_range(
 397        &self,
 398        range: Range<DisplayPoint>,
 399        start_row: u32,
 400        end_row: u32,
 401        color: Color,
 402        corner_radius: f32,
 403        layout: &LayoutState,
 404        content_origin: Vector2F,
 405        scroll_top: f32,
 406        scroll_left: f32,
 407        bounds: RectF,
 408        cx: &mut PaintContext,
 409    ) {
 410        if range.start != range.end {
 411            let row_range = if range.end.column() == 0 {
 412                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
 413            } else {
 414                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
 415            };
 416
 417            let selection = HighlightedRange {
 418                color,
 419                line_height: layout.line_height,
 420                corner_radius,
 421                start_y: content_origin.y() + row_range.start as f32 * layout.line_height
 422                    - scroll_top,
 423                lines: row_range
 424                    .into_iter()
 425                    .map(|row| {
 426                        let line_layout = &layout.line_layouts[(row - start_row) as usize];
 427                        HighlightedRangeLine {
 428                            start_x: if row == range.start.row() {
 429                                content_origin.x()
 430                                    + line_layout.x_for_index(range.start.column() as usize)
 431                                    - scroll_left
 432                            } else {
 433                                content_origin.x() - scroll_left
 434                            },
 435                            end_x: if row == range.end.row() {
 436                                content_origin.x()
 437                                    + line_layout.x_for_index(range.end.column() as usize)
 438                                    - scroll_left
 439                            } else {
 440                                content_origin.x() + line_layout.width() + corner_radius * 2.0
 441                                    - scroll_left
 442                            },
 443                        }
 444                    })
 445                    .collect(),
 446            };
 447
 448            selection.paint(bounds, cx.scene);
 449        }
 450    }
 451
 452    fn paint_blocks(
 453        &mut self,
 454        bounds: RectF,
 455        visible_bounds: RectF,
 456        layout: &mut LayoutState,
 457        cx: &mut PaintContext,
 458    ) {
 459        let scroll_position = layout.snapshot.scroll_position();
 460        let scroll_left = scroll_position.x() * layout.em_width;
 461        let scroll_top = scroll_position.y() * layout.line_height;
 462
 463        for (row, element) in &mut layout.blocks {
 464            let origin = bounds.origin()
 465                + vec2f(-scroll_left, *row as f32 * layout.line_height - scroll_top);
 466            element.paint(origin, visible_bounds, cx);
 467        }
 468    }
 469
 470    fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &LayoutContext) -> f32 {
 471        let digit_count = (snapshot.max_buffer_row() as f32).log10().floor() as usize + 1;
 472        let style = &self.settings.style;
 473
 474        cx.text_layout_cache
 475            .layout_str(
 476                "1".repeat(digit_count).as_str(),
 477                style.text.font_size,
 478                &[(
 479                    digit_count,
 480                    RunStyle {
 481                        font_id: style.text.font_id,
 482                        color: Color::black(),
 483                        underline: None,
 484                    },
 485                )],
 486            )
 487            .width()
 488    }
 489
 490    fn layout_line_numbers(
 491        &self,
 492        rows: Range<u32>,
 493        active_rows: &BTreeMap<u32, bool>,
 494        snapshot: &EditorSnapshot,
 495        cx: &LayoutContext,
 496    ) -> Vec<Option<text_layout::Line>> {
 497        let style = &self.settings.style;
 498        let include_line_numbers = snapshot.mode == EditorMode::Full;
 499        let mut line_number_layouts = Vec::with_capacity(rows.len());
 500        let mut line_number = String::new();
 501        for (ix, row) in snapshot
 502            .buffer_rows(rows.start)
 503            .take((rows.end - rows.start) as usize)
 504            .enumerate()
 505        {
 506            let display_row = rows.start + ix as u32;
 507            let color = if active_rows.contains_key(&display_row) {
 508                style.line_number_active
 509            } else {
 510                style.line_number
 511            };
 512            if let Some(buffer_row) = row {
 513                if include_line_numbers {
 514                    line_number.clear();
 515                    write!(&mut line_number, "{}", buffer_row + 1).unwrap();
 516                    line_number_layouts.push(Some(cx.text_layout_cache.layout_str(
 517                        &line_number,
 518                        style.text.font_size,
 519                        &[(
 520                            line_number.len(),
 521                            RunStyle {
 522                                font_id: style.text.font_id,
 523                                color,
 524                                underline: None,
 525                            },
 526                        )],
 527                    )));
 528                }
 529            } else {
 530                line_number_layouts.push(None);
 531            }
 532        }
 533
 534        line_number_layouts
 535    }
 536
 537    fn layout_lines(
 538        &mut self,
 539        mut rows: Range<u32>,
 540        snapshot: &mut EditorSnapshot,
 541        cx: &LayoutContext,
 542    ) -> Vec<text_layout::Line> {
 543        rows.end = cmp::min(rows.end, snapshot.max_point().row() + 1);
 544        if rows.start >= rows.end {
 545            return Vec::new();
 546        }
 547
 548        // When the editor is empty and unfocused, then show the placeholder.
 549        if snapshot.is_empty() && !snapshot.is_focused() {
 550            let placeholder_style = self.settings.style.placeholder_text();
 551            let placeholder_text = snapshot.placeholder_text();
 552            let placeholder_lines = placeholder_text
 553                .as_ref()
 554                .map_or("", AsRef::as_ref)
 555                .split('\n')
 556                .skip(rows.start as usize)
 557                .take(rows.len());
 558            return placeholder_lines
 559                .map(|line| {
 560                    cx.text_layout_cache.layout_str(
 561                        line,
 562                        placeholder_style.font_size,
 563                        &[(
 564                            line.len(),
 565                            RunStyle {
 566                                font_id: placeholder_style.font_id,
 567                                color: placeholder_style.color,
 568                                underline: None,
 569                            },
 570                        )],
 571                    )
 572                })
 573                .collect();
 574        } else {
 575            let style = &self.settings.style;
 576            let chunks = snapshot
 577                .chunks(rows.clone(), Some(&style.syntax))
 578                .map(|chunk| {
 579                    let highlight = if let Some(severity) = chunk.diagnostic {
 580                        let diagnostic_style = super::diagnostic_style(severity, true, style);
 581                        let underline = Some(Underline {
 582                            color: diagnostic_style.message.text.color,
 583                            thickness: 1.0.into(),
 584                            squiggly: true,
 585                        });
 586                        if let Some(mut highlight) = chunk.highlight_style {
 587                            highlight.underline = underline;
 588                            Some(highlight)
 589                        } else {
 590                            Some(HighlightStyle {
 591                                underline,
 592                                color: style.text.color,
 593                                font_properties: style.text.font_properties,
 594                            })
 595                        }
 596                    } else {
 597                        chunk.highlight_style
 598                    };
 599                    (chunk.text, highlight)
 600                });
 601            layout_highlighted_chunks(
 602                chunks,
 603                &style.text,
 604                &cx.text_layout_cache,
 605                &cx.font_cache,
 606                MAX_LINE_LEN,
 607                rows.len() as usize,
 608            )
 609        }
 610    }
 611
 612    fn layout_blocks(
 613        &mut self,
 614        rows: Range<u32>,
 615        snapshot: &EditorSnapshot,
 616        width: f32,
 617        gutter_padding: f32,
 618        gutter_width: f32,
 619        em_width: f32,
 620        text_x: f32,
 621        line_height: f32,
 622        style: &EditorStyle,
 623        line_layouts: &[text_layout::Line],
 624        cx: &mut LayoutContext,
 625    ) -> Vec<(u32, ElementBox)> {
 626        snapshot
 627            .blocks_in_range(rows.clone())
 628            .map(|(start_row, block)| {
 629                let anchor_row = block
 630                    .position()
 631                    .to_point(&snapshot.buffer_snapshot)
 632                    .to_display_point(snapshot)
 633                    .row();
 634
 635                let anchor_x = text_x
 636                    + if rows.contains(&anchor_row) {
 637                        line_layouts[(anchor_row - rows.start) as usize]
 638                            .x_for_index(block.column() as usize)
 639                    } else {
 640                        layout_line(anchor_row, snapshot, style, cx.text_layout_cache)
 641                            .x_for_index(block.column() as usize)
 642                    };
 643
 644                let mut element = block.render(&BlockContext {
 645                    cx,
 646                    anchor_x,
 647                    gutter_padding,
 648                    line_height,
 649                    scroll_x: snapshot.scroll_position.x(),
 650                    gutter_width,
 651                    em_width,
 652                });
 653                element.layout(
 654                    SizeConstraint {
 655                        min: Vector2F::zero(),
 656                        max: vec2f(width, block.height() as f32 * line_height),
 657                    },
 658                    cx,
 659                );
 660                (start_row, element)
 661            })
 662            .collect()
 663    }
 664}
 665
 666impl Element for EditorElement {
 667    type LayoutState = Option<LayoutState>;
 668    type PaintState = Option<PaintState>;
 669
 670    fn layout(
 671        &mut self,
 672        constraint: SizeConstraint,
 673        cx: &mut LayoutContext,
 674    ) -> (Vector2F, Self::LayoutState) {
 675        let mut size = constraint.max;
 676        if size.x().is_infinite() {
 677            unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
 678        }
 679
 680        let snapshot = self.snapshot(cx.app);
 681        let style = self.settings.style.clone();
 682        let line_height = style.text.line_height(cx.font_cache);
 683
 684        let gutter_padding;
 685        let gutter_width;
 686        if snapshot.mode == EditorMode::Full {
 687            gutter_padding = style.text.em_width(cx.font_cache) * style.gutter_padding_factor;
 688            gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
 689        } else {
 690            gutter_padding = 0.0;
 691            gutter_width = 0.0
 692        };
 693
 694        let text_width = size.x() - gutter_width;
 695        let text_offset = vec2f(-style.text.descent(cx.font_cache), 0.);
 696        let em_width = style.text.em_width(cx.font_cache);
 697        let em_advance = style.text.em_advance(cx.font_cache);
 698        let overscroll = vec2f(em_width, 0.);
 699        let wrap_width = match self.settings.soft_wrap {
 700            SoftWrap::None => None,
 701            SoftWrap::EditorWidth => Some(text_width - text_offset.x() - overscroll.x() - em_width),
 702            SoftWrap::Column(column) => Some(column as f32 * em_advance),
 703        };
 704        let snapshot = self.update_view(cx.app, |view, cx| {
 705            if view.set_wrap_width(wrap_width, cx) {
 706                view.snapshot(cx)
 707            } else {
 708                snapshot
 709            }
 710        });
 711
 712        let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
 713        if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
 714            size.set_y(
 715                scroll_height
 716                    .min(constraint.max_along(Axis::Vertical))
 717                    .max(constraint.min_along(Axis::Vertical))
 718                    .min(line_height * max_lines as f32),
 719            )
 720        } else if size.y().is_infinite() {
 721            size.set_y(scroll_height);
 722        }
 723        let gutter_size = vec2f(gutter_width, size.y());
 724        let text_size = vec2f(text_width, size.y());
 725
 726        let (autoscroll_horizontally, mut snapshot) = self.update_view(cx.app, |view, cx| {
 727            let autoscroll_horizontally = view.autoscroll_vertically(size.y(), line_height, cx);
 728            let snapshot = view.snapshot(cx);
 729            (autoscroll_horizontally, snapshot)
 730        });
 731
 732        let scroll_position = snapshot.scroll_position();
 733        let start_row = scroll_position.y() as u32;
 734        let scroll_top = scroll_position.y() * line_height;
 735        let end_row = ((scroll_top + size.y()) / line_height).ceil() as u32 + 1; // Add 1 to ensure selections bleed off screen
 736
 737        let start_anchor = if start_row == 0 {
 738            Anchor::min()
 739        } else {
 740            snapshot
 741                .buffer_snapshot
 742                .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
 743        };
 744        let end_anchor = if end_row > snapshot.max_point().row() {
 745            Anchor::max()
 746        } else {
 747            snapshot
 748                .buffer_snapshot
 749                .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
 750        };
 751
 752        let mut selections = HashMap::default();
 753        let mut active_rows = BTreeMap::new();
 754        let mut highlighted_rows = None;
 755        let mut highlighted_ranges = Vec::new();
 756        self.update_view(cx.app, |view, cx| {
 757            let display_map = view.display_map.update(cx, |map, cx| map.snapshot(cx));
 758
 759            highlighted_rows = view.highlighted_rows();
 760            highlighted_ranges = view.highlighted_ranges_in_range(
 761                start_anchor.clone()..end_anchor.clone(),
 762                &display_map,
 763            );
 764
 765            let local_selections = view
 766                .local_selections_in_range(start_anchor.clone()..end_anchor.clone(), &display_map);
 767            for selection in &local_selections {
 768                let is_empty = selection.start == selection.end;
 769                let selection_start = snapshot.prev_line_boundary(selection.start).1;
 770                let selection_end = snapshot.next_line_boundary(selection.end).1;
 771                for row in cmp::max(selection_start.row(), start_row)
 772                    ..=cmp::min(selection_end.row(), end_row)
 773                {
 774                    let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
 775                    *contains_non_empty_selection |= !is_empty;
 776                }
 777            }
 778            selections.insert(
 779                view.replica_id(cx),
 780                local_selections
 781                    .into_iter()
 782                    .map(|selection| crate::Selection {
 783                        id: selection.id,
 784                        goal: selection.goal,
 785                        reversed: selection.reversed,
 786                        start: selection.start.to_display_point(&display_map),
 787                        end: selection.end.to_display_point(&display_map),
 788                    })
 789                    .collect(),
 790            );
 791
 792            for (replica_id, selection) in display_map
 793                .buffer_snapshot
 794                .remote_selections_in_range(&(start_anchor..end_anchor))
 795            {
 796                selections
 797                    .entry(replica_id)
 798                    .or_insert(Vec::new())
 799                    .push(crate::Selection {
 800                        id: selection.id,
 801                        goal: selection.goal,
 802                        reversed: selection.reversed,
 803                        start: selection.start.to_display_point(&display_map),
 804                        end: selection.end.to_display_point(&display_map),
 805                    });
 806            }
 807        });
 808
 809        let line_number_layouts =
 810            self.layout_line_numbers(start_row..end_row, &active_rows, &snapshot, cx);
 811
 812        let mut max_visible_line_width = 0.0;
 813        let line_layouts = self.layout_lines(start_row..end_row, &mut snapshot, cx);
 814        for line in &line_layouts {
 815            if line.width() > max_visible_line_width {
 816                max_visible_line_width = line.width();
 817            }
 818        }
 819
 820        let style = self.settings.style.clone();
 821        let longest_line_width = layout_line(
 822            snapshot.longest_row(),
 823            &snapshot,
 824            &style,
 825            cx.text_layout_cache,
 826        )
 827        .width();
 828        let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
 829        let em_width = style.text.em_width(cx.font_cache);
 830        let max_row = snapshot.max_point().row();
 831        let scroll_max = vec2f(
 832            ((scroll_width - text_size.x()) / em_width).max(0.0),
 833            max_row.saturating_sub(1) as f32,
 834        );
 835
 836        self.update_view(cx.app, |view, cx| {
 837            let clamped = view.clamp_scroll_left(scroll_max.x());
 838            let autoscrolled;
 839            if autoscroll_horizontally {
 840                autoscrolled = view.autoscroll_horizontally(
 841                    start_row,
 842                    text_size.x(),
 843                    scroll_width,
 844                    em_width,
 845                    &line_layouts,
 846                    cx,
 847                );
 848            } else {
 849                autoscrolled = false;
 850            }
 851
 852            if clamped || autoscrolled {
 853                snapshot = view.snapshot(cx);
 854            }
 855        });
 856
 857        let blocks = self.layout_blocks(
 858            start_row..end_row,
 859            &snapshot,
 860            size.x().max(scroll_width + gutter_width),
 861            gutter_padding,
 862            gutter_width,
 863            em_width,
 864            gutter_width + text_offset.x(),
 865            line_height,
 866            &style,
 867            &line_layouts,
 868            cx,
 869        );
 870
 871        (
 872            size,
 873            Some(LayoutState {
 874                size,
 875                scroll_max,
 876                gutter_size,
 877                gutter_padding,
 878                text_size,
 879                text_offset,
 880                snapshot,
 881                active_rows,
 882                highlighted_rows,
 883                highlighted_ranges,
 884                line_layouts,
 885                line_number_layouts,
 886                blocks,
 887                line_height,
 888                em_width,
 889                em_advance,
 890                selections,
 891            }),
 892        )
 893    }
 894
 895    fn paint(
 896        &mut self,
 897        bounds: RectF,
 898        visible_bounds: RectF,
 899        layout: &mut Self::LayoutState,
 900        cx: &mut PaintContext,
 901    ) -> Self::PaintState {
 902        let layout = layout.as_mut()?;
 903        cx.scene.push_layer(Some(bounds));
 904
 905        let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
 906        let text_bounds = RectF::new(
 907            bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
 908            layout.text_size,
 909        );
 910
 911        self.paint_background(gutter_bounds, text_bounds, layout, cx);
 912        if layout.gutter_size.x() > 0. {
 913            self.paint_gutter(gutter_bounds, visible_bounds, layout, cx);
 914        }
 915        self.paint_text(text_bounds, visible_bounds, layout, cx);
 916
 917        if !layout.blocks.is_empty() {
 918            cx.scene.push_layer(Some(bounds));
 919            self.paint_blocks(bounds, visible_bounds, layout, cx);
 920            cx.scene.pop_layer();
 921        }
 922
 923        cx.scene.pop_layer();
 924
 925        Some(PaintState {
 926            bounds,
 927            gutter_bounds,
 928            text_bounds,
 929        })
 930    }
 931
 932    fn dispatch_event(
 933        &mut self,
 934        event: &Event,
 935        _: RectF,
 936        layout: &mut Self::LayoutState,
 937        paint: &mut Self::PaintState,
 938        cx: &mut EventContext,
 939    ) -> bool {
 940        if let (Some(layout), Some(paint)) = (layout, paint) {
 941            match event {
 942                Event::LeftMouseDown {
 943                    position,
 944                    alt,
 945                    shift,
 946                    click_count,
 947                    ..
 948                } => self.mouse_down(*position, *alt, *shift, *click_count, layout, paint, cx),
 949                Event::LeftMouseUp { position } => self.mouse_up(*position, cx),
 950                Event::LeftMouseDragged { position } => {
 951                    self.mouse_dragged(*position, layout, paint, cx)
 952                }
 953                Event::ScrollWheel {
 954                    position,
 955                    delta,
 956                    precise,
 957                } => self.scroll(*position, *delta, *precise, layout, paint, cx),
 958                Event::KeyDown {
 959                    chars, keystroke, ..
 960                } => self.key_down(chars, keystroke, cx),
 961                _ => false,
 962            }
 963        } else {
 964            false
 965        }
 966    }
 967
 968    fn debug(
 969        &self,
 970        bounds: RectF,
 971        _: &Self::LayoutState,
 972        _: &Self::PaintState,
 973        _: &gpui::DebugContext,
 974    ) -> json::Value {
 975        json!({
 976            "type": "BufferElement",
 977            "bounds": bounds.to_json()
 978        })
 979    }
 980}
 981
 982pub struct LayoutState {
 983    size: Vector2F,
 984    scroll_max: Vector2F,
 985    gutter_size: Vector2F,
 986    gutter_padding: f32,
 987    text_size: Vector2F,
 988    snapshot: EditorSnapshot,
 989    active_rows: BTreeMap<u32, bool>,
 990    highlighted_rows: Option<Range<u32>>,
 991    line_layouts: Vec<text_layout::Line>,
 992    line_number_layouts: Vec<Option<text_layout::Line>>,
 993    blocks: Vec<(u32, ElementBox)>,
 994    line_height: f32,
 995    em_width: f32,
 996    em_advance: f32,
 997    highlighted_ranges: Vec<(Color, Range<DisplayPoint>)>,
 998    selections: HashMap<ReplicaId, Vec<text::Selection<DisplayPoint>>>,
 999    text_offset: Vector2F,
1000}
1001
1002fn layout_line(
1003    row: u32,
1004    snapshot: &EditorSnapshot,
1005    style: &EditorStyle,
1006    layout_cache: &TextLayoutCache,
1007) -> text_layout::Line {
1008    let mut line = snapshot.line(row);
1009
1010    if line.len() > MAX_LINE_LEN {
1011        let mut len = MAX_LINE_LEN;
1012        while !line.is_char_boundary(len) {
1013            len -= 1;
1014        }
1015        line.truncate(len);
1016    }
1017
1018    layout_cache.layout_str(
1019        &line,
1020        style.text.font_size,
1021        &[(
1022            snapshot.line_len(row) as usize,
1023            RunStyle {
1024                font_id: style.text.font_id,
1025                color: Color::black(),
1026                underline: None,
1027            },
1028        )],
1029    )
1030}
1031
1032pub struct PaintState {
1033    bounds: RectF,
1034    gutter_bounds: RectF,
1035    text_bounds: RectF,
1036}
1037
1038impl PaintState {
1039    fn point_for_position(
1040        &self,
1041        snapshot: &EditorSnapshot,
1042        layout: &LayoutState,
1043        position: Vector2F,
1044    ) -> (DisplayPoint, u32) {
1045        let scroll_position = snapshot.scroll_position();
1046        let position = position - self.text_bounds.origin();
1047        let y = position.y().max(0.0).min(layout.size.y());
1048        let row = ((y / layout.line_height) + scroll_position.y()) as u32;
1049        let row = cmp::min(row, snapshot.max_point().row());
1050        let line = &layout.line_layouts[(row - scroll_position.y() as u32) as usize];
1051        let x = position.x() + (scroll_position.x() * layout.em_width);
1052
1053        let column = if x >= 0.0 {
1054            line.index_for_x(x)
1055                .map(|ix| ix as u32)
1056                .unwrap_or_else(|| snapshot.line_len(row))
1057        } else {
1058            0
1059        };
1060        let overshoot = (0f32.max(x - line.width()) / layout.em_advance) as u32;
1061
1062        (DisplayPoint::new(row, column), overshoot)
1063    }
1064}
1065
1066struct Cursor {
1067    origin: Vector2F,
1068    line_height: f32,
1069    color: Color,
1070}
1071
1072impl Cursor {
1073    fn paint(&self, cx: &mut PaintContext) {
1074        cx.scene.push_quad(Quad {
1075            bounds: RectF::new(self.origin, vec2f(2.0, self.line_height)),
1076            background: Some(self.color),
1077            border: Border::new(0., Color::black()),
1078            corner_radius: 0.,
1079        });
1080    }
1081}
1082
1083#[derive(Debug)]
1084struct HighlightedRange {
1085    start_y: f32,
1086    line_height: f32,
1087    lines: Vec<HighlightedRangeLine>,
1088    color: Color,
1089    corner_radius: f32,
1090}
1091
1092#[derive(Debug)]
1093struct HighlightedRangeLine {
1094    start_x: f32,
1095    end_x: f32,
1096}
1097
1098impl HighlightedRange {
1099    fn paint(&self, bounds: RectF, scene: &mut Scene) {
1100        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
1101            self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
1102            self.paint_lines(
1103                self.start_y + self.line_height,
1104                &self.lines[1..],
1105                bounds,
1106                scene,
1107            );
1108        } else {
1109            self.paint_lines(self.start_y, &self.lines, bounds, scene);
1110        }
1111    }
1112
1113    fn paint_lines(
1114        &self,
1115        start_y: f32,
1116        lines: &[HighlightedRangeLine],
1117        bounds: RectF,
1118        scene: &mut Scene,
1119    ) {
1120        if lines.is_empty() {
1121            return;
1122        }
1123
1124        let mut path = PathBuilder::new();
1125        let first_line = lines.first().unwrap();
1126        let last_line = lines.last().unwrap();
1127
1128        let first_top_left = vec2f(first_line.start_x, start_y);
1129        let first_top_right = vec2f(first_line.end_x, start_y);
1130
1131        let curve_height = vec2f(0., self.corner_radius);
1132        let curve_width = |start_x: f32, end_x: f32| {
1133            let max = (end_x - start_x) / 2.;
1134            let width = if max < self.corner_radius {
1135                max
1136            } else {
1137                self.corner_radius
1138            };
1139
1140            vec2f(width, 0.)
1141        };
1142
1143        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
1144        path.reset(first_top_right - top_curve_width);
1145        path.curve_to(first_top_right + curve_height, first_top_right);
1146
1147        let mut iter = lines.iter().enumerate().peekable();
1148        while let Some((ix, line)) = iter.next() {
1149            let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
1150
1151            if let Some((_, next_line)) = iter.peek() {
1152                let next_top_right = vec2f(next_line.end_x, bottom_right.y());
1153
1154                match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
1155                    Ordering::Equal => {
1156                        path.line_to(bottom_right);
1157                    }
1158                    Ordering::Less => {
1159                        let curve_width = curve_width(next_top_right.x(), bottom_right.x());
1160                        path.line_to(bottom_right - curve_height);
1161                        if self.corner_radius > 0. {
1162                            path.curve_to(bottom_right - curve_width, bottom_right);
1163                        }
1164                        path.line_to(next_top_right + curve_width);
1165                        if self.corner_radius > 0. {
1166                            path.curve_to(next_top_right + curve_height, next_top_right);
1167                        }
1168                    }
1169                    Ordering::Greater => {
1170                        let curve_width = curve_width(bottom_right.x(), next_top_right.x());
1171                        path.line_to(bottom_right - curve_height);
1172                        if self.corner_radius > 0. {
1173                            path.curve_to(bottom_right + curve_width, bottom_right);
1174                        }
1175                        path.line_to(next_top_right - curve_width);
1176                        if self.corner_radius > 0. {
1177                            path.curve_to(next_top_right + curve_height, next_top_right);
1178                        }
1179                    }
1180                }
1181            } else {
1182                let curve_width = curve_width(line.start_x, line.end_x);
1183                path.line_to(bottom_right - curve_height);
1184                if self.corner_radius > 0. {
1185                    path.curve_to(bottom_right - curve_width, bottom_right);
1186                }
1187
1188                let bottom_left = vec2f(line.start_x, bottom_right.y());
1189                path.line_to(bottom_left + curve_width);
1190                if self.corner_radius > 0. {
1191                    path.curve_to(bottom_left - curve_height, bottom_left);
1192                }
1193            }
1194        }
1195
1196        if first_line.start_x > last_line.start_x {
1197            let curve_width = curve_width(last_line.start_x, first_line.start_x);
1198            let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
1199            path.line_to(second_top_left + curve_height);
1200            if self.corner_radius > 0. {
1201                path.curve_to(second_top_left + curve_width, second_top_left);
1202            }
1203            let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
1204            path.line_to(first_bottom_left - curve_width);
1205            if self.corner_radius > 0. {
1206                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
1207            }
1208        }
1209
1210        path.line_to(first_top_left + curve_height);
1211        if self.corner_radius > 0. {
1212            path.curve_to(first_top_left + top_curve_width, first_top_left);
1213        }
1214        path.line_to(first_top_right - top_curve_width);
1215
1216        scene.push_path(path.build(self.color, Some(bounds)));
1217    }
1218}
1219
1220fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
1221    delta.powf(1.5) / 100.0
1222}
1223
1224fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
1225    delta.powf(1.2) / 300.0
1226}
1227
1228#[cfg(test)]
1229mod tests {
1230    use super::*;
1231    use crate::{Editor, EditorSettings, MultiBuffer};
1232    use std::sync::Arc;
1233    use util::test::sample_text;
1234
1235    #[gpui::test]
1236    fn test_layout_line_numbers(cx: &mut gpui::MutableAppContext) {
1237        let settings = EditorSettings::test(cx);
1238        let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
1239        let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1240            Editor::for_buffer(
1241                buffer,
1242                {
1243                    let settings = settings.clone();
1244                    Arc::new(move |_| settings.clone())
1245                },
1246                cx,
1247            )
1248        });
1249        let element = EditorElement::new(editor.downgrade(), settings);
1250
1251        let layouts = editor.update(cx, |editor, cx| {
1252            let snapshot = editor.snapshot(cx);
1253            let mut presenter = cx.build_presenter(window_id, 30.);
1254            let mut layout_cx = presenter.build_layout_context(false, cx);
1255            element.layout_line_numbers(0..6, &Default::default(), &snapshot, &mut layout_cx)
1256        });
1257        assert_eq!(layouts.len(), 6);
1258    }
1259}