element.rs

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