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