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 (range, color) in &layout.highlighted_ranges {
 320            self.paint_highlighted_range(
 321                range.clone(),
 322                start_row,
 323                end_row,
 324                *color,
 325                0.,
 326                0.15 * layout.line_height,
 327                layout,
 328                content_origin,
 329                scroll_top,
 330                scroll_left,
 331                bounds,
 332                cx,
 333            );
 334        }
 335
 336        let mut cursors = SmallVec::<[Cursor; 32]>::new();
 337        for (replica_id, selections) in &layout.selections {
 338            let style = style.replica_selection_style(*replica_id);
 339            let corner_radius = 0.15 * layout.line_height;
 340
 341            for selection in selections {
 342                self.paint_highlighted_range(
 343                    selection.start..selection.end,
 344                    start_row,
 345                    end_row,
 346                    style.selection,
 347                    corner_radius,
 348                    corner_radius * 2.,
 349                    layout,
 350                    content_origin,
 351                    scroll_top,
 352                    scroll_left,
 353                    bounds,
 354                    cx,
 355                );
 356
 357                if view.show_local_cursors() || *replica_id != local_replica_id {
 358                    let cursor_position = selection.head();
 359                    if (start_row..end_row).contains(&cursor_position.row()) {
 360                        let cursor_row_layout =
 361                            &layout.line_layouts[(cursor_position.row() - start_row) as usize];
 362                        let x = cursor_row_layout.x_for_index(cursor_position.column() as usize)
 363                            - scroll_left;
 364                        let y = cursor_position.row() as f32 * layout.line_height - scroll_top;
 365                        cursors.push(Cursor {
 366                            color: style.cursor,
 367                            origin: content_origin + vec2f(x, y),
 368                            line_height: layout.line_height,
 369                        });
 370                    }
 371                }
 372            }
 373        }
 374
 375        if let Some(visible_text_bounds) = bounds.intersection(visible_bounds) {
 376            // Draw glyphs
 377            for (ix, line) in layout.line_layouts.iter().enumerate() {
 378                let row = start_row + ix as u32;
 379                line.paint(
 380                    content_origin
 381                        + vec2f(-scroll_left, row as f32 * layout.line_height - scroll_top),
 382                    visible_text_bounds,
 383                    layout.line_height,
 384                    cx,
 385                );
 386            }
 387        }
 388
 389        cx.scene.push_layer(Some(bounds));
 390        for cursor in cursors {
 391            cursor.paint(cx);
 392        }
 393        cx.scene.pop_layer();
 394
 395        cx.scene.pop_layer();
 396    }
 397
 398    fn paint_highlighted_range(
 399        &self,
 400        range: Range<DisplayPoint>,
 401        start_row: u32,
 402        end_row: u32,
 403        color: Color,
 404        corner_radius: f32,
 405        line_end_overshoot: f32,
 406        layout: &LayoutState,
 407        content_origin: Vector2F,
 408        scroll_top: f32,
 409        scroll_left: f32,
 410        bounds: RectF,
 411        cx: &mut PaintContext,
 412    ) {
 413        if range.start != range.end {
 414            let row_range = if range.end.column() == 0 {
 415                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
 416            } else {
 417                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
 418            };
 419
 420            let highlighted_range = HighlightedRange {
 421                color,
 422                line_height: layout.line_height,
 423                corner_radius,
 424                start_y: content_origin.y() + row_range.start as f32 * layout.line_height
 425                    - scroll_top,
 426                lines: row_range
 427                    .into_iter()
 428                    .map(|row| {
 429                        let line_layout = &layout.line_layouts[(row - start_row) as usize];
 430                        HighlightedRangeLine {
 431                            start_x: if row == range.start.row() {
 432                                content_origin.x()
 433                                    + line_layout.x_for_index(range.start.column() as usize)
 434                                    - scroll_left
 435                            } else {
 436                                content_origin.x() - scroll_left
 437                            },
 438                            end_x: if row == range.end.row() {
 439                                content_origin.x()
 440                                    + line_layout.x_for_index(range.end.column() as usize)
 441                                    - scroll_left
 442                            } else {
 443                                content_origin.x() + line_layout.width() + line_end_overshoot
 444                                    - scroll_left
 445                            },
 446                        }
 447                    })
 448                    .collect(),
 449            };
 450
 451            highlighted_range.paint(bounds, cx.scene);
 452        }
 453    }
 454
 455    fn paint_blocks(
 456        &mut self,
 457        bounds: RectF,
 458        visible_bounds: RectF,
 459        layout: &mut LayoutState,
 460        cx: &mut PaintContext,
 461    ) {
 462        let scroll_position = layout.snapshot.scroll_position();
 463        let scroll_left = scroll_position.x() * layout.em_width;
 464        let scroll_top = scroll_position.y() * layout.line_height;
 465
 466        for (row, element) in &mut layout.blocks {
 467            let origin = bounds.origin()
 468                + vec2f(-scroll_left, *row as f32 * layout.line_height - scroll_top);
 469            element.paint(origin, visible_bounds, cx);
 470        }
 471    }
 472
 473    fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &LayoutContext) -> f32 {
 474        let digit_count = (snapshot.max_buffer_row() as f32).log10().floor() as usize + 1;
 475        let style = &self.settings.style;
 476
 477        cx.text_layout_cache
 478            .layout_str(
 479                "1".repeat(digit_count).as_str(),
 480                style.text.font_size,
 481                &[(
 482                    digit_count,
 483                    RunStyle {
 484                        font_id: style.text.font_id,
 485                        color: Color::black(),
 486                        underline: None,
 487                    },
 488                )],
 489            )
 490            .width()
 491    }
 492
 493    fn layout_line_numbers(
 494        &self,
 495        rows: Range<u32>,
 496        active_rows: &BTreeMap<u32, bool>,
 497        snapshot: &EditorSnapshot,
 498        cx: &LayoutContext,
 499    ) -> Vec<Option<text_layout::Line>> {
 500        let style = &self.settings.style;
 501        let include_line_numbers = snapshot.mode == EditorMode::Full;
 502        let mut line_number_layouts = Vec::with_capacity(rows.len());
 503        let mut line_number = String::new();
 504        for (ix, row) in snapshot
 505            .buffer_rows(rows.start)
 506            .take((rows.end - rows.start) as usize)
 507            .enumerate()
 508        {
 509            let display_row = rows.start + ix as u32;
 510            let color = if active_rows.contains_key(&display_row) {
 511                style.line_number_active
 512            } else {
 513                style.line_number
 514            };
 515            if let Some(buffer_row) = row {
 516                if include_line_numbers {
 517                    line_number.clear();
 518                    write!(&mut line_number, "{}", buffer_row + 1).unwrap();
 519                    line_number_layouts.push(Some(cx.text_layout_cache.layout_str(
 520                        &line_number,
 521                        style.text.font_size,
 522                        &[(
 523                            line_number.len(),
 524                            RunStyle {
 525                                font_id: style.text.font_id,
 526                                color,
 527                                underline: None,
 528                            },
 529                        )],
 530                    )));
 531                }
 532            } else {
 533                line_number_layouts.push(None);
 534            }
 535        }
 536
 537        line_number_layouts
 538    }
 539
 540    fn layout_lines(
 541        &mut self,
 542        mut rows: Range<u32>,
 543        snapshot: &mut EditorSnapshot,
 544        cx: &LayoutContext,
 545    ) -> Vec<text_layout::Line> {
 546        rows.end = cmp::min(rows.end, snapshot.max_point().row() + 1);
 547        if rows.start >= rows.end {
 548            return Vec::new();
 549        }
 550
 551        // When the editor is empty and unfocused, then show the placeholder.
 552        if snapshot.is_empty() && !snapshot.is_focused() {
 553            let placeholder_style = self.settings.style.placeholder_text();
 554            let placeholder_text = snapshot.placeholder_text();
 555            let placeholder_lines = placeholder_text
 556                .as_ref()
 557                .map_or("", AsRef::as_ref)
 558                .split('\n')
 559                .skip(rows.start as usize)
 560                .take(rows.len());
 561            return placeholder_lines
 562                .map(|line| {
 563                    cx.text_layout_cache.layout_str(
 564                        line,
 565                        placeholder_style.font_size,
 566                        &[(
 567                            line.len(),
 568                            RunStyle {
 569                                font_id: placeholder_style.font_id,
 570                                color: placeholder_style.color,
 571                                underline: None,
 572                            },
 573                        )],
 574                    )
 575                })
 576                .collect();
 577        } else {
 578            let style = &self.settings.style;
 579            let chunks = snapshot
 580                .chunks(rows.clone(), Some(&style.syntax))
 581                .map(|chunk| {
 582                    let highlight = if let Some(severity) = chunk.diagnostic {
 583                        let diagnostic_style = super::diagnostic_style(severity, true, style);
 584                        let underline = Some(Underline {
 585                            color: diagnostic_style.message.text.color,
 586                            thickness: 1.0.into(),
 587                            squiggly: true,
 588                        });
 589                        if let Some(mut highlight) = chunk.highlight_style {
 590                            highlight.underline = underline;
 591                            Some(highlight)
 592                        } else {
 593                            Some(HighlightStyle {
 594                                underline,
 595                                color: style.text.color,
 596                                font_properties: style.text.font_properties,
 597                            })
 598                        }
 599                    } else {
 600                        chunk.highlight_style
 601                    };
 602                    (chunk.text, highlight)
 603                });
 604            layout_highlighted_chunks(
 605                chunks,
 606                &style.text,
 607                &cx.text_layout_cache,
 608                &cx.font_cache,
 609                MAX_LINE_LEN,
 610                rows.len() as usize,
 611            )
 612        }
 613    }
 614
 615    fn layout_blocks(
 616        &mut self,
 617        rows: Range<u32>,
 618        snapshot: &EditorSnapshot,
 619        width: f32,
 620        gutter_padding: f32,
 621        gutter_width: f32,
 622        em_width: f32,
 623        text_x: f32,
 624        line_height: f32,
 625        style: &EditorStyle,
 626        line_layouts: &[text_layout::Line],
 627        cx: &mut LayoutContext,
 628    ) -> Vec<(u32, ElementBox)> {
 629        snapshot
 630            .blocks_in_range(rows.clone())
 631            .map(|(start_row, block)| {
 632                let anchor_row = block
 633                    .position()
 634                    .to_point(&snapshot.buffer_snapshot)
 635                    .to_display_point(snapshot)
 636                    .row();
 637
 638                let anchor_x = text_x
 639                    + if rows.contains(&anchor_row) {
 640                        line_layouts[(anchor_row - rows.start) as usize]
 641                            .x_for_index(block.column() as usize)
 642                    } else {
 643                        layout_line(anchor_row, snapshot, style, cx.text_layout_cache)
 644                            .x_for_index(block.column() as usize)
 645                    };
 646
 647                let mut element = block.render(&BlockContext {
 648                    cx,
 649                    anchor_x,
 650                    gutter_padding,
 651                    line_height,
 652                    scroll_x: snapshot.scroll_position.x(),
 653                    gutter_width,
 654                    em_width,
 655                });
 656                element.layout(
 657                    SizeConstraint {
 658                        min: Vector2F::zero(),
 659                        max: vec2f(width, block.height() as f32 * line_height),
 660                    },
 661                    cx,
 662                );
 663                (start_row, element)
 664            })
 665            .collect()
 666    }
 667}
 668
 669impl Element for EditorElement {
 670    type LayoutState = Option<LayoutState>;
 671    type PaintState = Option<PaintState>;
 672
 673    fn layout(
 674        &mut self,
 675        constraint: SizeConstraint,
 676        cx: &mut LayoutContext,
 677    ) -> (Vector2F, Self::LayoutState) {
 678        let mut size = constraint.max;
 679        if size.x().is_infinite() {
 680            unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
 681        }
 682
 683        let snapshot = self.snapshot(cx.app);
 684        let style = self.settings.style.clone();
 685        let line_height = style.text.line_height(cx.font_cache);
 686
 687        let gutter_padding;
 688        let gutter_width;
 689        if snapshot.mode == EditorMode::Full {
 690            gutter_padding = style.text.em_width(cx.font_cache) * style.gutter_padding_factor;
 691            gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
 692        } else {
 693            gutter_padding = 0.0;
 694            gutter_width = 0.0
 695        };
 696
 697        let text_width = size.x() - gutter_width;
 698        let text_offset = vec2f(-style.text.descent(cx.font_cache), 0.);
 699        let em_width = style.text.em_width(cx.font_cache);
 700        let em_advance = style.text.em_advance(cx.font_cache);
 701        let overscroll = vec2f(em_width, 0.);
 702        let wrap_width = match self.settings.soft_wrap {
 703            SoftWrap::None => None,
 704            SoftWrap::EditorWidth => Some(text_width - text_offset.x() - overscroll.x() - em_width),
 705            SoftWrap::Column(column) => Some(column as f32 * em_advance),
 706        };
 707        let snapshot = self.update_view(cx.app, |view, cx| {
 708            if view.set_wrap_width(wrap_width, cx) {
 709                view.snapshot(cx)
 710            } else {
 711                snapshot
 712            }
 713        });
 714
 715        let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
 716        if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
 717            size.set_y(
 718                scroll_height
 719                    .min(constraint.max_along(Axis::Vertical))
 720                    .max(constraint.min_along(Axis::Vertical))
 721                    .min(line_height * max_lines as f32),
 722            )
 723        } else if size.y().is_infinite() {
 724            size.set_y(scroll_height);
 725        }
 726        let gutter_size = vec2f(gutter_width, size.y());
 727        let text_size = vec2f(text_width, size.y());
 728
 729        let (autoscroll_horizontally, mut snapshot) = self.update_view(cx.app, |view, cx| {
 730            let autoscroll_horizontally = view.autoscroll_vertically(size.y(), line_height, cx);
 731            let snapshot = view.snapshot(cx);
 732            (autoscroll_horizontally, snapshot)
 733        });
 734
 735        let scroll_position = snapshot.scroll_position();
 736        let start_row = scroll_position.y() as u32;
 737        let scroll_top = scroll_position.y() * line_height;
 738        let end_row = ((scroll_top + size.y()) / line_height).ceil() as u32 + 1; // Add 1 to ensure selections bleed off screen
 739
 740        let start_anchor = if start_row == 0 {
 741            Anchor::min()
 742        } else {
 743            snapshot
 744                .buffer_snapshot
 745                .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
 746        };
 747        let end_anchor = if end_row > snapshot.max_point().row() {
 748            Anchor::max()
 749        } else {
 750            snapshot
 751                .buffer_snapshot
 752                .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
 753        };
 754
 755        let mut selections = HashMap::default();
 756        let mut active_rows = BTreeMap::new();
 757        let mut highlighted_rows = None;
 758        let mut highlighted_ranges = Vec::new();
 759        self.update_view(cx.app, |view, cx| {
 760            let display_map = view.display_map.update(cx, |map, cx| map.snapshot(cx));
 761
 762            highlighted_rows = view.highlighted_rows();
 763            highlighted_ranges = view.highlighted_ranges_in_range(
 764                start_anchor.clone()..end_anchor.clone(),
 765                &display_map,
 766            );
 767
 768            let local_selections = view
 769                .local_selections_in_range(start_anchor.clone()..end_anchor.clone(), &display_map);
 770            for selection in &local_selections {
 771                let is_empty = selection.start == selection.end;
 772                let selection_start = snapshot.prev_line_boundary(selection.start).1;
 773                let selection_end = snapshot.next_line_boundary(selection.end).1;
 774                for row in cmp::max(selection_start.row(), start_row)
 775                    ..=cmp::min(selection_end.row(), end_row)
 776                {
 777                    let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
 778                    *contains_non_empty_selection |= !is_empty;
 779                }
 780            }
 781            selections.insert(
 782                view.replica_id(cx),
 783                local_selections
 784                    .into_iter()
 785                    .map(|selection| crate::Selection {
 786                        id: selection.id,
 787                        goal: selection.goal,
 788                        reversed: selection.reversed,
 789                        start: selection.start.to_display_point(&display_map),
 790                        end: selection.end.to_display_point(&display_map),
 791                    })
 792                    .collect(),
 793            );
 794
 795            for (replica_id, selection) in display_map
 796                .buffer_snapshot
 797                .remote_selections_in_range(&(start_anchor..end_anchor))
 798            {
 799                selections
 800                    .entry(replica_id)
 801                    .or_insert(Vec::new())
 802                    .push(crate::Selection {
 803                        id: selection.id,
 804                        goal: selection.goal,
 805                        reversed: selection.reversed,
 806                        start: selection.start.to_display_point(&display_map),
 807                        end: selection.end.to_display_point(&display_map),
 808                    });
 809            }
 810        });
 811
 812        let line_number_layouts =
 813            self.layout_line_numbers(start_row..end_row, &active_rows, &snapshot, cx);
 814
 815        let mut max_visible_line_width = 0.0;
 816        let line_layouts = self.layout_lines(start_row..end_row, &mut snapshot, cx);
 817        for line in &line_layouts {
 818            if line.width() > max_visible_line_width {
 819                max_visible_line_width = line.width();
 820            }
 821        }
 822
 823        let style = self.settings.style.clone();
 824        let longest_line_width = layout_line(
 825            snapshot.longest_row(),
 826            &snapshot,
 827            &style,
 828            cx.text_layout_cache,
 829        )
 830        .width();
 831        let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
 832        let em_width = style.text.em_width(cx.font_cache);
 833        let max_row = snapshot.max_point().row();
 834        let scroll_max = vec2f(
 835            ((scroll_width - text_size.x()) / em_width).max(0.0),
 836            max_row.saturating_sub(1) as f32,
 837        );
 838
 839        let mut completions = None;
 840        self.update_view(cx.app, |view, cx| {
 841            let clamped = view.clamp_scroll_left(scroll_max.x());
 842            let autoscrolled;
 843            if autoscroll_horizontally {
 844                autoscrolled = view.autoscroll_horizontally(
 845                    start_row,
 846                    text_size.x(),
 847                    scroll_width,
 848                    em_width,
 849                    &line_layouts,
 850                    cx,
 851                );
 852            } else {
 853                autoscrolled = false;
 854            }
 855
 856            if clamped || autoscrolled {
 857                snapshot = view.snapshot(cx);
 858            }
 859
 860            completions = view.render_completions();
 861        });
 862
 863        let blocks = self.layout_blocks(
 864            start_row..end_row,
 865            &snapshot,
 866            size.x().max(scroll_width + gutter_width),
 867            gutter_padding,
 868            gutter_width,
 869            em_width,
 870            gutter_width + text_offset.x(),
 871            line_height,
 872            &style,
 873            &line_layouts,
 874            cx,
 875        );
 876
 877        (
 878            size,
 879            Some(LayoutState {
 880                size,
 881                scroll_max,
 882                gutter_size,
 883                gutter_padding,
 884                text_size,
 885                text_offset,
 886                snapshot,
 887                active_rows,
 888                highlighted_rows,
 889                highlighted_ranges,
 890                line_layouts,
 891                line_number_layouts,
 892                blocks,
 893                line_height,
 894                em_width,
 895                em_advance,
 896                selections,
 897                completions,
 898            }),
 899        )
 900    }
 901
 902    fn paint(
 903        &mut self,
 904        bounds: RectF,
 905        visible_bounds: RectF,
 906        layout: &mut Self::LayoutState,
 907        cx: &mut PaintContext,
 908    ) -> Self::PaintState {
 909        let layout = layout.as_mut()?;
 910        cx.scene.push_layer(Some(bounds));
 911
 912        let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
 913        let text_bounds = RectF::new(
 914            bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
 915            layout.text_size,
 916        );
 917
 918        self.paint_background(gutter_bounds, text_bounds, layout, cx);
 919        if layout.gutter_size.x() > 0. {
 920            self.paint_gutter(gutter_bounds, visible_bounds, layout, cx);
 921        }
 922        self.paint_text(text_bounds, visible_bounds, layout, cx);
 923
 924        if !layout.blocks.is_empty() {
 925            cx.scene.push_layer(Some(bounds));
 926            self.paint_blocks(bounds, visible_bounds, layout, cx);
 927            cx.scene.pop_layer();
 928        }
 929
 930        cx.scene.pop_layer();
 931
 932        Some(PaintState {
 933            bounds,
 934            gutter_bounds,
 935            text_bounds,
 936        })
 937    }
 938
 939    fn dispatch_event(
 940        &mut self,
 941        event: &Event,
 942        _: RectF,
 943        layout: &mut Self::LayoutState,
 944        paint: &mut Self::PaintState,
 945        cx: &mut EventContext,
 946    ) -> bool {
 947        if let (Some(layout), Some(paint)) = (layout, paint) {
 948            match event {
 949                Event::LeftMouseDown {
 950                    position,
 951                    alt,
 952                    shift,
 953                    click_count,
 954                    ..
 955                } => self.mouse_down(*position, *alt, *shift, *click_count, layout, paint, cx),
 956                Event::LeftMouseUp { position } => self.mouse_up(*position, cx),
 957                Event::LeftMouseDragged { position } => {
 958                    self.mouse_dragged(*position, layout, paint, cx)
 959                }
 960                Event::ScrollWheel {
 961                    position,
 962                    delta,
 963                    precise,
 964                } => self.scroll(*position, *delta, *precise, layout, paint, cx),
 965                Event::KeyDown {
 966                    chars, keystroke, ..
 967                } => self.key_down(chars, keystroke, cx),
 968                _ => false,
 969            }
 970        } else {
 971            false
 972        }
 973    }
 974
 975    fn debug(
 976        &self,
 977        bounds: RectF,
 978        _: &Self::LayoutState,
 979        _: &Self::PaintState,
 980        _: &gpui::DebugContext,
 981    ) -> json::Value {
 982        json!({
 983            "type": "BufferElement",
 984            "bounds": bounds.to_json()
 985        })
 986    }
 987}
 988
 989pub struct LayoutState {
 990    size: Vector2F,
 991    scroll_max: Vector2F,
 992    gutter_size: Vector2F,
 993    gutter_padding: f32,
 994    text_size: Vector2F,
 995    snapshot: EditorSnapshot,
 996    active_rows: BTreeMap<u32, bool>,
 997    highlighted_rows: Option<Range<u32>>,
 998    line_layouts: Vec<text_layout::Line>,
 999    line_number_layouts: Vec<Option<text_layout::Line>>,
1000    blocks: Vec<(u32, ElementBox)>,
1001    line_height: f32,
1002    em_width: f32,
1003    em_advance: f32,
1004    highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
1005    selections: HashMap<ReplicaId, Vec<text::Selection<DisplayPoint>>>,
1006    text_offset: Vector2F,
1007    completions: Option<ElementBox>,
1008}
1009
1010fn layout_line(
1011    row: u32,
1012    snapshot: &EditorSnapshot,
1013    style: &EditorStyle,
1014    layout_cache: &TextLayoutCache,
1015) -> text_layout::Line {
1016    let mut line = snapshot.line(row);
1017
1018    if line.len() > MAX_LINE_LEN {
1019        let mut len = MAX_LINE_LEN;
1020        while !line.is_char_boundary(len) {
1021            len -= 1;
1022        }
1023        line.truncate(len);
1024    }
1025
1026    layout_cache.layout_str(
1027        &line,
1028        style.text.font_size,
1029        &[(
1030            snapshot.line_len(row) as usize,
1031            RunStyle {
1032                font_id: style.text.font_id,
1033                color: Color::black(),
1034                underline: None,
1035            },
1036        )],
1037    )
1038}
1039
1040pub struct PaintState {
1041    bounds: RectF,
1042    gutter_bounds: RectF,
1043    text_bounds: RectF,
1044}
1045
1046impl PaintState {
1047    fn point_for_position(
1048        &self,
1049        snapshot: &EditorSnapshot,
1050        layout: &LayoutState,
1051        position: Vector2F,
1052    ) -> (DisplayPoint, u32) {
1053        let scroll_position = snapshot.scroll_position();
1054        let position = position - self.text_bounds.origin();
1055        let y = position.y().max(0.0).min(layout.size.y());
1056        let row = ((y / layout.line_height) + scroll_position.y()) as u32;
1057        let row = cmp::min(row, snapshot.max_point().row());
1058        let line = &layout.line_layouts[(row - scroll_position.y() as u32) as usize];
1059        let x = position.x() + (scroll_position.x() * layout.em_width);
1060
1061        let column = if x >= 0.0 {
1062            line.index_for_x(x)
1063                .map(|ix| ix as u32)
1064                .unwrap_or_else(|| snapshot.line_len(row))
1065        } else {
1066            0
1067        };
1068        let overshoot = (0f32.max(x - line.width()) / layout.em_advance) as u32;
1069
1070        (DisplayPoint::new(row, column), overshoot)
1071    }
1072}
1073
1074struct Cursor {
1075    origin: Vector2F,
1076    line_height: f32,
1077    color: Color,
1078}
1079
1080impl Cursor {
1081    fn paint(&self, cx: &mut PaintContext) {
1082        cx.scene.push_quad(Quad {
1083            bounds: RectF::new(self.origin, vec2f(2.0, self.line_height)),
1084            background: Some(self.color),
1085            border: Border::new(0., Color::black()),
1086            corner_radius: 0.,
1087        });
1088    }
1089}
1090
1091#[derive(Debug)]
1092struct HighlightedRange {
1093    start_y: f32,
1094    line_height: f32,
1095    lines: Vec<HighlightedRangeLine>,
1096    color: Color,
1097    corner_radius: f32,
1098}
1099
1100#[derive(Debug)]
1101struct HighlightedRangeLine {
1102    start_x: f32,
1103    end_x: f32,
1104}
1105
1106impl HighlightedRange {
1107    fn paint(&self, bounds: RectF, scene: &mut Scene) {
1108        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
1109            self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
1110            self.paint_lines(
1111                self.start_y + self.line_height,
1112                &self.lines[1..],
1113                bounds,
1114                scene,
1115            );
1116        } else {
1117            self.paint_lines(self.start_y, &self.lines, bounds, scene);
1118        }
1119    }
1120
1121    fn paint_lines(
1122        &self,
1123        start_y: f32,
1124        lines: &[HighlightedRangeLine],
1125        bounds: RectF,
1126        scene: &mut Scene,
1127    ) {
1128        if lines.is_empty() {
1129            return;
1130        }
1131
1132        let mut path = PathBuilder::new();
1133        let first_line = lines.first().unwrap();
1134        let last_line = lines.last().unwrap();
1135
1136        let first_top_left = vec2f(first_line.start_x, start_y);
1137        let first_top_right = vec2f(first_line.end_x, start_y);
1138
1139        let curve_height = vec2f(0., self.corner_radius);
1140        let curve_width = |start_x: f32, end_x: f32| {
1141            let max = (end_x - start_x) / 2.;
1142            let width = if max < self.corner_radius {
1143                max
1144            } else {
1145                self.corner_radius
1146            };
1147
1148            vec2f(width, 0.)
1149        };
1150
1151        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
1152        path.reset(first_top_right - top_curve_width);
1153        path.curve_to(first_top_right + curve_height, first_top_right);
1154
1155        let mut iter = lines.iter().enumerate().peekable();
1156        while let Some((ix, line)) = iter.next() {
1157            let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
1158
1159            if let Some((_, next_line)) = iter.peek() {
1160                let next_top_right = vec2f(next_line.end_x, bottom_right.y());
1161
1162                match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
1163                    Ordering::Equal => {
1164                        path.line_to(bottom_right);
1165                    }
1166                    Ordering::Less => {
1167                        let curve_width = curve_width(next_top_right.x(), bottom_right.x());
1168                        path.line_to(bottom_right - curve_height);
1169                        if self.corner_radius > 0. {
1170                            path.curve_to(bottom_right - curve_width, bottom_right);
1171                        }
1172                        path.line_to(next_top_right + curve_width);
1173                        if self.corner_radius > 0. {
1174                            path.curve_to(next_top_right + curve_height, next_top_right);
1175                        }
1176                    }
1177                    Ordering::Greater => {
1178                        let curve_width = curve_width(bottom_right.x(), next_top_right.x());
1179                        path.line_to(bottom_right - curve_height);
1180                        if self.corner_radius > 0. {
1181                            path.curve_to(bottom_right + curve_width, bottom_right);
1182                        }
1183                        path.line_to(next_top_right - curve_width);
1184                        if self.corner_radius > 0. {
1185                            path.curve_to(next_top_right + curve_height, next_top_right);
1186                        }
1187                    }
1188                }
1189            } else {
1190                let curve_width = curve_width(line.start_x, line.end_x);
1191                path.line_to(bottom_right - curve_height);
1192                if self.corner_radius > 0. {
1193                    path.curve_to(bottom_right - curve_width, bottom_right);
1194                }
1195
1196                let bottom_left = vec2f(line.start_x, bottom_right.y());
1197                path.line_to(bottom_left + curve_width);
1198                if self.corner_radius > 0. {
1199                    path.curve_to(bottom_left - curve_height, bottom_left);
1200                }
1201            }
1202        }
1203
1204        if first_line.start_x > last_line.start_x {
1205            let curve_width = curve_width(last_line.start_x, first_line.start_x);
1206            let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
1207            path.line_to(second_top_left + curve_height);
1208            if self.corner_radius > 0. {
1209                path.curve_to(second_top_left + curve_width, second_top_left);
1210            }
1211            let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
1212            path.line_to(first_bottom_left - curve_width);
1213            if self.corner_radius > 0. {
1214                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
1215            }
1216        }
1217
1218        path.line_to(first_top_left + curve_height);
1219        if self.corner_radius > 0. {
1220            path.curve_to(first_top_left + top_curve_width, first_top_left);
1221        }
1222        path.line_to(first_top_right - top_curve_width);
1223
1224        scene.push_path(path.build(self.color, Some(bounds)));
1225    }
1226}
1227
1228fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
1229    delta.powf(1.5) / 100.0
1230}
1231
1232fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
1233    delta.powf(1.2) / 300.0
1234}
1235
1236#[cfg(test)]
1237mod tests {
1238    use super::*;
1239    use crate::{Editor, EditorSettings, MultiBuffer};
1240    use std::sync::Arc;
1241    use util::test::sample_text;
1242
1243    #[gpui::test]
1244    fn test_layout_line_numbers(cx: &mut gpui::MutableAppContext) {
1245        let settings = EditorSettings::test(cx);
1246        let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
1247        let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1248            Editor::for_buffer(
1249                buffer,
1250                {
1251                    let settings = settings.clone();
1252                    Arc::new(move |_| settings.clone())
1253                },
1254                cx,
1255            )
1256        });
1257        let element = EditorElement::new(editor.downgrade(), settings);
1258
1259        let layouts = editor.update(cx, |editor, cx| {
1260            let snapshot = editor.snapshot(cx);
1261            let mut presenter = cx.build_presenter(window_id, 30.);
1262            let mut layout_cx = presenter.build_layout_context(false, cx);
1263            element.layout_line_numbers(0..6, &Default::default(), &snapshot, &mut layout_cx)
1264        });
1265        assert_eq!(layouts.len(), 6);
1266    }
1267}