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