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                    gutter_width,
 621                    em_width,
 622                });
 623                element.layout(
 624                    SizeConstraint {
 625                        min: Vector2F::zero(),
 626                        max: vec2f(width, block.height() as f32 * line_height),
 627                    },
 628                    cx,
 629                );
 630                (start_row, element)
 631            })
 632            .collect()
 633    }
 634}
 635
 636impl Element for EditorElement {
 637    type LayoutState = Option<LayoutState>;
 638    type PaintState = Option<PaintState>;
 639
 640    fn layout(
 641        &mut self,
 642        constraint: SizeConstraint,
 643        cx: &mut LayoutContext,
 644    ) -> (Vector2F, Self::LayoutState) {
 645        let mut size = constraint.max;
 646        if size.x().is_infinite() {
 647            unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
 648        }
 649
 650        let snapshot = self.snapshot(cx.app);
 651        let style = self.settings.style.clone();
 652        let line_height = style.text.line_height(cx.font_cache);
 653
 654        let gutter_padding;
 655        let gutter_width;
 656        if snapshot.mode == EditorMode::Full {
 657            gutter_padding = style.text.em_width(cx.font_cache) * style.gutter_padding_factor;
 658            gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
 659        } else {
 660            gutter_padding = 0.0;
 661            gutter_width = 0.0
 662        };
 663
 664        let text_width = size.x() - gutter_width;
 665        let text_offset = vec2f(-style.text.descent(cx.font_cache), 0.);
 666        let em_width = style.text.em_width(cx.font_cache);
 667        let em_advance = style.text.em_advance(cx.font_cache);
 668        let overscroll = vec2f(em_width, 0.);
 669        let wrap_width = match self.settings.soft_wrap {
 670            SoftWrap::None => None,
 671            SoftWrap::EditorWidth => Some(text_width - text_offset.x() - overscroll.x() - em_width),
 672            SoftWrap::Column(column) => Some(column as f32 * em_advance),
 673        };
 674        let snapshot = self.update_view(cx.app, |view, cx| {
 675            if view.set_wrap_width(wrap_width, cx) {
 676                view.snapshot(cx)
 677            } else {
 678                snapshot
 679            }
 680        });
 681
 682        let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
 683        if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
 684            size.set_y(
 685                scroll_height
 686                    .min(constraint.max_along(Axis::Vertical))
 687                    .max(constraint.min_along(Axis::Vertical))
 688                    .min(line_height * max_lines as f32),
 689            )
 690        } else if size.y().is_infinite() {
 691            size.set_y(scroll_height);
 692        }
 693        let gutter_size = vec2f(gutter_width, size.y());
 694        let text_size = vec2f(text_width, size.y());
 695
 696        let (autoscroll_horizontally, mut snapshot) = self.update_view(cx.app, |view, cx| {
 697            let autoscroll_horizontally = view.autoscroll_vertically(size.y(), line_height, cx);
 698            let snapshot = view.snapshot(cx);
 699            (autoscroll_horizontally, snapshot)
 700        });
 701
 702        let scroll_position = snapshot.scroll_position();
 703        let start_row = scroll_position.y() as u32;
 704        let scroll_top = scroll_position.y() * line_height;
 705        let end_row = ((scroll_top + size.y()) / line_height).ceil() as u32 + 1; // Add 1 to ensure selections bleed off screen
 706
 707        let start_anchor = if start_row == 0 {
 708            Anchor::min()
 709        } else {
 710            snapshot
 711                .buffer_snapshot
 712                .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
 713        };
 714        let end_anchor = if end_row > snapshot.max_point().row() {
 715            Anchor::max()
 716        } else {
 717            snapshot
 718                .buffer_snapshot
 719                .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
 720        };
 721
 722        let mut selections = HashMap::default();
 723        let mut active_rows = BTreeMap::new();
 724        let mut highlighted_rows = None;
 725        self.update_view(cx.app, |view, cx| {
 726            highlighted_rows = view.highlighted_rows();
 727            let display_map = view.display_map.update(cx, |map, cx| map.snapshot(cx));
 728
 729            let local_selections = view
 730                .local_selections_in_range(start_anchor.clone()..end_anchor.clone(), &display_map);
 731            for selection in &local_selections {
 732                let is_empty = selection.start == selection.end;
 733                let selection_start = snapshot.prev_line_boundary(selection.start).1;
 734                let selection_end = snapshot.next_line_boundary(selection.end).1;
 735                for row in cmp::max(selection_start.row(), start_row)
 736                    ..=cmp::min(selection_end.row(), end_row)
 737                {
 738                    let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
 739                    *contains_non_empty_selection |= !is_empty;
 740                }
 741            }
 742            selections.insert(
 743                view.replica_id(cx),
 744                local_selections
 745                    .into_iter()
 746                    .map(|selection| crate::Selection {
 747                        id: selection.id,
 748                        goal: selection.goal,
 749                        reversed: selection.reversed,
 750                        start: selection.start.to_display_point(&display_map),
 751                        end: selection.end.to_display_point(&display_map),
 752                    })
 753                    .collect(),
 754            );
 755
 756            for (replica_id, selection) in display_map
 757                .buffer_snapshot
 758                .remote_selections_in_range(&(start_anchor..end_anchor))
 759            {
 760                selections
 761                    .entry(replica_id)
 762                    .or_insert(Vec::new())
 763                    .push(crate::Selection {
 764                        id: selection.id,
 765                        goal: selection.goal,
 766                        reversed: selection.reversed,
 767                        start: selection.start.to_display_point(&display_map),
 768                        end: selection.end.to_display_point(&display_map),
 769                    });
 770            }
 771        });
 772
 773        let line_number_layouts = self.layout_rows(start_row..end_row, &active_rows, &snapshot, cx);
 774
 775        let mut max_visible_line_width = 0.0;
 776        let line_layouts = self.layout_lines(start_row..end_row, &mut snapshot, cx);
 777        for line in &line_layouts {
 778            if line.width() > max_visible_line_width {
 779                max_visible_line_width = line.width();
 780            }
 781        }
 782
 783        let blocks = self.layout_blocks(
 784            start_row..end_row,
 785            &snapshot,
 786            size.x(),
 787            gutter_padding,
 788            gutter_width,
 789            em_width,
 790            gutter_width + text_offset.x(),
 791            line_height,
 792            &style,
 793            &line_layouts,
 794            cx,
 795        );
 796
 797        let mut layout = LayoutState {
 798            size,
 799            gutter_size,
 800            gutter_padding,
 801            text_size,
 802            overscroll,
 803            text_offset,
 804            snapshot,
 805            style: self.settings.style.clone(),
 806            active_rows,
 807            highlighted_rows,
 808            line_layouts,
 809            line_number_layouts,
 810            blocks,
 811            line_height,
 812            em_width,
 813            em_advance,
 814            selections,
 815            max_visible_line_width,
 816        };
 817
 818        let scroll_max = layout.scroll_max(cx.font_cache, cx.text_layout_cache).x();
 819        let scroll_width = layout.scroll_width(cx.text_layout_cache);
 820        let max_glyph_width = style.text.em_width(&cx.font_cache);
 821        self.update_view(cx.app, |view, cx| {
 822            let clamped = view.clamp_scroll_left(scroll_max);
 823            let autoscrolled;
 824            if autoscroll_horizontally {
 825                autoscrolled = view.autoscroll_horizontally(
 826                    start_row,
 827                    layout.text_size.x(),
 828                    scroll_width,
 829                    max_glyph_width,
 830                    &layout.line_layouts,
 831                    cx,
 832                );
 833            } else {
 834                autoscrolled = false;
 835            }
 836
 837            if clamped || autoscrolled {
 838                layout.snapshot = view.snapshot(cx);
 839            }
 840        });
 841
 842        (size, Some(layout))
 843    }
 844
 845    fn paint(
 846        &mut self,
 847        bounds: RectF,
 848        visible_bounds: RectF,
 849        layout: &mut Self::LayoutState,
 850        cx: &mut PaintContext,
 851    ) -> Self::PaintState {
 852        if let Some(layout) = layout {
 853            cx.scene.push_layer(Some(bounds));
 854
 855            let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
 856            let text_bounds = RectF::new(
 857                bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
 858                layout.text_size,
 859            );
 860
 861            self.paint_background(gutter_bounds, text_bounds, layout, cx);
 862            if layout.gutter_size.x() > 0. {
 863                self.paint_gutter(gutter_bounds, visible_bounds, layout, cx);
 864            }
 865            self.paint_text(text_bounds, visible_bounds, layout, cx);
 866            self.paint_blocks(bounds, visible_bounds, layout, cx);
 867
 868            cx.scene.pop_layer();
 869
 870            Some(PaintState {
 871                bounds,
 872                gutter_bounds,
 873                text_bounds,
 874            })
 875        } else {
 876            None
 877        }
 878    }
 879
 880    fn dispatch_event(
 881        &mut self,
 882        event: &Event,
 883        _: RectF,
 884        layout: &mut Self::LayoutState,
 885        paint: &mut Self::PaintState,
 886        cx: &mut EventContext,
 887    ) -> bool {
 888        if let (Some(layout), Some(paint)) = (layout, paint) {
 889            match event {
 890                Event::LeftMouseDown {
 891                    position,
 892                    alt,
 893                    shift,
 894                    click_count,
 895                    ..
 896                } => self.mouse_down(*position, *alt, *shift, *click_count, layout, paint, cx),
 897                Event::LeftMouseUp { position } => self.mouse_up(*position, cx),
 898                Event::LeftMouseDragged { position } => {
 899                    self.mouse_dragged(*position, layout, paint, cx)
 900                }
 901                Event::ScrollWheel {
 902                    position,
 903                    delta,
 904                    precise,
 905                } => self.scroll(*position, *delta, *precise, layout, paint, cx),
 906                Event::KeyDown {
 907                    chars, keystroke, ..
 908                } => self.key_down(chars, keystroke, cx),
 909                _ => false,
 910            }
 911        } else {
 912            false
 913        }
 914    }
 915
 916    fn debug(
 917        &self,
 918        bounds: RectF,
 919        _: &Self::LayoutState,
 920        _: &Self::PaintState,
 921        _: &gpui::DebugContext,
 922    ) -> json::Value {
 923        json!({
 924            "type": "BufferElement",
 925            "bounds": bounds.to_json()
 926        })
 927    }
 928}
 929
 930pub struct LayoutState {
 931    size: Vector2F,
 932    gutter_size: Vector2F,
 933    gutter_padding: f32,
 934    text_size: Vector2F,
 935    style: EditorStyle,
 936    snapshot: EditorSnapshot,
 937    active_rows: BTreeMap<u32, bool>,
 938    highlighted_rows: Option<Range<u32>>,
 939    line_layouts: Vec<text_layout::Line>,
 940    line_number_layouts: Vec<Option<text_layout::Line>>,
 941    blocks: Vec<(u32, ElementBox)>,
 942    line_height: f32,
 943    em_width: f32,
 944    em_advance: f32,
 945    selections: HashMap<ReplicaId, Vec<text::Selection<DisplayPoint>>>,
 946    overscroll: Vector2F,
 947    text_offset: Vector2F,
 948    max_visible_line_width: f32,
 949}
 950
 951impl LayoutState {
 952    fn scroll_width(&self, layout_cache: &TextLayoutCache) -> f32 {
 953        let row = self.snapshot.longest_row();
 954        let longest_line_width =
 955            layout_line(row, &self.snapshot, &self.style, layout_cache).width();
 956        longest_line_width.max(self.max_visible_line_width) + self.overscroll.x()
 957    }
 958
 959    fn scroll_max(&self, font_cache: &FontCache, layout_cache: &TextLayoutCache) -> Vector2F {
 960        let text_width = self.text_size.x();
 961        let scroll_width = self.scroll_width(layout_cache);
 962        let em_width = self.style.text.em_width(font_cache);
 963        let max_row = self.snapshot.max_point().row();
 964
 965        vec2f(
 966            ((scroll_width - text_width) / em_width).max(0.0),
 967            max_row.saturating_sub(1) as f32,
 968        )
 969    }
 970}
 971
 972fn layout_line(
 973    row: u32,
 974    snapshot: &EditorSnapshot,
 975    style: &EditorStyle,
 976    layout_cache: &TextLayoutCache,
 977) -> text_layout::Line {
 978    let mut line = snapshot.line(row);
 979
 980    if line.len() > MAX_LINE_LEN {
 981        let mut len = MAX_LINE_LEN;
 982        while !line.is_char_boundary(len) {
 983            len -= 1;
 984        }
 985        line.truncate(len);
 986    }
 987
 988    layout_cache.layout_str(
 989        &line,
 990        style.text.font_size,
 991        &[(
 992            snapshot.line_len(row) as usize,
 993            RunStyle {
 994                font_id: style.text.font_id,
 995                color: Color::black(),
 996                underline: None,
 997            },
 998        )],
 999    )
1000}
1001
1002pub struct PaintState {
1003    bounds: RectF,
1004    gutter_bounds: RectF,
1005    text_bounds: RectF,
1006}
1007
1008impl PaintState {
1009    fn point_for_position(
1010        &self,
1011        snapshot: &EditorSnapshot,
1012        layout: &LayoutState,
1013        position: Vector2F,
1014    ) -> (DisplayPoint, u32) {
1015        let scroll_position = snapshot.scroll_position();
1016        let position = position - self.text_bounds.origin();
1017        let y = position.y().max(0.0).min(layout.size.y());
1018        let row = ((y / layout.line_height) + scroll_position.y()) as u32;
1019        let row = cmp::min(row, snapshot.max_point().row());
1020        let line = &layout.line_layouts[(row - scroll_position.y() as u32) as usize];
1021        let x = position.x() + (scroll_position.x() * layout.em_width);
1022
1023        let column = if x >= 0.0 {
1024            line.index_for_x(x)
1025                .map(|ix| ix as u32)
1026                .unwrap_or_else(|| snapshot.line_len(row))
1027        } else {
1028            0
1029        };
1030        let overshoot = (0f32.max(x - line.width()) / layout.em_advance) as u32;
1031
1032        (DisplayPoint::new(row, column), overshoot)
1033    }
1034}
1035
1036struct Cursor {
1037    origin: Vector2F,
1038    line_height: f32,
1039    color: Color,
1040}
1041
1042impl Cursor {
1043    fn paint(&self, cx: &mut PaintContext) {
1044        cx.scene.push_quad(Quad {
1045            bounds: RectF::new(self.origin, vec2f(2.0, self.line_height)),
1046            background: Some(self.color),
1047            border: Border::new(0., Color::black()),
1048            corner_radius: 0.,
1049        });
1050    }
1051}
1052
1053#[derive(Debug)]
1054struct Selection {
1055    start_y: f32,
1056    line_height: f32,
1057    lines: Vec<SelectionLine>,
1058    color: Color,
1059}
1060
1061#[derive(Debug)]
1062struct SelectionLine {
1063    start_x: f32,
1064    end_x: f32,
1065}
1066
1067impl Selection {
1068    fn paint(&self, bounds: RectF, scene: &mut Scene) {
1069        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
1070            self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
1071            self.paint_lines(
1072                self.start_y + self.line_height,
1073                &self.lines[1..],
1074                bounds,
1075                scene,
1076            );
1077        } else {
1078            self.paint_lines(self.start_y, &self.lines, bounds, scene);
1079        }
1080    }
1081
1082    fn paint_lines(&self, start_y: f32, lines: &[SelectionLine], bounds: RectF, scene: &mut Scene) {
1083        if lines.is_empty() {
1084            return;
1085        }
1086
1087        let mut path = PathBuilder::new();
1088        let corner_radius = 0.15 * self.line_height;
1089        let first_line = lines.first().unwrap();
1090        let last_line = lines.last().unwrap();
1091
1092        let first_top_left = vec2f(first_line.start_x, start_y);
1093        let first_top_right = vec2f(first_line.end_x, start_y);
1094
1095        let curve_height = vec2f(0., corner_radius);
1096        let curve_width = |start_x: f32, end_x: f32| {
1097            let max = (end_x - start_x) / 2.;
1098            let width = if max < corner_radius {
1099                max
1100            } else {
1101                corner_radius
1102            };
1103
1104            vec2f(width, 0.)
1105        };
1106
1107        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
1108        path.reset(first_top_right - top_curve_width);
1109        path.curve_to(first_top_right + curve_height, first_top_right);
1110
1111        let mut iter = lines.iter().enumerate().peekable();
1112        while let Some((ix, line)) = iter.next() {
1113            let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
1114
1115            if let Some((_, next_line)) = iter.peek() {
1116                let next_top_right = vec2f(next_line.end_x, bottom_right.y());
1117
1118                match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
1119                    Ordering::Equal => {
1120                        path.line_to(bottom_right);
1121                    }
1122                    Ordering::Less => {
1123                        let curve_width = curve_width(next_top_right.x(), bottom_right.x());
1124                        path.line_to(bottom_right - curve_height);
1125                        path.curve_to(bottom_right - curve_width, bottom_right);
1126                        path.line_to(next_top_right + curve_width);
1127                        path.curve_to(next_top_right + curve_height, next_top_right);
1128                    }
1129                    Ordering::Greater => {
1130                        let curve_width = curve_width(bottom_right.x(), next_top_right.x());
1131                        path.line_to(bottom_right - curve_height);
1132                        path.curve_to(bottom_right + curve_width, bottom_right);
1133                        path.line_to(next_top_right - curve_width);
1134                        path.curve_to(next_top_right + curve_height, next_top_right);
1135                    }
1136                }
1137            } else {
1138                let curve_width = curve_width(line.start_x, line.end_x);
1139                path.line_to(bottom_right - curve_height);
1140                path.curve_to(bottom_right - curve_width, bottom_right);
1141
1142                let bottom_left = vec2f(line.start_x, bottom_right.y());
1143                path.line_to(bottom_left + curve_width);
1144                path.curve_to(bottom_left - curve_height, bottom_left);
1145            }
1146        }
1147
1148        if first_line.start_x > last_line.start_x {
1149            let curve_width = curve_width(last_line.start_x, first_line.start_x);
1150            let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
1151            path.line_to(second_top_left + curve_height);
1152            path.curve_to(second_top_left + curve_width, second_top_left);
1153            let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
1154            path.line_to(first_bottom_left - curve_width);
1155            path.curve_to(first_bottom_left - curve_height, first_bottom_left);
1156        }
1157
1158        path.line_to(first_top_left + curve_height);
1159        path.curve_to(first_top_left + top_curve_width, first_top_left);
1160        path.line_to(first_top_right - top_curve_width);
1161
1162        scene.push_path(path.build(self.color, Some(bounds)));
1163    }
1164}
1165
1166fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
1167    delta.powf(1.5) / 100.0
1168}
1169
1170fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
1171    delta.powf(1.2) / 300.0
1172}
1173
1174#[cfg(test)]
1175mod tests {
1176    use super::*;
1177    use crate::{Editor, EditorSettings, MultiBuffer};
1178    use std::sync::Arc;
1179    use util::test::sample_text;
1180
1181    #[gpui::test]
1182    fn test_layout_line_numbers(cx: &mut gpui::MutableAppContext) {
1183        let settings = EditorSettings::test(cx);
1184        let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
1185        let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1186            Editor::for_buffer(
1187                buffer,
1188                {
1189                    let settings = settings.clone();
1190                    Arc::new(move |_| settings.clone())
1191                },
1192                cx,
1193            )
1194        });
1195        let element = EditorElement::new(editor.downgrade(), settings);
1196
1197        let layouts = editor.update(cx, |editor, cx| {
1198            let snapshot = editor.snapshot(cx);
1199            let mut presenter = cx.build_presenter(window_id, 30.);
1200            let mut layout_cx = presenter.build_layout_context(false, cx);
1201            element.layout_rows(0..6, &Default::default(), &snapshot, &mut layout_cx)
1202        });
1203        assert_eq!(layouts.len(), 6);
1204    }
1205}