element.rs

   1use super::{
   2    display_map::{BlockContext, ToDisplayPoint},
   3    Anchor, DisplayPoint, Editor, EditorMode, EditorSnapshot, Input, Scroll, Select, SelectPhase,
   4    SoftWrap, ToPoint, MAX_LINE_LEN,
   5};
   6use crate::{display_map::TransformBlock, EditorStyle};
   7use clock::ReplicaId;
   8use collections::{BTreeMap, HashMap};
   9use gpui::{
  10    color::Color,
  11    elements::*,
  12    fonts::{HighlightStyle, Underline},
  13    geometry::{
  14        rect::RectF,
  15        vector::{vec2f, Vector2F},
  16        PathBuilder,
  17    },
  18    json::{self, ToJson},
  19    text_layout::{self, RunStyle, TextLayoutCache},
  20    AppContext, Axis, Border, Element, ElementBox, Event, EventContext, LayoutContext,
  21    MutableAppContext, PaintContext, Quad, Scene, SizeConstraint, ViewContext, WeakViewHandle,
  22};
  23use json::json;
  24use language::Bias;
  25use smallvec::SmallVec;
  26use std::{
  27    cmp::{self, Ordering},
  28    fmt::Write,
  29    ops::Range,
  30};
  31
  32pub struct EditorElement {
  33    view: WeakViewHandle<Editor>,
  34    style: EditorStyle,
  35}
  36
  37impl EditorElement {
  38    pub fn new(view: WeakViewHandle<Editor>, style: EditorStyle) -> Self {
  39        Self { view, style }
  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 snapshot = self.snapshot(cx.app);
 144            let (position, overshoot) = paint.point_for_position(&snapshot, layout, position);
 145
 146            cx.dispatch_action(Select(SelectPhase::Update {
 147                position,
 148                overshoot,
 149                scroll_position: (snapshot.scroll_position() + scroll_delta)
 150                    .clamp(Vector2F::zero(), layout.scroll_max),
 151            }));
 152            true
 153        } else {
 154            false
 155        }
 156    }
 157
 158    fn key_down(&self, input: Option<&str>, cx: &mut EventContext) -> bool {
 159        let view = self.view.upgrade(cx.app).unwrap();
 160
 161        if view.is_focused(cx.app) {
 162            if let Some(input) = input {
 163                cx.dispatch_action(Input(input.to_string()));
 164                true
 165            } else {
 166                false
 167            }
 168        } else {
 169            false
 170        }
 171    }
 172
 173    fn scroll(
 174        &self,
 175        position: Vector2F,
 176        mut delta: Vector2F,
 177        precise: bool,
 178        layout: &mut LayoutState,
 179        paint: &mut PaintState,
 180        cx: &mut EventContext,
 181    ) -> bool {
 182        if !paint.bounds.contains_point(position) {
 183            return false;
 184        }
 185
 186        let snapshot = self.snapshot(cx.app);
 187        let max_glyph_width = layout.em_width;
 188        if !precise {
 189            delta *= vec2f(max_glyph_width, layout.line_height);
 190        }
 191
 192        let scroll_position = snapshot.scroll_position();
 193        let x = (scroll_position.x() * max_glyph_width - delta.x()) / max_glyph_width;
 194        let y = (scroll_position.y() * layout.line_height - delta.y()) / layout.line_height;
 195        let scroll_position = vec2f(x, y).clamp(Vector2F::zero(), layout.scroll_max);
 196
 197        cx.dispatch_action(Scroll(scroll_position));
 198
 199        true
 200    }
 201
 202    fn paint_background(
 203        &self,
 204        gutter_bounds: RectF,
 205        text_bounds: RectF,
 206        layout: &LayoutState,
 207        cx: &mut PaintContext,
 208    ) {
 209        let bounds = gutter_bounds.union_rect(text_bounds);
 210        let scroll_top = layout.snapshot.scroll_position().y() * layout.line_height;
 211        let editor = self.view(cx.app);
 212        cx.scene.push_quad(Quad {
 213            bounds: gutter_bounds,
 214            background: Some(self.style.gutter_background),
 215            border: Border::new(0., Color::transparent_black()),
 216            corner_radius: 0.,
 217        });
 218        cx.scene.push_quad(Quad {
 219            bounds: text_bounds,
 220            background: Some(self.style.background),
 221            border: Border::new(0., Color::transparent_black()),
 222            corner_radius: 0.,
 223        });
 224
 225        if let EditorMode::Full = editor.mode {
 226            let mut active_rows = layout.active_rows.iter().peekable();
 227            while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
 228                let mut end_row = *start_row;
 229                while active_rows.peek().map_or(false, |r| {
 230                    *r.0 == end_row + 1 && r.1 == contains_non_empty_selection
 231                }) {
 232                    active_rows.next().unwrap();
 233                    end_row += 1;
 234                }
 235
 236                if !contains_non_empty_selection {
 237                    let origin = vec2f(
 238                        bounds.origin_x(),
 239                        bounds.origin_y() + (layout.line_height * *start_row as f32) - scroll_top,
 240                    );
 241                    let size = vec2f(
 242                        bounds.width(),
 243                        layout.line_height * (end_row - start_row + 1) as f32,
 244                    );
 245                    cx.scene.push_quad(Quad {
 246                        bounds: RectF::new(origin, size),
 247                        background: Some(self.style.active_line_background),
 248                        border: Border::default(),
 249                        corner_radius: 0.,
 250                    });
 251                }
 252            }
 253
 254            if let Some(highlighted_rows) = &layout.highlighted_rows {
 255                let origin = vec2f(
 256                    bounds.origin_x(),
 257                    bounds.origin_y() + (layout.line_height * highlighted_rows.start as f32)
 258                        - scroll_top,
 259                );
 260                let size = vec2f(
 261                    bounds.width(),
 262                    layout.line_height * highlighted_rows.len() as f32,
 263                );
 264                cx.scene.push_quad(Quad {
 265                    bounds: RectF::new(origin, size),
 266                    background: Some(self.style.highlighted_line_background),
 267                    border: Border::default(),
 268                    corner_radius: 0.,
 269                });
 270            }
 271        }
 272    }
 273
 274    fn paint_gutter(
 275        &mut self,
 276        bounds: RectF,
 277        visible_bounds: RectF,
 278        layout: &mut LayoutState,
 279        cx: &mut PaintContext,
 280    ) {
 281        let scroll_top = layout.snapshot.scroll_position().y() * layout.line_height;
 282        for (ix, line) in layout.line_number_layouts.iter().enumerate() {
 283            if let Some(line) = line {
 284                let line_origin = bounds.origin()
 285                    + vec2f(
 286                        bounds.width() - line.width() - layout.gutter_padding,
 287                        ix as f32 * layout.line_height - (scroll_top % layout.line_height),
 288                    );
 289                line.paint(line_origin, visible_bounds, layout.line_height, cx);
 290            }
 291        }
 292
 293        if let Some((row, indicator)) = layout.code_actions_indicator.as_mut() {
 294            let mut x = bounds.width() - layout.gutter_padding;
 295            let mut y = *row as f32 * layout.line_height - scroll_top;
 296            x += ((layout.gutter_padding + layout.gutter_margin) - indicator.size().x()) / 2.;
 297            y += (layout.line_height - indicator.size().y()) / 2.;
 298            indicator.paint(bounds.origin() + vec2f(x, y), visible_bounds, cx);
 299        }
 300    }
 301
 302    fn paint_text(
 303        &mut self,
 304        bounds: RectF,
 305        visible_bounds: RectF,
 306        layout: &mut LayoutState,
 307        cx: &mut PaintContext,
 308    ) {
 309        let view = self.view(cx.app);
 310        let style = &self.style;
 311        let local_replica_id = view.replica_id(cx);
 312        let scroll_position = layout.snapshot.scroll_position();
 313        let start_row = scroll_position.y() as u32;
 314        let scroll_top = scroll_position.y() * layout.line_height;
 315        let end_row = ((scroll_top + bounds.height()) / layout.line_height).ceil() as u32 + 1; // Add 1 to ensure selections bleed off screen
 316        let max_glyph_width = layout.em_width;
 317        let scroll_left = scroll_position.x() * max_glyph_width;
 318        let content_origin = bounds.origin() + vec2f(layout.gutter_margin, 0.);
 319
 320        cx.scene.push_layer(Some(bounds));
 321
 322        for (range, color) in &layout.highlighted_ranges {
 323            self.paint_highlighted_range(
 324                range.clone(),
 325                start_row,
 326                end_row,
 327                *color,
 328                0.,
 329                0.15 * layout.line_height,
 330                layout,
 331                content_origin,
 332                scroll_top,
 333                scroll_left,
 334                bounds,
 335                cx,
 336            );
 337        }
 338
 339        let mut cursors = SmallVec::<[Cursor; 32]>::new();
 340        for (replica_id, selections) in &layout.selections {
 341            let style = style.replica_selection_style(*replica_id);
 342            let corner_radius = 0.15 * layout.line_height;
 343
 344            for selection in selections {
 345                self.paint_highlighted_range(
 346                    selection.start..selection.end,
 347                    start_row,
 348                    end_row,
 349                    style.selection,
 350                    corner_radius,
 351                    corner_radius * 2.,
 352                    layout,
 353                    content_origin,
 354                    scroll_top,
 355                    scroll_left,
 356                    bounds,
 357                    cx,
 358                );
 359
 360                if view.show_local_cursors() || *replica_id != local_replica_id {
 361                    let cursor_position = selection.head();
 362                    if (start_row..end_row).contains(&cursor_position.row()) {
 363                        let cursor_row_layout =
 364                            &layout.line_layouts[(cursor_position.row() - start_row) as usize];
 365                        let x = cursor_row_layout.x_for_index(cursor_position.column() as usize)
 366                            - scroll_left;
 367                        let y = cursor_position.row() as f32 * layout.line_height - scroll_top;
 368                        cursors.push(Cursor {
 369                            color: style.cursor,
 370                            origin: content_origin + vec2f(x, y),
 371                            line_height: layout.line_height,
 372                        });
 373                    }
 374                }
 375            }
 376        }
 377
 378        if let Some(visible_text_bounds) = bounds.intersection(visible_bounds) {
 379            // Draw glyphs
 380            for (ix, line) in layout.line_layouts.iter().enumerate() {
 381                let row = start_row + ix as u32;
 382                line.paint(
 383                    content_origin
 384                        + vec2f(-scroll_left, row as f32 * layout.line_height - scroll_top),
 385                    visible_text_bounds,
 386                    layout.line_height,
 387                    cx,
 388                );
 389            }
 390        }
 391
 392        cx.scene.push_layer(Some(bounds));
 393        for cursor in cursors {
 394            cursor.paint(cx);
 395        }
 396        cx.scene.pop_layer();
 397
 398        if let Some((position, context_menu)) = layout.context_menu.as_mut() {
 399            cx.scene.push_stacking_context(None);
 400
 401            let cursor_row_layout = &layout.line_layouts[(position.row() - start_row) as usize];
 402            let x = cursor_row_layout.x_for_index(position.column() as usize) - scroll_left;
 403            let y = (position.row() + 1) as f32 * layout.line_height - scroll_top;
 404            let mut list_origin = content_origin + vec2f(x, y);
 405            let list_height = context_menu.size().y();
 406
 407            if list_origin.y() + list_height > bounds.lower_left().y() {
 408                list_origin.set_y(list_origin.y() - layout.line_height - list_height);
 409            }
 410
 411            context_menu.paint(
 412                list_origin,
 413                RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
 414                cx,
 415            );
 416
 417            cx.scene.pop_stacking_context();
 418        }
 419
 420        cx.scene.pop_layer();
 421    }
 422
 423    fn paint_highlighted_range(
 424        &self,
 425        range: Range<DisplayPoint>,
 426        start_row: u32,
 427        end_row: u32,
 428        color: Color,
 429        corner_radius: f32,
 430        line_end_overshoot: f32,
 431        layout: &LayoutState,
 432        content_origin: Vector2F,
 433        scroll_top: f32,
 434        scroll_left: f32,
 435        bounds: RectF,
 436        cx: &mut PaintContext,
 437    ) {
 438        if range.start != range.end {
 439            let row_range = if range.end.column() == 0 {
 440                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
 441            } else {
 442                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
 443            };
 444
 445            let highlighted_range = HighlightedRange {
 446                color,
 447                line_height: layout.line_height,
 448                corner_radius,
 449                start_y: content_origin.y() + row_range.start as f32 * layout.line_height
 450                    - scroll_top,
 451                lines: row_range
 452                    .into_iter()
 453                    .map(|row| {
 454                        let line_layout = &layout.line_layouts[(row - start_row) as usize];
 455                        HighlightedRangeLine {
 456                            start_x: if row == range.start.row() {
 457                                content_origin.x()
 458                                    + line_layout.x_for_index(range.start.column() as usize)
 459                                    - scroll_left
 460                            } else {
 461                                content_origin.x() - scroll_left
 462                            },
 463                            end_x: if row == range.end.row() {
 464                                content_origin.x()
 465                                    + line_layout.x_for_index(range.end.column() as usize)
 466                                    - scroll_left
 467                            } else {
 468                                content_origin.x() + line_layout.width() + line_end_overshoot
 469                                    - scroll_left
 470                            },
 471                        }
 472                    })
 473                    .collect(),
 474            };
 475
 476            highlighted_range.paint(bounds, cx.scene);
 477        }
 478    }
 479
 480    fn paint_blocks(
 481        &mut self,
 482        bounds: RectF,
 483        visible_bounds: RectF,
 484        layout: &mut LayoutState,
 485        cx: &mut PaintContext,
 486    ) {
 487        let scroll_position = layout.snapshot.scroll_position();
 488        let scroll_left = scroll_position.x() * layout.em_width;
 489        let scroll_top = scroll_position.y() * layout.line_height;
 490
 491        for (row, element) in &mut layout.blocks {
 492            let origin = bounds.origin()
 493                + vec2f(-scroll_left, *row as f32 * layout.line_height - scroll_top);
 494            element.paint(origin, visible_bounds, cx);
 495        }
 496    }
 497
 498    fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &LayoutContext) -> f32 {
 499        let digit_count = (snapshot.max_buffer_row() as f32).log10().floor() as usize + 1;
 500        let style = &self.style;
 501
 502        cx.text_layout_cache
 503            .layout_str(
 504                "1".repeat(digit_count).as_str(),
 505                style.text.font_size,
 506                &[(
 507                    digit_count,
 508                    RunStyle {
 509                        font_id: style.text.font_id,
 510                        color: Color::black(),
 511                        underline: None,
 512                    },
 513                )],
 514            )
 515            .width()
 516    }
 517
 518    fn layout_line_numbers(
 519        &self,
 520        rows: Range<u32>,
 521        active_rows: &BTreeMap<u32, bool>,
 522        snapshot: &EditorSnapshot,
 523        cx: &LayoutContext,
 524    ) -> Vec<Option<text_layout::Line>> {
 525        let style = &self.style;
 526        let include_line_numbers = snapshot.mode == EditorMode::Full;
 527        let mut line_number_layouts = Vec::with_capacity(rows.len());
 528        let mut line_number = String::new();
 529        for (ix, row) in snapshot
 530            .buffer_rows(rows.start)
 531            .take((rows.end - rows.start) as usize)
 532            .enumerate()
 533        {
 534            let display_row = rows.start + ix as u32;
 535            let color = if active_rows.contains_key(&display_row) {
 536                style.line_number_active
 537            } else {
 538                style.line_number
 539            };
 540            if let Some(buffer_row) = row {
 541                if include_line_numbers {
 542                    line_number.clear();
 543                    write!(&mut line_number, "{}", buffer_row + 1).unwrap();
 544                    line_number_layouts.push(Some(cx.text_layout_cache.layout_str(
 545                        &line_number,
 546                        style.text.font_size,
 547                        &[(
 548                            line_number.len(),
 549                            RunStyle {
 550                                font_id: style.text.font_id,
 551                                color,
 552                                underline: None,
 553                            },
 554                        )],
 555                    )));
 556                }
 557            } else {
 558                line_number_layouts.push(None);
 559            }
 560        }
 561
 562        line_number_layouts
 563    }
 564
 565    fn layout_lines(
 566        &mut self,
 567        mut rows: Range<u32>,
 568        snapshot: &mut EditorSnapshot,
 569        cx: &LayoutContext,
 570    ) -> Vec<text_layout::Line> {
 571        rows.end = cmp::min(rows.end, snapshot.max_point().row() + 1);
 572        if rows.start >= rows.end {
 573            return Vec::new();
 574        }
 575
 576        // When the editor is empty and unfocused, then show the placeholder.
 577        if snapshot.is_empty() && !snapshot.is_focused() {
 578            let placeholder_style = self
 579                .style
 580                .placeholder_text
 581                .as_ref()
 582                .unwrap_or_else(|| &self.style.text);
 583            let placeholder_text = snapshot.placeholder_text();
 584            let placeholder_lines = placeholder_text
 585                .as_ref()
 586                .map_or("", AsRef::as_ref)
 587                .split('\n')
 588                .skip(rows.start as usize)
 589                .take(rows.len());
 590            return placeholder_lines
 591                .map(|line| {
 592                    cx.text_layout_cache.layout_str(
 593                        line,
 594                        placeholder_style.font_size,
 595                        &[(
 596                            line.len(),
 597                            RunStyle {
 598                                font_id: placeholder_style.font_id,
 599                                color: placeholder_style.color,
 600                                underline: None,
 601                            },
 602                        )],
 603                    )
 604                })
 605                .collect();
 606        } else {
 607            let style = &self.style;
 608            let chunks = snapshot.chunks(rows.clone(), true).map(|chunk| {
 609                let highlight_style = chunk
 610                    .highlight_id
 611                    .and_then(|highlight_id| highlight_id.style(&style.syntax));
 612                let highlight = if let Some(severity) = chunk.diagnostic {
 613                    let diagnostic_style = super::diagnostic_style(severity, true, style);
 614                    let underline = Some(Underline {
 615                        color: diagnostic_style.message.text.color,
 616                        thickness: 1.0.into(),
 617                        squiggly: true,
 618                    });
 619                    if let Some(mut highlight) = highlight_style {
 620                        highlight.underline = underline;
 621                        Some(highlight)
 622                    } else {
 623                        Some(HighlightStyle {
 624                            underline,
 625                            color: style.text.color,
 626                            font_properties: style.text.font_properties,
 627                        })
 628                    }
 629                } else {
 630                    highlight_style
 631                };
 632                (chunk.text, highlight)
 633            });
 634            layout_highlighted_chunks(
 635                chunks,
 636                &style.text,
 637                &cx.text_layout_cache,
 638                &cx.font_cache,
 639                MAX_LINE_LEN,
 640                rows.len() as usize,
 641            )
 642        }
 643    }
 644
 645    fn layout_blocks(
 646        &mut self,
 647        rows: Range<u32>,
 648        snapshot: &EditorSnapshot,
 649        width: f32,
 650        gutter_padding: f32,
 651        gutter_width: f32,
 652        em_width: f32,
 653        text_x: f32,
 654        line_height: f32,
 655        style: &EditorStyle,
 656        line_layouts: &[text_layout::Line],
 657        cx: &mut LayoutContext,
 658    ) -> Vec<(u32, ElementBox)> {
 659        let scroll_x = snapshot.scroll_position.x();
 660        snapshot
 661            .blocks_in_range(rows.clone())
 662            .map(|(block_row, block)| {
 663                let mut element = match block {
 664                    TransformBlock::Custom(block) => {
 665                        let align_to = block
 666                            .position()
 667                            .to_point(&snapshot.buffer_snapshot)
 668                            .to_display_point(snapshot);
 669                        let anchor_x = text_x
 670                            + if rows.contains(&align_to.row()) {
 671                                line_layouts[(align_to.row() - rows.start) as usize]
 672                                    .x_for_index(align_to.column() as usize)
 673                            } else {
 674                                layout_line(align_to.row(), snapshot, style, cx.text_layout_cache)
 675                                    .x_for_index(align_to.column() as usize)
 676                            };
 677
 678                        block.render(&BlockContext {
 679                            cx,
 680                            anchor_x,
 681                            gutter_padding,
 682                            line_height,
 683                            scroll_x,
 684                            gutter_width,
 685                            em_width,
 686                        })
 687                    }
 688                    TransformBlock::ExcerptHeader {
 689                        buffer,
 690                        starts_new_buffer,
 691                        ..
 692                    } => {
 693                        if *starts_new_buffer {
 694                            let style = &self.style.diagnostic_path_header;
 695                            let font_size =
 696                                (style.text_scale_factor * self.style.text.font_size).round();
 697
 698                            let mut filename = None;
 699                            let mut parent_path = None;
 700                            if let Some(path) = buffer.path() {
 701                                filename =
 702                                    path.file_name().map(|f| f.to_string_lossy().to_string());
 703                                parent_path =
 704                                    path.parent().map(|p| p.to_string_lossy().to_string() + "/");
 705                            }
 706
 707                            Flex::row()
 708                                .with_child(
 709                                    Label::new(
 710                                        filename.unwrap_or_else(|| "untitled".to_string()),
 711                                        style.filename.text.clone().with_font_size(font_size),
 712                                    )
 713                                    .contained()
 714                                    .with_style(style.filename.container)
 715                                    .boxed(),
 716                                )
 717                                .with_children(parent_path.map(|path| {
 718                                    Label::new(
 719                                        path,
 720                                        style.path.text.clone().with_font_size(font_size),
 721                                    )
 722                                    .contained()
 723                                    .with_style(style.path.container)
 724                                    .boxed()
 725                                }))
 726                                .aligned()
 727                                .left()
 728                                .contained()
 729                                .with_style(style.container)
 730                                .with_padding_left(gutter_padding + scroll_x * em_width)
 731                                .expanded()
 732                                .named("path header block")
 733                        } else {
 734                            let text_style = self.style.text.clone();
 735                            Label::new("".to_string(), text_style)
 736                                .contained()
 737                                .with_padding_left(gutter_padding + scroll_x * em_width)
 738                                .named("collapsed context")
 739                        }
 740                    }
 741                };
 742
 743                element.layout(
 744                    SizeConstraint {
 745                        min: Vector2F::zero(),
 746                        max: vec2f(width, block.height() as f32 * line_height),
 747                    },
 748                    cx,
 749                );
 750                (block_row, element)
 751            })
 752            .collect()
 753    }
 754}
 755
 756impl Element for EditorElement {
 757    type LayoutState = LayoutState;
 758    type PaintState = PaintState;
 759
 760    fn layout(
 761        &mut self,
 762        constraint: SizeConstraint,
 763        cx: &mut LayoutContext,
 764    ) -> (Vector2F, Self::LayoutState) {
 765        let mut size = constraint.max;
 766        if size.x().is_infinite() {
 767            unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
 768        }
 769
 770        let snapshot = self.snapshot(cx.app);
 771        let style = self.style.clone();
 772        let line_height = style.text.line_height(cx.font_cache);
 773
 774        let gutter_padding;
 775        let gutter_width;
 776        let gutter_margin;
 777        if snapshot.mode == EditorMode::Full {
 778            gutter_padding = style.text.em_width(cx.font_cache) * style.gutter_padding_factor;
 779            gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
 780            gutter_margin = -style.text.descent(cx.font_cache);
 781        } else {
 782            gutter_padding = 0.0;
 783            gutter_width = 0.0;
 784            gutter_margin = 0.0;
 785        };
 786
 787        let text_width = size.x() - gutter_width;
 788        let em_width = style.text.em_width(cx.font_cache);
 789        let em_advance = style.text.em_advance(cx.font_cache);
 790        let overscroll = vec2f(em_width, 0.);
 791        let snapshot = self.update_view(cx.app, |view, cx| {
 792            let wrap_width = match view.soft_wrap_mode(cx) {
 793                SoftWrap::None => None,
 794                SoftWrap::EditorWidth => {
 795                    Some(text_width - gutter_margin - overscroll.x() - em_width)
 796                }
 797                SoftWrap::Column(column) => Some(column as f32 * em_advance),
 798            };
 799
 800            if view.set_wrap_width(wrap_width, cx) {
 801                view.snapshot(cx)
 802            } else {
 803                snapshot
 804            }
 805        });
 806
 807        let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
 808        if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
 809            size.set_y(
 810                scroll_height
 811                    .min(constraint.max_along(Axis::Vertical))
 812                    .max(constraint.min_along(Axis::Vertical))
 813                    .min(line_height * max_lines as f32),
 814            )
 815        } else if size.y().is_infinite() {
 816            size.set_y(scroll_height);
 817        }
 818        let gutter_size = vec2f(gutter_width, size.y());
 819        let text_size = vec2f(text_width, size.y());
 820
 821        let (autoscroll_horizontally, mut snapshot) = self.update_view(cx.app, |view, cx| {
 822            let autoscroll_horizontally = view.autoscroll_vertically(size.y(), line_height, cx);
 823            let snapshot = view.snapshot(cx);
 824            (autoscroll_horizontally, snapshot)
 825        });
 826
 827        let scroll_position = snapshot.scroll_position();
 828        let start_row = scroll_position.y() as u32;
 829        let scroll_top = scroll_position.y() * line_height;
 830        let end_row = ((scroll_top + size.y()) / line_height).ceil() as u32 + 1; // Add 1 to ensure selections bleed off screen
 831
 832        let start_anchor = if start_row == 0 {
 833            Anchor::min()
 834        } else {
 835            snapshot
 836                .buffer_snapshot
 837                .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
 838        };
 839        let end_anchor = if end_row > snapshot.max_point().row() {
 840            Anchor::max()
 841        } else {
 842            snapshot
 843                .buffer_snapshot
 844                .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
 845        };
 846
 847        let mut selections = HashMap::default();
 848        let mut active_rows = BTreeMap::new();
 849        let mut highlighted_rows = None;
 850        let mut highlighted_ranges = Vec::new();
 851        self.update_view(cx.app, |view, cx| {
 852            let display_map = view.display_map.update(cx, |map, cx| map.snapshot(cx));
 853
 854            highlighted_rows = view.highlighted_rows();
 855            highlighted_ranges = view.highlighted_ranges_in_range(
 856                start_anchor.clone()..end_anchor.clone(),
 857                &display_map,
 858            );
 859
 860            let local_selections = view
 861                .local_selections_in_range(start_anchor.clone()..end_anchor.clone(), &display_map);
 862            for selection in &local_selections {
 863                let is_empty = selection.start == selection.end;
 864                let selection_start = snapshot.prev_line_boundary(selection.start).1;
 865                let selection_end = snapshot.next_line_boundary(selection.end).1;
 866                for row in cmp::max(selection_start.row(), start_row)
 867                    ..=cmp::min(selection_end.row(), end_row)
 868                {
 869                    let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
 870                    *contains_non_empty_selection |= !is_empty;
 871                }
 872            }
 873            selections.insert(
 874                view.replica_id(cx),
 875                local_selections
 876                    .into_iter()
 877                    .map(|selection| crate::Selection {
 878                        id: selection.id,
 879                        goal: selection.goal,
 880                        reversed: selection.reversed,
 881                        start: selection.start.to_display_point(&display_map),
 882                        end: selection.end.to_display_point(&display_map),
 883                    })
 884                    .collect(),
 885            );
 886
 887            for (replica_id, selection) in display_map
 888                .buffer_snapshot
 889                .remote_selections_in_range(&(start_anchor..end_anchor))
 890            {
 891                selections
 892                    .entry(replica_id)
 893                    .or_insert(Vec::new())
 894                    .push(crate::Selection {
 895                        id: selection.id,
 896                        goal: selection.goal,
 897                        reversed: selection.reversed,
 898                        start: selection.start.to_display_point(&display_map),
 899                        end: selection.end.to_display_point(&display_map),
 900                    });
 901            }
 902        });
 903
 904        let line_number_layouts =
 905            self.layout_line_numbers(start_row..end_row, &active_rows, &snapshot, cx);
 906
 907        let mut max_visible_line_width = 0.0;
 908        let line_layouts = self.layout_lines(start_row..end_row, &mut snapshot, cx);
 909        for line in &line_layouts {
 910            if line.width() > max_visible_line_width {
 911                max_visible_line_width = line.width();
 912            }
 913        }
 914
 915        let style = self.style.clone();
 916        let longest_line_width = layout_line(
 917            snapshot.longest_row(),
 918            &snapshot,
 919            &style,
 920            cx.text_layout_cache,
 921        )
 922        .width();
 923        let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
 924        let em_width = style.text.em_width(cx.font_cache);
 925        let max_row = snapshot.max_point().row();
 926        let scroll_max = vec2f(
 927            ((scroll_width - text_size.x()) / em_width).max(0.0),
 928            max_row.saturating_sub(1) as f32,
 929        );
 930
 931        let mut context_menu = None;
 932        let mut code_actions_indicator = None;
 933        self.update_view(cx.app, |view, cx| {
 934            let clamped = view.clamp_scroll_left(scroll_max.x());
 935            let autoscrolled;
 936            if autoscroll_horizontally {
 937                autoscrolled = view.autoscroll_horizontally(
 938                    start_row,
 939                    text_size.x(),
 940                    scroll_width,
 941                    em_width,
 942                    &line_layouts,
 943                    cx,
 944                );
 945            } else {
 946                autoscrolled = false;
 947            }
 948
 949            if clamped || autoscrolled {
 950                snapshot = view.snapshot(cx);
 951            }
 952
 953            let newest_selection_head = view
 954                .newest_selection_with_snapshot::<usize>(&snapshot.buffer_snapshot)
 955                .head()
 956                .to_display_point(&snapshot);
 957
 958            if (start_row..end_row).contains(&newest_selection_head.row()) {
 959                let style = view.style(cx);
 960                if view.context_menu_visible() {
 961                    context_menu =
 962                        view.render_context_menu(newest_selection_head, style.clone(), cx);
 963                }
 964
 965                code_actions_indicator = view
 966                    .render_code_actions_indicator(&style, cx)
 967                    .map(|indicator| (newest_selection_head.row(), indicator));
 968            }
 969        });
 970
 971        if let Some((_, context_menu)) = context_menu.as_mut() {
 972            context_menu.layout(
 973                SizeConstraint {
 974                    min: Vector2F::zero(),
 975                    max: vec2f(
 976                        f32::INFINITY,
 977                        (12. * line_height).min((size.y() - line_height) / 2.),
 978                    ),
 979                },
 980                cx,
 981            );
 982        }
 983
 984        if let Some((_, indicator)) = code_actions_indicator.as_mut() {
 985            indicator.layout(
 986                SizeConstraint::strict_along(Axis::Vertical, line_height * 0.618),
 987                cx,
 988            );
 989        }
 990
 991        let blocks = self.layout_blocks(
 992            start_row..end_row,
 993            &snapshot,
 994            size.x().max(scroll_width + gutter_width),
 995            gutter_padding,
 996            gutter_width,
 997            em_width,
 998            gutter_width + gutter_margin,
 999            line_height,
1000            &style,
1001            &line_layouts,
1002            cx,
1003        );
1004
1005        (
1006            size,
1007            LayoutState {
1008                size,
1009                scroll_max,
1010                gutter_size,
1011                gutter_padding,
1012                text_size,
1013                gutter_margin,
1014                snapshot,
1015                active_rows,
1016                highlighted_rows,
1017                highlighted_ranges,
1018                line_layouts,
1019                line_number_layouts,
1020                blocks,
1021                line_height,
1022                em_width,
1023                em_advance,
1024                selections,
1025                context_menu,
1026                code_actions_indicator,
1027            },
1028        )
1029    }
1030
1031    fn paint(
1032        &mut self,
1033        bounds: RectF,
1034        visible_bounds: RectF,
1035        layout: &mut Self::LayoutState,
1036        cx: &mut PaintContext,
1037    ) -> Self::PaintState {
1038        cx.scene.push_layer(Some(bounds));
1039
1040        let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
1041        let text_bounds = RectF::new(
1042            bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
1043            layout.text_size,
1044        );
1045
1046        self.paint_background(gutter_bounds, text_bounds, layout, cx);
1047        if layout.gutter_size.x() > 0. {
1048            self.paint_gutter(gutter_bounds, visible_bounds, layout, cx);
1049        }
1050        self.paint_text(text_bounds, visible_bounds, layout, cx);
1051
1052        if !layout.blocks.is_empty() {
1053            cx.scene.push_layer(Some(bounds));
1054            self.paint_blocks(bounds, visible_bounds, layout, cx);
1055            cx.scene.pop_layer();
1056        }
1057
1058        cx.scene.pop_layer();
1059
1060        PaintState {
1061            bounds,
1062            gutter_bounds,
1063            text_bounds,
1064        }
1065    }
1066
1067    fn dispatch_event(
1068        &mut self,
1069        event: &Event,
1070        _: RectF,
1071        layout: &mut LayoutState,
1072        paint: &mut PaintState,
1073        cx: &mut EventContext,
1074    ) -> bool {
1075        if let Some((_, context_menu)) = &mut layout.context_menu {
1076            if context_menu.dispatch_event(event, cx) {
1077                return true;
1078            }
1079        }
1080
1081        if let Some((_, indicator)) = &mut layout.code_actions_indicator {
1082            if indicator.dispatch_event(event, cx) {
1083                return true;
1084            }
1085        }
1086
1087        for (_, block) in &mut layout.blocks {
1088            if block.dispatch_event(event, cx) {
1089                return true;
1090            }
1091        }
1092
1093        match event {
1094            Event::LeftMouseDown {
1095                position,
1096                alt,
1097                shift,
1098                click_count,
1099                ..
1100            } => self.mouse_down(*position, *alt, *shift, *click_count, layout, paint, cx),
1101            Event::LeftMouseUp { position } => self.mouse_up(*position, cx),
1102            Event::LeftMouseDragged { position } => {
1103                self.mouse_dragged(*position, layout, paint, cx)
1104            }
1105            Event::ScrollWheel {
1106                position,
1107                delta,
1108                precise,
1109            } => self.scroll(*position, *delta, *precise, layout, paint, cx),
1110            Event::KeyDown { input, .. } => self.key_down(input.as_deref(), cx),
1111            _ => false,
1112        }
1113    }
1114
1115    fn debug(
1116        &self,
1117        bounds: RectF,
1118        _: &Self::LayoutState,
1119        _: &Self::PaintState,
1120        _: &gpui::DebugContext,
1121    ) -> json::Value {
1122        json!({
1123            "type": "BufferElement",
1124            "bounds": bounds.to_json()
1125        })
1126    }
1127}
1128
1129pub struct LayoutState {
1130    size: Vector2F,
1131    scroll_max: Vector2F,
1132    gutter_size: Vector2F,
1133    gutter_padding: f32,
1134    gutter_margin: f32,
1135    text_size: Vector2F,
1136    snapshot: EditorSnapshot,
1137    active_rows: BTreeMap<u32, bool>,
1138    highlighted_rows: Option<Range<u32>>,
1139    line_layouts: Vec<text_layout::Line>,
1140    line_number_layouts: Vec<Option<text_layout::Line>>,
1141    blocks: Vec<(u32, ElementBox)>,
1142    line_height: f32,
1143    em_width: f32,
1144    em_advance: f32,
1145    highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
1146    selections: HashMap<ReplicaId, Vec<text::Selection<DisplayPoint>>>,
1147    context_menu: Option<(DisplayPoint, ElementBox)>,
1148    code_actions_indicator: Option<(u32, ElementBox)>,
1149}
1150
1151fn layout_line(
1152    row: u32,
1153    snapshot: &EditorSnapshot,
1154    style: &EditorStyle,
1155    layout_cache: &TextLayoutCache,
1156) -> text_layout::Line {
1157    let mut line = snapshot.line(row);
1158
1159    if line.len() > MAX_LINE_LEN {
1160        let mut len = MAX_LINE_LEN;
1161        while !line.is_char_boundary(len) {
1162            len -= 1;
1163        }
1164        line.truncate(len);
1165    }
1166
1167    layout_cache.layout_str(
1168        &line,
1169        style.text.font_size,
1170        &[(
1171            snapshot.line_len(row) as usize,
1172            RunStyle {
1173                font_id: style.text.font_id,
1174                color: Color::black(),
1175                underline: None,
1176            },
1177        )],
1178    )
1179}
1180
1181pub struct PaintState {
1182    bounds: RectF,
1183    gutter_bounds: RectF,
1184    text_bounds: RectF,
1185}
1186
1187impl PaintState {
1188    fn point_for_position(
1189        &self,
1190        snapshot: &EditorSnapshot,
1191        layout: &LayoutState,
1192        position: Vector2F,
1193    ) -> (DisplayPoint, u32) {
1194        let scroll_position = snapshot.scroll_position();
1195        let position = position - self.text_bounds.origin();
1196        let y = position.y().max(0.0).min(layout.size.y());
1197        let row = ((y / layout.line_height) + scroll_position.y()) as u32;
1198        let row = cmp::min(row, snapshot.max_point().row());
1199        let line = &layout.line_layouts[(row - scroll_position.y() as u32) as usize];
1200        let x = position.x() + (scroll_position.x() * layout.em_width);
1201
1202        let column = if x >= 0.0 {
1203            line.index_for_x(x)
1204                .map(|ix| ix as u32)
1205                .unwrap_or_else(|| snapshot.line_len(row))
1206        } else {
1207            0
1208        };
1209        let overshoot = (0f32.max(x - line.width()) / layout.em_advance) as u32;
1210
1211        (DisplayPoint::new(row, column), overshoot)
1212    }
1213}
1214
1215struct Cursor {
1216    origin: Vector2F,
1217    line_height: f32,
1218    color: Color,
1219}
1220
1221impl Cursor {
1222    fn paint(&self, cx: &mut PaintContext) {
1223        cx.scene.push_quad(Quad {
1224            bounds: RectF::new(self.origin, vec2f(2.0, self.line_height)),
1225            background: Some(self.color),
1226            border: Border::new(0., Color::black()),
1227            corner_radius: 0.,
1228        });
1229    }
1230}
1231
1232#[derive(Debug)]
1233struct HighlightedRange {
1234    start_y: f32,
1235    line_height: f32,
1236    lines: Vec<HighlightedRangeLine>,
1237    color: Color,
1238    corner_radius: f32,
1239}
1240
1241#[derive(Debug)]
1242struct HighlightedRangeLine {
1243    start_x: f32,
1244    end_x: f32,
1245}
1246
1247impl HighlightedRange {
1248    fn paint(&self, bounds: RectF, scene: &mut Scene) {
1249        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
1250            self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
1251            self.paint_lines(
1252                self.start_y + self.line_height,
1253                &self.lines[1..],
1254                bounds,
1255                scene,
1256            );
1257        } else {
1258            self.paint_lines(self.start_y, &self.lines, bounds, scene);
1259        }
1260    }
1261
1262    fn paint_lines(
1263        &self,
1264        start_y: f32,
1265        lines: &[HighlightedRangeLine],
1266        bounds: RectF,
1267        scene: &mut Scene,
1268    ) {
1269        if lines.is_empty() {
1270            return;
1271        }
1272
1273        let mut path = PathBuilder::new();
1274        let first_line = lines.first().unwrap();
1275        let last_line = lines.last().unwrap();
1276
1277        let first_top_left = vec2f(first_line.start_x, start_y);
1278        let first_top_right = vec2f(first_line.end_x, start_y);
1279
1280        let curve_height = vec2f(0., self.corner_radius);
1281        let curve_width = |start_x: f32, end_x: f32| {
1282            let max = (end_x - start_x) / 2.;
1283            let width = if max < self.corner_radius {
1284                max
1285            } else {
1286                self.corner_radius
1287            };
1288
1289            vec2f(width, 0.)
1290        };
1291
1292        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
1293        path.reset(first_top_right - top_curve_width);
1294        path.curve_to(first_top_right + curve_height, first_top_right);
1295
1296        let mut iter = lines.iter().enumerate().peekable();
1297        while let Some((ix, line)) = iter.next() {
1298            let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
1299
1300            if let Some((_, next_line)) = iter.peek() {
1301                let next_top_right = vec2f(next_line.end_x, bottom_right.y());
1302
1303                match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
1304                    Ordering::Equal => {
1305                        path.line_to(bottom_right);
1306                    }
1307                    Ordering::Less => {
1308                        let curve_width = curve_width(next_top_right.x(), bottom_right.x());
1309                        path.line_to(bottom_right - curve_height);
1310                        if self.corner_radius > 0. {
1311                            path.curve_to(bottom_right - curve_width, bottom_right);
1312                        }
1313                        path.line_to(next_top_right + curve_width);
1314                        if self.corner_radius > 0. {
1315                            path.curve_to(next_top_right + curve_height, next_top_right);
1316                        }
1317                    }
1318                    Ordering::Greater => {
1319                        let curve_width = curve_width(bottom_right.x(), next_top_right.x());
1320                        path.line_to(bottom_right - curve_height);
1321                        if self.corner_radius > 0. {
1322                            path.curve_to(bottom_right + curve_width, bottom_right);
1323                        }
1324                        path.line_to(next_top_right - curve_width);
1325                        if self.corner_radius > 0. {
1326                            path.curve_to(next_top_right + curve_height, next_top_right);
1327                        }
1328                    }
1329                }
1330            } else {
1331                let curve_width = curve_width(line.start_x, line.end_x);
1332                path.line_to(bottom_right - curve_height);
1333                if self.corner_radius > 0. {
1334                    path.curve_to(bottom_right - curve_width, bottom_right);
1335                }
1336
1337                let bottom_left = vec2f(line.start_x, bottom_right.y());
1338                path.line_to(bottom_left + curve_width);
1339                if self.corner_radius > 0. {
1340                    path.curve_to(bottom_left - curve_height, bottom_left);
1341                }
1342            }
1343        }
1344
1345        if first_line.start_x > last_line.start_x {
1346            let curve_width = curve_width(last_line.start_x, first_line.start_x);
1347            let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
1348            path.line_to(second_top_left + curve_height);
1349            if self.corner_radius > 0. {
1350                path.curve_to(second_top_left + curve_width, second_top_left);
1351            }
1352            let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
1353            path.line_to(first_bottom_left - curve_width);
1354            if self.corner_radius > 0. {
1355                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
1356            }
1357        }
1358
1359        path.line_to(first_top_left + curve_height);
1360        if self.corner_radius > 0. {
1361            path.curve_to(first_top_left + top_curve_width, first_top_left);
1362        }
1363        path.line_to(first_top_right - top_curve_width);
1364
1365        scene.push_path(path.build(self.color, Some(bounds)));
1366    }
1367}
1368
1369fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
1370    delta.powf(1.5) / 100.0
1371}
1372
1373fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
1374    delta.powf(1.2) / 300.0
1375}
1376
1377#[cfg(test)]
1378mod tests {
1379    use super::*;
1380    use crate::{Editor, MultiBuffer};
1381    use postage::watch;
1382    use util::test::sample_text;
1383    use workspace::Settings;
1384
1385    #[gpui::test]
1386    fn test_layout_line_numbers(cx: &mut gpui::MutableAppContext) {
1387        let settings = watch::channel_with(Settings::test(cx));
1388        let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
1389        let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1390            Editor::new(EditorMode::Full, buffer, None, settings.1, None, cx)
1391        });
1392        let element = EditorElement::new(editor.downgrade(), editor.read(cx).style(cx));
1393
1394        let layouts = editor.update(cx, |editor, cx| {
1395            let snapshot = editor.snapshot(cx);
1396            let mut presenter = cx.build_presenter(window_id, 30.);
1397            let mut layout_cx = presenter.build_layout_context(false, cx);
1398            element.layout_line_numbers(0..6, &Default::default(), &snapshot, &mut layout_cx)
1399        });
1400        assert_eq!(layouts.len(), 6);
1401    }
1402}