element.rs

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