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