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