element.rs

   1use super::{
   2    DisplayPoint, DisplayRow, Editor, EditorMode, EditorSettings, EditorStyle, Input, Scroll,
   3    Select, SelectPhase, Snapshot, MAX_LINE_LEN,
   4};
   5use clock::ReplicaId;
   6use gpui::{
   7    color::Color,
   8    geometry::{
   9        rect::RectF,
  10        vector::{vec2f, Vector2F},
  11        PathBuilder,
  12    },
  13    json::{self, ToJson},
  14    keymap::Keystroke,
  15    text_layout::{self, RunStyle, TextLayoutCache},
  16    AppContext, Axis, Border, Element, Event, EventContext, FontCache, LayoutContext,
  17    MutableAppContext, PaintContext, Quad, Scene, SizeConstraint, ViewContext, WeakViewHandle,
  18};
  19use json::json;
  20use language::Chunk;
  21use smallvec::SmallVec;
  22use std::{
  23    cmp::{self, Ordering},
  24    collections::{BTreeMap, HashMap},
  25    fmt::Write,
  26    ops::Range,
  27};
  28use theme::BlockStyle;
  29
  30pub struct EditorElement {
  31    view: WeakViewHandle<Editor>,
  32    settings: EditorSettings,
  33}
  34
  35impl EditorElement {
  36    pub fn new(view: WeakViewHandle<Editor>, settings: EditorSettings) -> Self {
  37        Self { view, settings }
  38    }
  39
  40    fn view<'a>(&self, cx: &'a AppContext) -> &'a Editor {
  41        self.view.upgrade(cx).unwrap().read(cx)
  42    }
  43
  44    fn update_view<F, T>(&self, cx: &mut MutableAppContext, f: F) -> T
  45    where
  46        F: FnOnce(&mut Editor, &mut ViewContext<Editor>) -> T,
  47    {
  48        self.view.upgrade(cx).unwrap().update(cx, f)
  49    }
  50
  51    fn snapshot(&self, cx: &mut MutableAppContext) -> Snapshot {
  52        self.update_view(cx, |view, cx| view.snapshot(cx))
  53    }
  54
  55    fn mouse_down(
  56        &self,
  57        position: Vector2F,
  58        alt: bool,
  59        shift: bool,
  60        mut click_count: usize,
  61        layout: &mut LayoutState,
  62        paint: &mut PaintState,
  63        cx: &mut EventContext,
  64    ) -> bool {
  65        if paint.gutter_bounds.contains_point(position) {
  66            click_count = 3; // Simulate triple-click when clicking the gutter to select lines
  67        } else if !paint.text_bounds.contains_point(position) {
  68            return false;
  69        }
  70
  71        let snapshot = self.snapshot(cx.app);
  72        let (position, overshoot) = paint.point_for_position(&snapshot, layout, position);
  73
  74        if shift && alt {
  75            cx.dispatch_action(Select(SelectPhase::BeginColumnar {
  76                position,
  77                overshoot,
  78            }));
  79        } else if shift {
  80            cx.dispatch_action(Select(SelectPhase::Extend {
  81                position,
  82                click_count,
  83            }));
  84        } else {
  85            cx.dispatch_action(Select(SelectPhase::Begin {
  86                position,
  87                add: alt,
  88                click_count,
  89            }));
  90        }
  91
  92        true
  93    }
  94
  95    fn mouse_up(&self, _position: Vector2F, cx: &mut EventContext) -> bool {
  96        if self.view(cx.app.as_ref()).is_selecting() {
  97            cx.dispatch_action(Select(SelectPhase::End));
  98            true
  99        } else {
 100            false
 101        }
 102    }
 103
 104    fn mouse_dragged(
 105        &self,
 106        position: Vector2F,
 107        layout: &mut LayoutState,
 108        paint: &mut PaintState,
 109        cx: &mut EventContext,
 110    ) -> bool {
 111        let view = self.view(cx.app.as_ref());
 112
 113        if view.is_selecting() {
 114            let rect = paint.text_bounds;
 115            let mut scroll_delta = Vector2F::zero();
 116
 117            let vertical_margin = layout.line_height.min(rect.height() / 3.0);
 118            let top = rect.origin_y() + vertical_margin;
 119            let bottom = rect.lower_left().y() - vertical_margin;
 120            if position.y() < top {
 121                scroll_delta.set_y(-scale_vertical_mouse_autoscroll_delta(top - position.y()))
 122            }
 123            if position.y() > bottom {
 124                scroll_delta.set_y(scale_vertical_mouse_autoscroll_delta(position.y() - bottom))
 125            }
 126
 127            let horizontal_margin = layout.line_height.min(rect.width() / 3.0);
 128            let left = rect.origin_x() + horizontal_margin;
 129            let right = rect.upper_right().x() - horizontal_margin;
 130            if position.x() < left {
 131                scroll_delta.set_x(-scale_horizontal_mouse_autoscroll_delta(
 132                    left - position.x(),
 133                ))
 134            }
 135            if position.x() > right {
 136                scroll_delta.set_x(scale_horizontal_mouse_autoscroll_delta(
 137                    position.x() - right,
 138                ))
 139            }
 140
 141            let font_cache = cx.font_cache.clone();
 142            let text_layout_cache = cx.text_layout_cache.clone();
 143            let snapshot = self.snapshot(cx.app);
 144            let (position, overshoot) = paint.point_for_position(&snapshot, layout, position);
 145
 146            cx.dispatch_action(Select(SelectPhase::Update {
 147                position,
 148                overshoot,
 149                scroll_position: (snapshot.scroll_position() + scroll_delta).clamp(
 150                    Vector2F::zero(),
 151                    layout.scroll_max(&font_cache, &text_layout_cache),
 152                ),
 153            }));
 154            true
 155        } else {
 156            false
 157        }
 158    }
 159
 160    fn key_down(&self, chars: &str, keystroke: &Keystroke, cx: &mut EventContext) -> bool {
 161        let view = self.view.upgrade(cx.app).unwrap();
 162
 163        if view.is_focused(cx.app) {
 164            if chars.is_empty() {
 165                false
 166            } else {
 167                if chars.chars().any(|c| c.is_control()) || keystroke.cmd || keystroke.ctrl {
 168                    false
 169                } else {
 170                    cx.dispatch_action(Input(chars.to_string()));
 171                    true
 172                }
 173            }
 174        } else {
 175            false
 176        }
 177    }
 178
 179    fn scroll(
 180        &self,
 181        position: Vector2F,
 182        mut delta: Vector2F,
 183        precise: bool,
 184        layout: &mut LayoutState,
 185        paint: &mut PaintState,
 186        cx: &mut EventContext,
 187    ) -> bool {
 188        if !paint.bounds.contains_point(position) {
 189            return false;
 190        }
 191
 192        let snapshot = self.snapshot(cx.app);
 193        let font_cache = &cx.font_cache;
 194        let layout_cache = &cx.text_layout_cache;
 195        let max_glyph_width = layout.em_width;
 196        if !precise {
 197            delta *= vec2f(max_glyph_width, layout.line_height);
 198        }
 199
 200        let scroll_position = snapshot.scroll_position();
 201        let x = (scroll_position.x() * max_glyph_width - delta.x()) / max_glyph_width;
 202        let y = (scroll_position.y() * layout.line_height - delta.y()) / layout.line_height;
 203        let scroll_position = vec2f(x, y).clamp(
 204            Vector2F::zero(),
 205            layout.scroll_max(font_cache, layout_cache),
 206        );
 207
 208        cx.dispatch_action(Scroll(scroll_position));
 209
 210        true
 211    }
 212
 213    fn paint_background(
 214        &self,
 215        gutter_bounds: RectF,
 216        text_bounds: RectF,
 217        layout: &LayoutState,
 218        cx: &mut PaintContext,
 219    ) {
 220        let bounds = gutter_bounds.union_rect(text_bounds);
 221        let scroll_top = layout.snapshot.scroll_position().y() * layout.line_height;
 222        let start_row = layout.snapshot.scroll_position().y() as u32;
 223        let editor = self.view(cx.app);
 224        let style = &self.settings.style;
 225        cx.scene.push_quad(Quad {
 226            bounds: gutter_bounds,
 227            background: Some(style.gutter_background),
 228            border: Border::new(0., Color::transparent_black()),
 229            corner_radius: 0.,
 230        });
 231        cx.scene.push_quad(Quad {
 232            bounds: text_bounds,
 233            background: Some(style.background),
 234            border: Border::new(0., Color::transparent_black()),
 235            corner_radius: 0.,
 236        });
 237
 238        if let EditorMode::Full = editor.mode {
 239            let mut active_rows = layout.active_rows.iter().peekable();
 240            while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
 241                let mut end_row = *start_row;
 242                while active_rows.peek().map_or(false, |r| {
 243                    *r.0 == end_row + 1 && r.1 == contains_non_empty_selection
 244                }) {
 245                    active_rows.next().unwrap();
 246                    end_row += 1;
 247                }
 248
 249                if !contains_non_empty_selection {
 250                    let origin = vec2f(
 251                        bounds.origin_x(),
 252                        bounds.origin_y() + (layout.line_height * *start_row as f32) - scroll_top,
 253                    );
 254                    let size = vec2f(
 255                        bounds.width(),
 256                        layout.line_height * (end_row - start_row + 1) as f32,
 257                    );
 258                    cx.scene.push_quad(Quad {
 259                        bounds: RectF::new(origin, size),
 260                        background: Some(style.active_line_background),
 261                        border: Border::default(),
 262                        corner_radius: 0.,
 263                    });
 264                }
 265            }
 266
 267            if let Some(highlighted_row) = layout.highlighted_row {
 268                let origin = vec2f(
 269                    bounds.origin_x(),
 270                    bounds.origin_y() + (layout.line_height * highlighted_row as f32) - scroll_top,
 271                );
 272                let size = vec2f(bounds.width(), layout.line_height);
 273                cx.scene.push_quad(Quad {
 274                    bounds: RectF::new(origin, size),
 275                    background: Some(style.highlighted_line_background),
 276                    border: Border::default(),
 277                    corner_radius: 0.,
 278                });
 279            }
 280        }
 281
 282        // Draw block backgrounds
 283        for (ixs, block_style) in &layout.block_layouts {
 284            let row = start_row + ixs.start;
 285            let offset = vec2f(0., row as f32 * layout.line_height - scroll_top);
 286            let height = ixs.len() as f32 * layout.line_height;
 287            cx.scene.push_quad(Quad {
 288                bounds: RectF::new(
 289                    text_bounds.origin() + offset,
 290                    vec2f(text_bounds.width(), height),
 291                ),
 292                background: block_style.background,
 293                border: block_style
 294                    .border
 295                    .map_or(Default::default(), |color| Border {
 296                        width: 1.,
 297                        color,
 298                        overlay: true,
 299                        top: true,
 300                        right: false,
 301                        bottom: true,
 302                        left: false,
 303                    }),
 304                corner_radius: 0.,
 305            });
 306            cx.scene.push_quad(Quad {
 307                bounds: RectF::new(
 308                    gutter_bounds.origin() + offset,
 309                    vec2f(gutter_bounds.width(), height),
 310                ),
 311                background: block_style.gutter_background,
 312                border: block_style
 313                    .gutter_border
 314                    .map_or(Default::default(), |color| Border {
 315                        width: 1.,
 316                        color,
 317                        overlay: true,
 318                        top: true,
 319                        right: false,
 320                        bottom: true,
 321                        left: false,
 322                    }),
 323                corner_radius: 0.,
 324            });
 325        }
 326    }
 327
 328    fn paint_gutter(
 329        &mut self,
 330        bounds: RectF,
 331        visible_bounds: RectF,
 332        layout: &LayoutState,
 333        cx: &mut PaintContext,
 334    ) {
 335        let scroll_top = layout.snapshot.scroll_position().y() * layout.line_height;
 336        for (ix, line) in layout.line_number_layouts.iter().enumerate() {
 337            if let Some(line) = line {
 338                let line_origin = bounds.origin()
 339                    + vec2f(
 340                        bounds.width() - line.width() - layout.gutter_padding,
 341                        ix as f32 * layout.line_height - (scroll_top % layout.line_height),
 342                    );
 343                line.paint(line_origin, visible_bounds, layout.line_height, cx);
 344            }
 345        }
 346    }
 347
 348    fn paint_text(
 349        &mut self,
 350        bounds: RectF,
 351        visible_bounds: RectF,
 352        layout: &LayoutState,
 353        cx: &mut PaintContext,
 354    ) {
 355        let view = self.view(cx.app);
 356        let style = &self.settings.style;
 357        let local_replica_id = view.replica_id(cx);
 358        let scroll_position = layout.snapshot.scroll_position();
 359        let start_row = scroll_position.y() as u32;
 360        let scroll_top = scroll_position.y() * layout.line_height;
 361        let end_row = ((scroll_top + bounds.height()) / layout.line_height).ceil() as u32 + 1; // Add 1 to ensure selections bleed off screen
 362        let max_glyph_width = layout.em_width;
 363        let scroll_left = scroll_position.x() * max_glyph_width;
 364
 365        cx.scene.push_layer(Some(bounds));
 366
 367        // Draw selections
 368        let corner_radius = 2.5;
 369        let mut cursors = SmallVec::<[Cursor; 32]>::new();
 370
 371        let content_origin = bounds.origin() + layout.text_offset;
 372
 373        for (replica_id, selections) in &layout.selections {
 374            let style = 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 = text_width - text_offset.x() - overscroll.x() - em_width;
 707        let snapshot = self.update_view(cx.app, |view, cx| {
 708            if view.set_wrap_width(wrap_width, cx) {
 709                view.snapshot(cx)
 710            } else {
 711                snapshot
 712            }
 713        });
 714
 715        let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
 716        if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
 717            size.set_y(
 718                scroll_height
 719                    .min(constraint.max_along(Axis::Vertical))
 720                    .max(constraint.min_along(Axis::Vertical))
 721                    .min(line_height * max_lines as f32),
 722            )
 723        } else if size.y().is_infinite() {
 724            size.set_y(scroll_height);
 725        }
 726        let gutter_size = vec2f(gutter_width, size.y());
 727        let text_size = vec2f(text_width, size.y());
 728
 729        let (autoscroll_horizontally, mut snapshot) = self.update_view(cx.app, |view, cx| {
 730            let autoscroll_horizontally = view.autoscroll_vertically(size.y(), line_height, cx);
 731            let snapshot = view.snapshot(cx);
 732            (autoscroll_horizontally, snapshot)
 733        });
 734
 735        let scroll_position = snapshot.scroll_position();
 736        let start_row = scroll_position.y() as u32;
 737        let scroll_top = scroll_position.y() * line_height;
 738        let end_row = ((scroll_top + size.y()) / line_height).ceil() as u32 + 1; // Add 1 to ensure selections bleed off screen
 739
 740        let mut selections = HashMap::new();
 741        let mut active_rows = BTreeMap::new();
 742        let mut highlighted_row = None;
 743        self.update_view(cx.app, |view, cx| {
 744            highlighted_row = view.highlighted_row();
 745            for selection_set_id in view.active_selection_sets(cx).collect::<Vec<_>>() {
 746                let replica_selections = view
 747                    .intersecting_selections(
 748                        selection_set_id,
 749                        DisplayPoint::new(start_row, 0)..DisplayPoint::new(end_row, 0),
 750                        cx,
 751                    )
 752                    .collect::<Vec<_>>();
 753                for selection in &replica_selections {
 754                    if selection_set_id == view.selection_set_id {
 755                        let is_empty = selection.start == selection.end;
 756                        let selection_start = snapshot.prev_row_boundary(selection.start).0;
 757                        let selection_end = snapshot.next_row_boundary(selection.end).0;
 758                        for row in cmp::max(selection_start.row(), start_row)
 759                            ..=cmp::min(selection_end.row(), end_row)
 760                        {
 761                            let contains_non_empty_selection =
 762                                active_rows.entry(row).or_insert(!is_empty);
 763                            *contains_non_empty_selection |= !is_empty;
 764                        }
 765                    }
 766                }
 767
 768                selections.insert(selection_set_id.replica_id, replica_selections);
 769            }
 770        });
 771
 772        let (line_number_layouts, block_layouts) =
 773            self.layout_rows(start_row..end_row, &active_rows, &snapshot, cx);
 774
 775        let mut max_visible_line_width = 0.0;
 776        let line_layouts = self.layout_lines(start_row..end_row, &mut snapshot, cx);
 777        for line in &line_layouts {
 778            if line.width() > max_visible_line_width {
 779                max_visible_line_width = line.width();
 780            }
 781        }
 782
 783        let mut layout = LayoutState {
 784            size,
 785            gutter_size,
 786            gutter_padding,
 787            text_size,
 788            overscroll,
 789            text_offset,
 790            snapshot,
 791            style: self.settings.style.clone(),
 792            active_rows,
 793            highlighted_row,
 794            line_layouts,
 795            line_number_layouts,
 796            block_layouts,
 797            line_height,
 798            em_width,
 799            em_advance,
 800            selections,
 801            max_visible_line_width,
 802        };
 803
 804        let scroll_max = layout.scroll_max(cx.font_cache, cx.text_layout_cache).x();
 805        let scroll_width = layout.scroll_width(cx.text_layout_cache);
 806        let max_glyph_width = style.text.em_width(&cx.font_cache);
 807        self.update_view(cx.app, |view, cx| {
 808            let clamped = view.clamp_scroll_left(scroll_max);
 809            let autoscrolled;
 810            if autoscroll_horizontally {
 811                autoscrolled = view.autoscroll_horizontally(
 812                    start_row,
 813                    layout.text_size.x(),
 814                    scroll_width,
 815                    max_glyph_width,
 816                    &layout.line_layouts,
 817                    cx,
 818                );
 819            } else {
 820                autoscrolled = false;
 821            }
 822
 823            if clamped || autoscrolled {
 824                layout.snapshot = view.snapshot(cx);
 825            }
 826        });
 827
 828        (size, Some(layout))
 829    }
 830
 831    fn paint(
 832        &mut self,
 833        bounds: RectF,
 834        visible_bounds: RectF,
 835        layout: &mut Self::LayoutState,
 836        cx: &mut PaintContext,
 837    ) -> Self::PaintState {
 838        if let Some(layout) = layout {
 839            cx.scene.push_layer(Some(bounds));
 840
 841            let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
 842            let text_bounds = RectF::new(
 843                bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
 844                layout.text_size,
 845            );
 846
 847            self.paint_background(gutter_bounds, text_bounds, layout, cx);
 848            if layout.gutter_size.x() > 0. {
 849                self.paint_gutter(gutter_bounds, visible_bounds, layout, cx);
 850            }
 851            self.paint_text(text_bounds, visible_bounds, layout, cx);
 852
 853            cx.scene.pop_layer();
 854
 855            Some(PaintState {
 856                bounds,
 857                gutter_bounds,
 858                text_bounds,
 859            })
 860        } else {
 861            None
 862        }
 863    }
 864
 865    fn dispatch_event(
 866        &mut self,
 867        event: &Event,
 868        _: RectF,
 869        layout: &mut Self::LayoutState,
 870        paint: &mut Self::PaintState,
 871        cx: &mut EventContext,
 872    ) -> bool {
 873        if let (Some(layout), Some(paint)) = (layout, paint) {
 874            match event {
 875                Event::LeftMouseDown {
 876                    position,
 877                    alt,
 878                    shift,
 879                    click_count,
 880                    ..
 881                } => self.mouse_down(*position, *alt, *shift, *click_count, layout, paint, cx),
 882                Event::LeftMouseUp { position } => self.mouse_up(*position, cx),
 883                Event::LeftMouseDragged { position } => {
 884                    self.mouse_dragged(*position, layout, paint, cx)
 885                }
 886                Event::ScrollWheel {
 887                    position,
 888                    delta,
 889                    precise,
 890                } => self.scroll(*position, *delta, *precise, layout, paint, cx),
 891                Event::KeyDown {
 892                    chars, keystroke, ..
 893                } => self.key_down(chars, keystroke, cx),
 894                _ => false,
 895            }
 896        } else {
 897            false
 898        }
 899    }
 900
 901    fn debug(
 902        &self,
 903        bounds: RectF,
 904        _: &Self::LayoutState,
 905        _: &Self::PaintState,
 906        _: &gpui::DebugContext,
 907    ) -> json::Value {
 908        json!({
 909            "type": "BufferElement",
 910            "bounds": bounds.to_json()
 911        })
 912    }
 913}
 914
 915pub struct LayoutState {
 916    size: Vector2F,
 917    gutter_size: Vector2F,
 918    gutter_padding: f32,
 919    text_size: Vector2F,
 920    style: EditorStyle,
 921    snapshot: Snapshot,
 922    active_rows: BTreeMap<u32, bool>,
 923    highlighted_row: Option<u32>,
 924    line_layouts: Vec<text_layout::Line>,
 925    line_number_layouts: Vec<Option<text_layout::Line>>,
 926    block_layouts: Vec<(Range<u32>, BlockStyle)>,
 927    line_height: f32,
 928    em_width: f32,
 929    em_advance: f32,
 930    selections: HashMap<ReplicaId, Vec<buffer::Selection<DisplayPoint>>>,
 931    overscroll: Vector2F,
 932    text_offset: Vector2F,
 933    max_visible_line_width: f32,
 934}
 935
 936impl LayoutState {
 937    fn scroll_width(&self, layout_cache: &TextLayoutCache) -> f32 {
 938        let row = self.snapshot.longest_row();
 939        let longest_line_width = self.layout_line(row, &self.snapshot, layout_cache).width();
 940        longest_line_width.max(self.max_visible_line_width) + self.overscroll.x()
 941    }
 942
 943    fn scroll_max(&self, font_cache: &FontCache, layout_cache: &TextLayoutCache) -> Vector2F {
 944        let text_width = self.text_size.x();
 945        let scroll_width = self.scroll_width(layout_cache);
 946        let em_width = self.style.text.em_width(font_cache);
 947        let max_row = self.snapshot.max_point().row();
 948
 949        vec2f(
 950            ((scroll_width - text_width) / em_width).max(0.0),
 951            max_row.saturating_sub(1) as f32,
 952        )
 953    }
 954
 955    pub fn layout_line(
 956        &self,
 957        row: u32,
 958        snapshot: &Snapshot,
 959        layout_cache: &TextLayoutCache,
 960    ) -> text_layout::Line {
 961        let mut line = snapshot.line(row);
 962
 963        if line.len() > MAX_LINE_LEN {
 964            let mut len = MAX_LINE_LEN;
 965            while !line.is_char_boundary(len) {
 966                len -= 1;
 967            }
 968            line.truncate(len);
 969        }
 970
 971        layout_cache.layout_str(
 972            &line,
 973            self.style.text.font_size,
 974            &[(
 975                snapshot.line_len(row) as usize,
 976                RunStyle {
 977                    font_id: self.style.text.font_id,
 978                    color: Color::black(),
 979                    underline: None,
 980                },
 981            )],
 982        )
 983    }
 984}
 985
 986pub struct PaintState {
 987    bounds: RectF,
 988    gutter_bounds: RectF,
 989    text_bounds: RectF,
 990}
 991
 992impl PaintState {
 993    fn point_for_position(
 994        &self,
 995        snapshot: &Snapshot,
 996        layout: &LayoutState,
 997        position: Vector2F,
 998    ) -> (DisplayPoint, u32) {
 999        let scroll_position = snapshot.scroll_position();
1000        let position = position - self.text_bounds.origin();
1001        let y = position.y().max(0.0).min(layout.size.y());
1002        let row = ((y / layout.line_height) + scroll_position.y()) as u32;
1003        let row = cmp::min(row, snapshot.max_point().row());
1004        let line = &layout.line_layouts[(row - scroll_position.y() as u32) as usize];
1005        let x = position.x() + (scroll_position.x() * layout.em_width);
1006
1007        let column = if x >= 0.0 {
1008            line.index_for_x(x)
1009                .map(|ix| ix as u32)
1010                .unwrap_or_else(|| snapshot.line_len(row))
1011        } else {
1012            0
1013        };
1014        let overshoot = (0f32.max(x - line.width()) / layout.em_advance) as u32;
1015
1016        (DisplayPoint::new(row, column), overshoot)
1017    }
1018}
1019
1020struct Cursor {
1021    origin: Vector2F,
1022    line_height: f32,
1023    color: Color,
1024}
1025
1026impl Cursor {
1027    fn paint(&self, cx: &mut PaintContext) {
1028        cx.scene.push_quad(Quad {
1029            bounds: RectF::new(self.origin, vec2f(2.0, self.line_height)),
1030            background: Some(self.color),
1031            border: Border::new(0., Color::black()),
1032            corner_radius: 0.,
1033        });
1034    }
1035}
1036
1037#[derive(Debug)]
1038struct Selection {
1039    start_y: f32,
1040    line_height: f32,
1041    lines: Vec<SelectionLine>,
1042    color: Color,
1043}
1044
1045#[derive(Debug)]
1046struct SelectionLine {
1047    start_x: f32,
1048    end_x: f32,
1049}
1050
1051impl Selection {
1052    fn paint(&self, bounds: RectF, scene: &mut Scene) {
1053        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
1054            self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
1055            self.paint_lines(
1056                self.start_y + self.line_height,
1057                &self.lines[1..],
1058                bounds,
1059                scene,
1060            );
1061        } else {
1062            self.paint_lines(self.start_y, &self.lines, bounds, scene);
1063        }
1064    }
1065
1066    fn paint_lines(&self, start_y: f32, lines: &[SelectionLine], bounds: RectF, scene: &mut Scene) {
1067        if lines.is_empty() {
1068            return;
1069        }
1070
1071        let mut path = PathBuilder::new();
1072        let corner_radius = 0.15 * self.line_height;
1073        let first_line = lines.first().unwrap();
1074        let last_line = lines.last().unwrap();
1075
1076        let first_top_left = vec2f(first_line.start_x, start_y);
1077        let first_top_right = vec2f(first_line.end_x, start_y);
1078
1079        let curve_height = vec2f(0., corner_radius);
1080        let curve_width = |start_x: f32, end_x: f32| {
1081            let max = (end_x - start_x) / 2.;
1082            let width = if max < corner_radius {
1083                max
1084            } else {
1085                corner_radius
1086            };
1087
1088            vec2f(width, 0.)
1089        };
1090
1091        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
1092        path.reset(first_top_right - top_curve_width);
1093        path.curve_to(first_top_right + curve_height, first_top_right);
1094
1095        let mut iter = lines.iter().enumerate().peekable();
1096        while let Some((ix, line)) = iter.next() {
1097            let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
1098
1099            if let Some((_, next_line)) = iter.peek() {
1100                let next_top_right = vec2f(next_line.end_x, bottom_right.y());
1101
1102                match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
1103                    Ordering::Equal => {
1104                        path.line_to(bottom_right);
1105                    }
1106                    Ordering::Less => {
1107                        let curve_width = curve_width(next_top_right.x(), bottom_right.x());
1108                        path.line_to(bottom_right - curve_height);
1109                        path.curve_to(bottom_right - curve_width, bottom_right);
1110                        path.line_to(next_top_right + curve_width);
1111                        path.curve_to(next_top_right + curve_height, next_top_right);
1112                    }
1113                    Ordering::Greater => {
1114                        let curve_width = curve_width(bottom_right.x(), next_top_right.x());
1115                        path.line_to(bottom_right - curve_height);
1116                        path.curve_to(bottom_right + curve_width, bottom_right);
1117                        path.line_to(next_top_right - curve_width);
1118                        path.curve_to(next_top_right + curve_height, next_top_right);
1119                    }
1120                }
1121            } else {
1122                let curve_width = curve_width(line.start_x, line.end_x);
1123                path.line_to(bottom_right - curve_height);
1124                path.curve_to(bottom_right - curve_width, bottom_right);
1125
1126                let bottom_left = vec2f(line.start_x, bottom_right.y());
1127                path.line_to(bottom_left + curve_width);
1128                path.curve_to(bottom_left - curve_height, bottom_left);
1129            }
1130        }
1131
1132        if first_line.start_x > last_line.start_x {
1133            let curve_width = curve_width(last_line.start_x, first_line.start_x);
1134            let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
1135            path.line_to(second_top_left + curve_height);
1136            path.curve_to(second_top_left + curve_width, second_top_left);
1137            let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
1138            path.line_to(first_bottom_left - curve_width);
1139            path.curve_to(first_bottom_left - curve_height, first_bottom_left);
1140        }
1141
1142        path.line_to(first_top_left + curve_height);
1143        path.curve_to(first_top_left + top_curve_width, first_top_left);
1144        path.line_to(first_top_right - top_curve_width);
1145
1146        scene.push_path(path.build(self.color, Some(bounds)));
1147    }
1148}
1149
1150fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
1151    delta.powf(1.5) / 100.0
1152}
1153
1154fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
1155    delta.powf(1.2) / 300.0
1156}
1157
1158#[cfg(test)]
1159mod tests {
1160    use super::*;
1161    use crate::{
1162        test::sample_text,
1163        {Editor, EditorSettings},
1164    };
1165    use language::Buffer;
1166
1167    #[gpui::test]
1168    fn test_layout_line_numbers(cx: &mut gpui::MutableAppContext) {
1169        let settings = EditorSettings::test(cx);
1170
1171        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6), cx));
1172        let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1173            Editor::for_buffer(
1174                buffer,
1175                {
1176                    let settings = settings.clone();
1177                    move |_| settings.clone()
1178                },
1179                cx,
1180            )
1181        });
1182        let element = EditorElement::new(editor.downgrade(), settings);
1183
1184        let (layouts, _) = editor.update(cx, |editor, cx| {
1185            let snapshot = editor.snapshot(cx);
1186            let mut presenter = cx.build_presenter(window_id, 30.);
1187            let mut layout_cx = presenter.build_layout_context(false, cx);
1188            element.layout_rows(0..6, &Default::default(), &snapshot, &mut layout_cx)
1189        });
1190        assert_eq!(layouts.len(), 6);
1191    }
1192}