element.rs

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