element.rs

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