element.rs

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