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::{
   7    display_map::{BlockStyle, DisplaySnapshot, TransformBlock},
   8    hover_popover::HoverAt,
   9    EditorStyle,
  10};
  11use clock::ReplicaId;
  12use collections::{BTreeMap, HashMap};
  13use gpui::{
  14    color::Color,
  15    elements::*,
  16    fonts::{HighlightStyle, Underline},
  17    geometry::{
  18        rect::RectF,
  19        vector::{vec2f, Vector2F},
  20        PathBuilder,
  21    },
  22    json::{self, ToJson},
  23    platform::CursorStyle,
  24    text_layout::{self, Line, RunStyle, TextLayoutCache},
  25    AppContext, Axis, Border, CursorRegion, Element, ElementBox, Event, EventContext,
  26    LayoutContext, MutableAppContext, PaintContext, Quad, Scene, SizeConstraint, ViewContext,
  27    WeakViewHandle,
  28};
  29use json::json;
  30use language::{Bias, DiagnosticSeverity, Selection};
  31use project::ProjectPath;
  32use settings::Settings;
  33use smallvec::SmallVec;
  34use std::{
  35    cmp::{self, Ordering},
  36    fmt::Write,
  37    iter,
  38    ops::Range,
  39};
  40
  41struct SelectionLayout {
  42    head: DisplayPoint,
  43    range: Range<DisplayPoint>,
  44}
  45
  46impl SelectionLayout {
  47    fn new<T: ToPoint + ToDisplayPoint + Clone>(
  48        selection: Selection<T>,
  49        line_mode: bool,
  50        map: &DisplaySnapshot,
  51    ) -> Self {
  52        if line_mode {
  53            let selection = selection.map(|p| p.to_point(&map.buffer_snapshot));
  54            let point_range = map.expand_to_line(selection.range());
  55            Self {
  56                head: selection.head().to_display_point(map),
  57                range: point_range.start.to_display_point(map)
  58                    ..point_range.end.to_display_point(map),
  59            }
  60        } else {
  61            let selection = selection.map(|p| p.to_display_point(map));
  62            Self {
  63                head: selection.head(),
  64                range: selection.range(),
  65            }
  66        }
  67    }
  68}
  69
  70pub struct EditorElement {
  71    view: WeakViewHandle<Editor>,
  72    style: EditorStyle,
  73    cursor_shape: CursorShape,
  74}
  75
  76impl EditorElement {
  77    pub fn new(
  78        view: WeakViewHandle<Editor>,
  79        style: EditorStyle,
  80        cursor_shape: CursorShape,
  81    ) -> Self {
  82        Self {
  83            view,
  84            style,
  85            cursor_shape,
  86        }
  87    }
  88
  89    fn view<'a>(&self, cx: &'a AppContext) -> &'a Editor {
  90        self.view.upgrade(cx).unwrap().read(cx)
  91    }
  92
  93    fn update_view<F, T>(&self, cx: &mut MutableAppContext, f: F) -> T
  94    where
  95        F: FnOnce(&mut Editor, &mut ViewContext<Editor>) -> T,
  96    {
  97        self.view.upgrade(cx).unwrap().update(cx, f)
  98    }
  99
 100    fn snapshot(&self, cx: &mut MutableAppContext) -> EditorSnapshot {
 101        self.update_view(cx, |view, cx| view.snapshot(cx))
 102    }
 103
 104    fn mouse_down(
 105        &self,
 106        position: Vector2F,
 107        _: bool,
 108        alt: bool,
 109        shift: bool,
 110        mut click_count: usize,
 111        layout: &mut LayoutState,
 112        paint: &mut PaintState,
 113        cx: &mut EventContext,
 114    ) -> bool {
 115        if paint.gutter_bounds.contains_point(position) {
 116            click_count = 3; // Simulate triple-click when clicking the gutter to select lines
 117        } else if !paint.text_bounds.contains_point(position) {
 118            return false;
 119        }
 120
 121        let snapshot = self.snapshot(cx.app);
 122        let (position, overshoot) = paint.point_for_position(&snapshot, layout, position);
 123
 124        if shift && alt {
 125            cx.dispatch_action(Select(SelectPhase::BeginColumnar {
 126                position,
 127                overshoot: overshoot.column(),
 128            }));
 129        } else if shift {
 130            cx.dispatch_action(Select(SelectPhase::Extend {
 131                position,
 132                click_count,
 133            }));
 134        } else {
 135            cx.dispatch_action(Select(SelectPhase::Begin {
 136                position,
 137                add: alt,
 138                click_count,
 139            }));
 140        }
 141
 142        true
 143    }
 144
 145    fn mouse_up(&self, _position: Vector2F, cx: &mut EventContext) -> bool {
 146        if self.view(cx.app.as_ref()).is_selecting() {
 147            cx.dispatch_action(Select(SelectPhase::End));
 148            true
 149        } else {
 150            false
 151        }
 152    }
 153
 154    fn mouse_dragged(
 155        &self,
 156        position: Vector2F,
 157        layout: &mut LayoutState,
 158        paint: &mut PaintState,
 159        cx: &mut EventContext,
 160    ) -> bool {
 161        let view = self.view(cx.app.as_ref());
 162
 163        if view.is_selecting() {
 164            let rect = paint.text_bounds;
 165            let mut scroll_delta = Vector2F::zero();
 166
 167            let vertical_margin = layout.line_height.min(rect.height() / 3.0);
 168            let top = rect.origin_y() + vertical_margin;
 169            let bottom = rect.lower_left().y() - vertical_margin;
 170            if position.y() < top {
 171                scroll_delta.set_y(-scale_vertical_mouse_autoscroll_delta(top - position.y()))
 172            }
 173            if position.y() > bottom {
 174                scroll_delta.set_y(scale_vertical_mouse_autoscroll_delta(position.y() - bottom))
 175            }
 176
 177            let horizontal_margin = layout.line_height.min(rect.width() / 3.0);
 178            let left = rect.origin_x() + horizontal_margin;
 179            let right = rect.upper_right().x() - horizontal_margin;
 180            if position.x() < left {
 181                scroll_delta.set_x(-scale_horizontal_mouse_autoscroll_delta(
 182                    left - position.x(),
 183                ))
 184            }
 185            if position.x() > right {
 186                scroll_delta.set_x(scale_horizontal_mouse_autoscroll_delta(
 187                    position.x() - right,
 188                ))
 189            }
 190
 191            let snapshot = self.snapshot(cx.app);
 192            let (position, overshoot) = paint.point_for_position(&snapshot, layout, position);
 193
 194            cx.dispatch_action(Select(SelectPhase::Update {
 195                position,
 196                overshoot: overshoot.column(),
 197                scroll_position: (snapshot.scroll_position() + scroll_delta)
 198                    .clamp(Vector2F::zero(), layout.scroll_max),
 199            }));
 200            true
 201        } else {
 202            false
 203        }
 204    }
 205
 206    fn key_down(&self, input: Option<&str>, cx: &mut EventContext) -> bool {
 207        let view = self.view.upgrade(cx.app).unwrap();
 208
 209        if view.is_focused(cx.app) {
 210            if let Some(input) = input {
 211                cx.dispatch_action(Input(input.to_string()));
 212                true
 213            } else {
 214                false
 215            }
 216        } else {
 217            false
 218        }
 219    }
 220
 221    fn scroll(
 222        &self,
 223        position: Vector2F,
 224        mut delta: Vector2F,
 225        precise: bool,
 226        layout: &mut LayoutState,
 227        paint: &mut PaintState,
 228        cx: &mut EventContext,
 229    ) -> bool {
 230        if !paint.bounds.contains_point(position) {
 231            return false;
 232        }
 233
 234        let snapshot = self.snapshot(cx.app);
 235        let max_glyph_width = layout.em_width;
 236        if !precise {
 237            delta *= vec2f(max_glyph_width, layout.line_height);
 238        }
 239
 240        let scroll_position = snapshot.scroll_position();
 241        let x = (scroll_position.x() * max_glyph_width - delta.x()) / max_glyph_width;
 242        let y = (scroll_position.y() * layout.line_height - delta.y()) / layout.line_height;
 243        let scroll_position = vec2f(x, y).clamp(Vector2F::zero(), layout.scroll_max);
 244
 245        cx.dispatch_action(Scroll(scroll_position));
 246
 247        true
 248    }
 249
 250    fn paint_background(
 251        &self,
 252        gutter_bounds: RectF,
 253        text_bounds: RectF,
 254        layout: &LayoutState,
 255        cx: &mut PaintContext,
 256    ) {
 257        let bounds = gutter_bounds.union_rect(text_bounds);
 258        let scroll_top = layout.snapshot.scroll_position().y() * layout.line_height;
 259        let editor = self.view(cx.app);
 260        cx.scene.push_quad(Quad {
 261            bounds: gutter_bounds,
 262            background: Some(self.style.gutter_background),
 263            border: Border::new(0., Color::transparent_black()),
 264            corner_radius: 0.,
 265        });
 266        cx.scene.push_quad(Quad {
 267            bounds: text_bounds,
 268            background: Some(self.style.background),
 269            border: Border::new(0., Color::transparent_black()),
 270            corner_radius: 0.,
 271        });
 272
 273        if let EditorMode::Full = editor.mode {
 274            let mut active_rows = layout.active_rows.iter().peekable();
 275            while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
 276                let mut end_row = *start_row;
 277                while active_rows.peek().map_or(false, |r| {
 278                    *r.0 == end_row + 1 && r.1 == contains_non_empty_selection
 279                }) {
 280                    active_rows.next().unwrap();
 281                    end_row += 1;
 282                }
 283
 284                if !contains_non_empty_selection {
 285                    let origin = vec2f(
 286                        bounds.origin_x(),
 287                        bounds.origin_y() + (layout.line_height * *start_row as f32) - scroll_top,
 288                    );
 289                    let size = vec2f(
 290                        bounds.width(),
 291                        layout.line_height * (end_row - start_row + 1) as f32,
 292                    );
 293                    cx.scene.push_quad(Quad {
 294                        bounds: RectF::new(origin, size),
 295                        background: Some(self.style.active_line_background),
 296                        border: Border::default(),
 297                        corner_radius: 0.,
 298                    });
 299                }
 300            }
 301
 302            if let Some(highlighted_rows) = &layout.highlighted_rows {
 303                let origin = vec2f(
 304                    bounds.origin_x(),
 305                    bounds.origin_y() + (layout.line_height * highlighted_rows.start as f32)
 306                        - scroll_top,
 307                );
 308                let size = vec2f(
 309                    bounds.width(),
 310                    layout.line_height * highlighted_rows.len() as f32,
 311                );
 312                cx.scene.push_quad(Quad {
 313                    bounds: RectF::new(origin, size),
 314                    background: Some(self.style.highlighted_line_background),
 315                    border: Border::default(),
 316                    corner_radius: 0.,
 317                });
 318            }
 319        }
 320    }
 321
 322    fn paint_gutter(
 323        &mut self,
 324        bounds: RectF,
 325        visible_bounds: RectF,
 326        layout: &mut LayoutState,
 327        cx: &mut PaintContext,
 328    ) {
 329        let scroll_top = layout.snapshot.scroll_position().y() * layout.line_height;
 330        for (ix, line) in layout.line_number_layouts.iter().enumerate() {
 331            if let Some(line) = line {
 332                let line_origin = bounds.origin()
 333                    + vec2f(
 334                        bounds.width() - line.width() - layout.gutter_padding,
 335                        ix as f32 * layout.line_height - (scroll_top % layout.line_height),
 336                    );
 337                line.paint(line_origin, visible_bounds, layout.line_height, cx);
 338            }
 339        }
 340
 341        if let Some((row, indicator)) = layout.code_actions_indicator.as_mut() {
 342            let mut x = bounds.width() - layout.gutter_padding;
 343            let mut y = *row as f32 * layout.line_height - scroll_top;
 344            x += ((layout.gutter_padding + layout.gutter_margin) - indicator.size().x()) / 2.;
 345            y += (layout.line_height - indicator.size().y()) / 2.;
 346            indicator.paint(bounds.origin() + vec2f(x, y), visible_bounds, cx);
 347        }
 348    }
 349
 350    fn paint_text(
 351        &mut self,
 352        bounds: RectF,
 353        visible_bounds: RectF,
 354        layout: &mut LayoutState,
 355        paint: &mut PaintState,
 356        cx: &mut PaintContext,
 357    ) {
 358        let view = self.view(cx.app);
 359        let style = &self.style;
 360        let local_replica_id = view.replica_id(cx);
 361        let scroll_position = layout.snapshot.scroll_position();
 362        let start_row = scroll_position.y() as u32;
 363        let scroll_top = scroll_position.y() * layout.line_height;
 364        let end_row = ((scroll_top + bounds.height()) / layout.line_height).ceil() as u32 + 1; // Add 1 to ensure selections bleed off screen
 365        let max_glyph_width = layout.em_width;
 366        let scroll_left = scroll_position.x() * max_glyph_width;
 367        let content_origin = bounds.origin() + vec2f(layout.gutter_margin, 0.);
 368
 369        cx.scene.push_layer(Some(bounds));
 370        cx.scene.push_cursor_region(CursorRegion {
 371            bounds,
 372            style: CursorStyle::IBeam,
 373        });
 374
 375        for (range, color) in &layout.highlighted_ranges {
 376            self.paint_highlighted_range(
 377                range.clone(),
 378                start_row,
 379                end_row,
 380                *color,
 381                0.,
 382                0.15 * layout.line_height,
 383                layout,
 384                content_origin,
 385                scroll_top,
 386                scroll_left,
 387                bounds,
 388                cx,
 389            );
 390        }
 391
 392        let mut cursors = SmallVec::<[Cursor; 32]>::new();
 393        for (replica_id, selections) in &layout.selections {
 394            let selection_style = style.replica_selection_style(*replica_id);
 395            let corner_radius = 0.15 * layout.line_height;
 396
 397            for selection in selections {
 398                self.paint_highlighted_range(
 399                    selection.range.clone(),
 400                    start_row,
 401                    end_row,
 402                    selection_style.selection,
 403                    corner_radius,
 404                    corner_radius * 2.,
 405                    layout,
 406                    content_origin,
 407                    scroll_top,
 408                    scroll_left,
 409                    bounds,
 410                    cx,
 411                );
 412
 413                if view.show_local_cursors() || *replica_id != local_replica_id {
 414                    let cursor_position = selection.head;
 415                    if (start_row..end_row).contains(&cursor_position.row()) {
 416                        let cursor_row_layout =
 417                            &layout.line_layouts[(cursor_position.row() - start_row) as usize];
 418                        let cursor_column = cursor_position.column() as usize;
 419
 420                        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 421                        let mut block_width =
 422                            cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
 423                        if block_width == 0.0 {
 424                            block_width = layout.em_width;
 425                        }
 426
 427                        let block_text =
 428                            if matches!(self.cursor_shape, CursorShape::Block) {
 429                                layout.snapshot.chars_at(cursor_position).next().and_then(
 430                                    |character| {
 431                                        let font_id =
 432                                            cursor_row_layout.font_for_index(cursor_column)?;
 433                                        let text = character.to_string();
 434
 435                                        Some(cx.text_layout_cache.layout_str(
 436                                            &text,
 437                                            cursor_row_layout.font_size(),
 438                                            &[(
 439                                                text.len(),
 440                                                RunStyle {
 441                                                    font_id,
 442                                                    color: style.background,
 443                                                    underline: Default::default(),
 444                                                },
 445                                            )],
 446                                        ))
 447                                    },
 448                                )
 449                            } else {
 450                                None
 451                            };
 452
 453                        let x = cursor_character_x - scroll_left;
 454                        let y = cursor_position.row() as f32 * layout.line_height - scroll_top;
 455                        cursors.push(Cursor {
 456                            color: selection_style.cursor,
 457                            block_width,
 458                            origin: content_origin + vec2f(x, y),
 459                            line_height: layout.line_height,
 460                            shape: self.cursor_shape,
 461                            block_text,
 462                        });
 463                    }
 464                }
 465            }
 466        }
 467
 468        if let Some(visible_text_bounds) = bounds.intersection(visible_bounds) {
 469            // Draw glyphs
 470            for (ix, line) in layout.line_layouts.iter().enumerate() {
 471                let row = start_row + ix as u32;
 472                line.paint(
 473                    content_origin
 474                        + vec2f(-scroll_left, row as f32 * layout.line_height - scroll_top),
 475                    visible_text_bounds,
 476                    layout.line_height,
 477                    cx,
 478                );
 479            }
 480        }
 481
 482        cx.scene.push_layer(Some(bounds));
 483        for cursor in cursors {
 484            cursor.paint(cx);
 485        }
 486        cx.scene.pop_layer();
 487
 488        if let Some((position, context_menu)) = layout.context_menu.as_mut() {
 489            cx.scene.push_stacking_context(None);
 490
 491            let cursor_row_layout = &layout.line_layouts[(position.row() - start_row) as usize];
 492            let x = cursor_row_layout.x_for_index(position.column() as usize) - scroll_left;
 493            let y = (position.row() + 1) as f32 * layout.line_height - scroll_top;
 494            let mut list_origin = content_origin + vec2f(x, y);
 495            let list_width = context_menu.size().x();
 496            let list_height = context_menu.size().y();
 497
 498            // Snap the right edge of the list to the right edge of the window if
 499            // its horizontal bounds overflow.
 500            if list_origin.x() + list_width > cx.window_size.x() {
 501                list_origin.set_x((cx.window_size.x() - list_width).max(0.));
 502            }
 503
 504            if list_origin.y() + list_height > bounds.max_y() {
 505                list_origin.set_y(list_origin.y() - layout.line_height - list_height);
 506            }
 507
 508            context_menu.paint(
 509                list_origin,
 510                RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
 511                cx,
 512            );
 513
 514            paint.context_menu_bounds = Some(RectF::new(list_origin, context_menu.size()));
 515
 516            cx.scene.pop_stacking_context();
 517        }
 518
 519        if let Some((position, hover_popover)) = layout.hover.as_mut() {
 520            cx.scene.push_stacking_context(None);
 521
 522            // This is safe because we check on layout whether the required row is available
 523            let hovered_row_layout = &layout.line_layouts[(position.row() - start_row) as usize];
 524            let size = hover_popover.size();
 525            let x = hovered_row_layout.x_for_index(position.column() as usize) - scroll_left;
 526            let y = position.row() as f32 * layout.line_height - scroll_top - size.y();
 527            let mut popover_origin = content_origin + vec2f(x, y);
 528
 529            if popover_origin.y() < 0.0 {
 530                popover_origin.set_y(popover_origin.y() + layout.line_height + size.y());
 531            }
 532
 533            let x_out_of_bounds = bounds.max_x() - (popover_origin.x() + size.x());
 534            if x_out_of_bounds < 0.0 {
 535                popover_origin.set_x(popover_origin.x() + x_out_of_bounds);
 536            }
 537
 538            hover_popover.paint(
 539                popover_origin,
 540                RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
 541                cx,
 542            );
 543
 544            paint.hover_bounds = Some(
 545                RectF::new(popover_origin, hover_popover.size()).dilate(Vector2F::new(0., 5.)),
 546            );
 547
 548            cx.scene.pop_stacking_context();
 549        }
 550
 551        cx.scene.pop_layer();
 552    }
 553
 554    fn paint_highlighted_range(
 555        &self,
 556        range: Range<DisplayPoint>,
 557        start_row: u32,
 558        end_row: u32,
 559        color: Color,
 560        corner_radius: f32,
 561        line_end_overshoot: f32,
 562        layout: &LayoutState,
 563        content_origin: Vector2F,
 564        scroll_top: f32,
 565        scroll_left: f32,
 566        bounds: RectF,
 567        cx: &mut PaintContext,
 568    ) {
 569        if range.start != range.end {
 570            let row_range = if range.end.column() == 0 {
 571                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
 572            } else {
 573                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
 574            };
 575
 576            let highlighted_range = HighlightedRange {
 577                color,
 578                line_height: layout.line_height,
 579                corner_radius,
 580                start_y: content_origin.y() + row_range.start as f32 * layout.line_height
 581                    - scroll_top,
 582                lines: row_range
 583                    .into_iter()
 584                    .map(|row| {
 585                        let line_layout = &layout.line_layouts[(row - start_row) as usize];
 586                        HighlightedRangeLine {
 587                            start_x: if row == range.start.row() {
 588                                content_origin.x()
 589                                    + line_layout.x_for_index(range.start.column() as usize)
 590                                    - scroll_left
 591                            } else {
 592                                content_origin.x() - scroll_left
 593                            },
 594                            end_x: if row == range.end.row() {
 595                                content_origin.x()
 596                                    + line_layout.x_for_index(range.end.column() as usize)
 597                                    - scroll_left
 598                            } else {
 599                                content_origin.x() + line_layout.width() + line_end_overshoot
 600                                    - scroll_left
 601                            },
 602                        }
 603                    })
 604                    .collect(),
 605            };
 606
 607            highlighted_range.paint(bounds, cx.scene);
 608        }
 609    }
 610
 611    fn paint_blocks(
 612        &mut self,
 613        bounds: RectF,
 614        visible_bounds: RectF,
 615        layout: &mut LayoutState,
 616        cx: &mut PaintContext,
 617    ) {
 618        let scroll_position = layout.snapshot.scroll_position();
 619        let scroll_left = scroll_position.x() * layout.em_width;
 620        let scroll_top = scroll_position.y() * layout.line_height;
 621
 622        for block in &mut layout.blocks {
 623            let mut origin =
 624                bounds.origin() + vec2f(0., block.row as f32 * layout.line_height - scroll_top);
 625            if !matches!(block.style, BlockStyle::Sticky) {
 626                origin += vec2f(-scroll_left, 0.);
 627            }
 628            block.element.paint(origin, visible_bounds, cx);
 629        }
 630    }
 631
 632    fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &LayoutContext) -> f32 {
 633        let digit_count = (snapshot.max_buffer_row() as f32).log10().floor() as usize + 1;
 634        let style = &self.style;
 635
 636        cx.text_layout_cache
 637            .layout_str(
 638                "1".repeat(digit_count).as_str(),
 639                style.text.font_size,
 640                &[(
 641                    digit_count,
 642                    RunStyle {
 643                        font_id: style.text.font_id,
 644                        color: Color::black(),
 645                        underline: Default::default(),
 646                    },
 647                )],
 648            )
 649            .width()
 650    }
 651
 652    fn layout_line_numbers(
 653        &self,
 654        rows: Range<u32>,
 655        active_rows: &BTreeMap<u32, bool>,
 656        snapshot: &EditorSnapshot,
 657        cx: &LayoutContext,
 658    ) -> Vec<Option<text_layout::Line>> {
 659        let style = &self.style;
 660        let include_line_numbers = snapshot.mode == EditorMode::Full;
 661        let mut line_number_layouts = Vec::with_capacity(rows.len());
 662        let mut line_number = String::new();
 663        for (ix, row) in snapshot
 664            .buffer_rows(rows.start)
 665            .take((rows.end - rows.start) as usize)
 666            .enumerate()
 667        {
 668            let display_row = rows.start + ix as u32;
 669            let color = if active_rows.contains_key(&display_row) {
 670                style.line_number_active
 671            } else {
 672                style.line_number
 673            };
 674            if let Some(buffer_row) = row {
 675                if include_line_numbers {
 676                    line_number.clear();
 677                    write!(&mut line_number, "{}", buffer_row + 1).unwrap();
 678                    line_number_layouts.push(Some(cx.text_layout_cache.layout_str(
 679                        &line_number,
 680                        style.text.font_size,
 681                        &[(
 682                            line_number.len(),
 683                            RunStyle {
 684                                font_id: style.text.font_id,
 685                                color,
 686                                underline: Default::default(),
 687                            },
 688                        )],
 689                    )));
 690                }
 691            } else {
 692                line_number_layouts.push(None);
 693            }
 694        }
 695
 696        line_number_layouts
 697    }
 698
 699    fn layout_lines(
 700        &mut self,
 701        rows: Range<u32>,
 702        snapshot: &EditorSnapshot,
 703        cx: &LayoutContext,
 704    ) -> Vec<text_layout::Line> {
 705        if rows.start >= rows.end {
 706            return Vec::new();
 707        }
 708
 709        // When the editor is empty and unfocused, then show the placeholder.
 710        if snapshot.is_empty() && !snapshot.is_focused() {
 711            let placeholder_style = self
 712                .style
 713                .placeholder_text
 714                .as_ref()
 715                .unwrap_or_else(|| &self.style.text);
 716            let placeholder_text = snapshot.placeholder_text();
 717            let placeholder_lines = placeholder_text
 718                .as_ref()
 719                .map_or("", AsRef::as_ref)
 720                .split('\n')
 721                .skip(rows.start as usize)
 722                .chain(iter::repeat(""))
 723                .take(rows.len());
 724            return placeholder_lines
 725                .map(|line| {
 726                    cx.text_layout_cache.layout_str(
 727                        line,
 728                        placeholder_style.font_size,
 729                        &[(
 730                            line.len(),
 731                            RunStyle {
 732                                font_id: placeholder_style.font_id,
 733                                color: placeholder_style.color,
 734                                underline: Default::default(),
 735                            },
 736                        )],
 737                    )
 738                })
 739                .collect();
 740        } else {
 741            let style = &self.style;
 742            let chunks = snapshot.chunks(rows.clone(), true).map(|chunk| {
 743                let mut highlight_style = chunk
 744                    .syntax_highlight_id
 745                    .and_then(|id| id.style(&style.syntax));
 746
 747                if let Some(chunk_highlight) = chunk.highlight_style {
 748                    if let Some(highlight_style) = highlight_style.as_mut() {
 749                        highlight_style.highlight(chunk_highlight);
 750                    } else {
 751                        highlight_style = Some(chunk_highlight);
 752                    }
 753                }
 754
 755                let mut diagnostic_highlight = HighlightStyle::default();
 756
 757                if chunk.is_unnecessary {
 758                    diagnostic_highlight.fade_out = Some(style.unnecessary_code_fade);
 759                }
 760
 761                if let Some(severity) = chunk.diagnostic_severity {
 762                    // Omit underlines for HINT/INFO diagnostics on 'unnecessary' code.
 763                    if severity <= DiagnosticSeverity::WARNING || !chunk.is_unnecessary {
 764                        let diagnostic_style = super::diagnostic_style(severity, true, style);
 765                        diagnostic_highlight.underline = Some(Underline {
 766                            color: Some(diagnostic_style.message.text.color),
 767                            thickness: 1.0.into(),
 768                            squiggly: true,
 769                        });
 770                    }
 771                }
 772
 773                if let Some(highlight_style) = highlight_style.as_mut() {
 774                    highlight_style.highlight(diagnostic_highlight);
 775                } else {
 776                    highlight_style = Some(diagnostic_highlight);
 777                }
 778
 779                (chunk.text, highlight_style)
 780            });
 781            layout_highlighted_chunks(
 782                chunks,
 783                &style.text,
 784                &cx.text_layout_cache,
 785                &cx.font_cache,
 786                MAX_LINE_LEN,
 787                rows.len() as usize,
 788            )
 789        }
 790    }
 791
 792    fn layout_blocks(
 793        &mut self,
 794        rows: Range<u32>,
 795        snapshot: &EditorSnapshot,
 796        editor_width: f32,
 797        scroll_width: f32,
 798        gutter_padding: f32,
 799        gutter_width: f32,
 800        em_width: f32,
 801        text_x: f32,
 802        line_height: f32,
 803        style: &EditorStyle,
 804        line_layouts: &[text_layout::Line],
 805        cx: &mut LayoutContext,
 806    ) -> (f32, Vec<BlockLayout>) {
 807        let editor = if let Some(editor) = self.view.upgrade(cx) {
 808            editor
 809        } else {
 810            return Default::default();
 811        };
 812
 813        let tooltip_style = cx.global::<Settings>().theme.tooltip.clone();
 814        let scroll_x = snapshot.scroll_position.x();
 815        let (fixed_blocks, non_fixed_blocks) = snapshot
 816            .blocks_in_range(rows.clone())
 817            .partition::<Vec<_>, _>(|(_, block)| match block {
 818                TransformBlock::ExcerptHeader { .. } => false,
 819                TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
 820            });
 821        let mut render_block = |block: &TransformBlock, width: f32| {
 822            let mut element = match block {
 823                TransformBlock::Custom(block) => {
 824                    let align_to = block
 825                        .position()
 826                        .to_point(&snapshot.buffer_snapshot)
 827                        .to_display_point(snapshot);
 828                    let anchor_x = text_x
 829                        + if rows.contains(&align_to.row()) {
 830                            line_layouts[(align_to.row() - rows.start) as usize]
 831                                .x_for_index(align_to.column() as usize)
 832                        } else {
 833                            layout_line(align_to.row(), snapshot, style, cx.text_layout_cache)
 834                                .x_for_index(align_to.column() as usize)
 835                        };
 836
 837                    cx.render(&editor, |_, cx| {
 838                        block.render(&mut BlockContext {
 839                            cx,
 840                            anchor_x,
 841                            gutter_padding,
 842                            line_height,
 843                            scroll_x,
 844                            gutter_width,
 845                            em_width,
 846                        })
 847                    })
 848                }
 849                TransformBlock::ExcerptHeader {
 850                    key,
 851                    buffer,
 852                    range,
 853                    starts_new_buffer,
 854                    ..
 855                } => {
 856                    let jump_icon = project::File::from_dyn(buffer.file()).map(|file| {
 857                        let jump_position = range
 858                            .primary
 859                            .as_ref()
 860                            .map_or(range.context.start, |primary| primary.start);
 861                        let jump_action = crate::Jump {
 862                            path: ProjectPath {
 863                                worktree_id: file.worktree_id(cx),
 864                                path: file.path.clone(),
 865                            },
 866                            position: language::ToPoint::to_point(&jump_position, buffer),
 867                            anchor: jump_position,
 868                        };
 869
 870                        enum JumpIcon {}
 871                        cx.render(&editor, |_, cx| {
 872                            MouseEventHandler::new::<JumpIcon, _, _>(*key, cx, |state, _| {
 873                                let style = style.jump_icon.style_for(state, false);
 874                                Svg::new("icons/jump.svg")
 875                                    .with_color(style.color)
 876                                    .constrained()
 877                                    .with_width(style.icon_width)
 878                                    .aligned()
 879                                    .contained()
 880                                    .with_style(style.container)
 881                                    .constrained()
 882                                    .with_width(style.button_width)
 883                                    .with_height(style.button_width)
 884                                    .boxed()
 885                            })
 886                            .with_cursor_style(CursorStyle::PointingHand)
 887                            .on_click(move |_, _, cx| cx.dispatch_action(jump_action.clone()))
 888                            .with_tooltip::<JumpIcon, _>(
 889                                *key,
 890                                "Jump to Buffer".to_string(),
 891                                Some(Box::new(crate::OpenExcerpts)),
 892                                tooltip_style.clone(),
 893                                cx,
 894                            )
 895                            .aligned()
 896                            .flex_float()
 897                            .boxed()
 898                        })
 899                    });
 900
 901                    if *starts_new_buffer {
 902                        let style = &self.style.diagnostic_path_header;
 903                        let font_size =
 904                            (style.text_scale_factor * self.style.text.font_size).round();
 905
 906                        let mut filename = None;
 907                        let mut parent_path = None;
 908                        if let Some(file) = buffer.file() {
 909                            let path = file.path();
 910                            filename = path.file_name().map(|f| f.to_string_lossy().to_string());
 911                            parent_path =
 912                                path.parent().map(|p| p.to_string_lossy().to_string() + "/");
 913                        }
 914
 915                        Flex::row()
 916                            .with_child(
 917                                Label::new(
 918                                    filename.unwrap_or_else(|| "untitled".to_string()),
 919                                    style.filename.text.clone().with_font_size(font_size),
 920                                )
 921                                .contained()
 922                                .with_style(style.filename.container)
 923                                .aligned()
 924                                .boxed(),
 925                            )
 926                            .with_children(parent_path.map(|path| {
 927                                Label::new(path, style.path.text.clone().with_font_size(font_size))
 928                                    .contained()
 929                                    .with_style(style.path.container)
 930                                    .aligned()
 931                                    .boxed()
 932                            }))
 933                            .with_children(jump_icon)
 934                            .contained()
 935                            .with_style(style.container)
 936                            .with_padding_left(gutter_padding)
 937                            .with_padding_right(gutter_padding)
 938                            .expanded()
 939                            .named("path header block")
 940                    } else {
 941                        let text_style = self.style.text.clone();
 942                        Flex::row()
 943                            .with_child(Label::new("".to_string(), text_style).boxed())
 944                            .with_children(jump_icon)
 945                            .contained()
 946                            .with_padding_left(gutter_padding)
 947                            .with_padding_right(gutter_padding)
 948                            .expanded()
 949                            .named("collapsed context")
 950                    }
 951                }
 952            };
 953
 954            element.layout(
 955                SizeConstraint {
 956                    min: Vector2F::zero(),
 957                    max: vec2f(width, block.height() as f32 * line_height),
 958                },
 959                cx,
 960            );
 961            element
 962        };
 963
 964        let mut fixed_block_max_width = 0f32;
 965        let mut blocks = Vec::new();
 966        for (row, block) in fixed_blocks {
 967            let element = render_block(block, f32::INFINITY);
 968            fixed_block_max_width = fixed_block_max_width.max(element.size().x() + em_width);
 969            blocks.push(BlockLayout {
 970                row,
 971                element,
 972                style: BlockStyle::Fixed,
 973            });
 974        }
 975        for (row, block) in non_fixed_blocks {
 976            let style = match block {
 977                TransformBlock::Custom(block) => block.style(),
 978                TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
 979            };
 980            let width = match style {
 981                BlockStyle::Sticky => editor_width,
 982                BlockStyle::Flex => editor_width
 983                    .max(fixed_block_max_width)
 984                    .max(gutter_width + scroll_width),
 985                BlockStyle::Fixed => unreachable!(),
 986            };
 987            let element = render_block(block, width);
 988            blocks.push(BlockLayout {
 989                row,
 990                element,
 991                style,
 992            });
 993        }
 994        (
 995            scroll_width.max(fixed_block_max_width - gutter_width),
 996            blocks,
 997        )
 998    }
 999}
1000
1001impl Element for EditorElement {
1002    type LayoutState = LayoutState;
1003    type PaintState = PaintState;
1004
1005    fn layout(
1006        &mut self,
1007        constraint: SizeConstraint,
1008        cx: &mut LayoutContext,
1009    ) -> (Vector2F, Self::LayoutState) {
1010        let mut size = constraint.max;
1011        if size.x().is_infinite() {
1012            unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
1013        }
1014
1015        let snapshot = self.snapshot(cx.app);
1016        let style = self.style.clone();
1017        let line_height = style.text.line_height(cx.font_cache);
1018
1019        let gutter_padding;
1020        let gutter_width;
1021        let gutter_margin;
1022        if snapshot.mode == EditorMode::Full {
1023            gutter_padding = style.text.em_width(cx.font_cache) * style.gutter_padding_factor;
1024            gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
1025            gutter_margin = -style.text.descent(cx.font_cache);
1026        } else {
1027            gutter_padding = 0.0;
1028            gutter_width = 0.0;
1029            gutter_margin = 0.0;
1030        };
1031
1032        let text_width = size.x() - gutter_width;
1033        let em_width = style.text.em_width(cx.font_cache);
1034        let em_advance = style.text.em_advance(cx.font_cache);
1035        let overscroll = vec2f(em_width, 0.);
1036        let snapshot = self.update_view(cx.app, |view, cx| {
1037            let wrap_width = match view.soft_wrap_mode(cx) {
1038                SoftWrap::None => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
1039                SoftWrap::EditorWidth => {
1040                    Some(text_width - gutter_margin - overscroll.x() - em_width)
1041                }
1042                SoftWrap::Column(column) => Some(column as f32 * em_advance),
1043            };
1044
1045            if view.set_wrap_width(wrap_width, cx) {
1046                view.snapshot(cx)
1047            } else {
1048                snapshot
1049            }
1050        });
1051
1052        let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
1053        if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
1054            size.set_y(
1055                scroll_height
1056                    .min(constraint.max_along(Axis::Vertical))
1057                    .max(constraint.min_along(Axis::Vertical))
1058                    .min(line_height * max_lines as f32),
1059            )
1060        } else if let EditorMode::SingleLine = snapshot.mode {
1061            size.set_y(
1062                line_height
1063                    .min(constraint.max_along(Axis::Vertical))
1064                    .max(constraint.min_along(Axis::Vertical)),
1065            )
1066        } else if size.y().is_infinite() {
1067            size.set_y(scroll_height);
1068        }
1069        let gutter_size = vec2f(gutter_width, size.y());
1070        let text_size = vec2f(text_width, size.y());
1071
1072        let (autoscroll_horizontally, mut snapshot) = self.update_view(cx.app, |view, cx| {
1073            let autoscroll_horizontally = view.autoscroll_vertically(size.y(), line_height, cx);
1074            let snapshot = view.snapshot(cx);
1075            (autoscroll_horizontally, snapshot)
1076        });
1077
1078        let scroll_position = snapshot.scroll_position();
1079        let start_row = scroll_position.y() as u32;
1080        let scroll_top = scroll_position.y() * line_height;
1081
1082        // Add 1 to ensure selections bleed off screen
1083        let end_row = 1 + cmp::min(
1084            ((scroll_top + size.y()) / line_height).ceil() as u32,
1085            snapshot.max_point().row(),
1086        );
1087
1088        let start_anchor = if start_row == 0 {
1089            Anchor::min()
1090        } else {
1091            snapshot
1092                .buffer_snapshot
1093                .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
1094        };
1095        let end_anchor = if end_row > snapshot.max_point().row() {
1096            Anchor::max()
1097        } else {
1098            snapshot
1099                .buffer_snapshot
1100                .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
1101        };
1102
1103        let mut selections: Vec<(ReplicaId, Vec<SelectionLayout>)> = Vec::new();
1104        let mut active_rows = BTreeMap::new();
1105        let mut highlighted_rows = None;
1106        let mut highlighted_ranges = Vec::new();
1107        self.update_view(cx.app, |view, cx| {
1108            let display_map = view.display_map.update(cx, |map, cx| map.snapshot(cx));
1109
1110            highlighted_rows = view.highlighted_rows();
1111            let theme = cx.global::<Settings>().theme.as_ref();
1112            highlighted_ranges = view.background_highlights_in_range(
1113                start_anchor.clone()..end_anchor.clone(),
1114                &display_map,
1115                theme,
1116            );
1117
1118            let mut remote_selections = HashMap::default();
1119            for (replica_id, line_mode, selection) in display_map
1120                .buffer_snapshot
1121                .remote_selections_in_range(&(start_anchor.clone()..end_anchor.clone()))
1122            {
1123                // The local selections match the leader's selections.
1124                if Some(replica_id) == view.leader_replica_id {
1125                    continue;
1126                }
1127                remote_selections
1128                    .entry(replica_id)
1129                    .or_insert(Vec::new())
1130                    .push(SelectionLayout::new(selection, line_mode, &display_map));
1131            }
1132            selections.extend(remote_selections);
1133
1134            if view.show_local_selections {
1135                let mut local_selections = view
1136                    .selections
1137                    .disjoint_in_range(start_anchor..end_anchor, cx);
1138                local_selections.extend(view.selections.pending(cx));
1139                for selection in &local_selections {
1140                    let is_empty = selection.start == selection.end;
1141                    let selection_start = snapshot.prev_line_boundary(selection.start).1;
1142                    let selection_end = snapshot.next_line_boundary(selection.end).1;
1143                    for row in cmp::max(selection_start.row(), start_row)
1144                        ..=cmp::min(selection_end.row(), end_row)
1145                    {
1146                        let contains_non_empty_selection =
1147                            active_rows.entry(row).or_insert(!is_empty);
1148                        *contains_non_empty_selection |= !is_empty;
1149                    }
1150                }
1151
1152                // Render the local selections in the leader's color when following.
1153                let local_replica_id = view.leader_replica_id.unwrap_or(view.replica_id(cx));
1154
1155                selections.push((
1156                    local_replica_id,
1157                    local_selections
1158                        .into_iter()
1159                        .map(|selection| {
1160                            SelectionLayout::new(selection, view.selections.line_mode, &display_map)
1161                        })
1162                        .collect(),
1163                ));
1164            }
1165        });
1166
1167        let line_number_layouts =
1168            self.layout_line_numbers(start_row..end_row, &active_rows, &snapshot, cx);
1169
1170        let mut max_visible_line_width = 0.0;
1171        let line_layouts = self.layout_lines(start_row..end_row, &snapshot, cx);
1172        for line in &line_layouts {
1173            if line.width() > max_visible_line_width {
1174                max_visible_line_width = line.width();
1175            }
1176        }
1177
1178        let style = self.style.clone();
1179        let longest_line_width = layout_line(
1180            snapshot.longest_row(),
1181            &snapshot,
1182            &style,
1183            cx.text_layout_cache,
1184        )
1185        .width();
1186        let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
1187        let em_width = style.text.em_width(cx.font_cache);
1188        let (scroll_width, blocks) = self.layout_blocks(
1189            start_row..end_row,
1190            &snapshot,
1191            size.x(),
1192            scroll_width,
1193            gutter_padding,
1194            gutter_width,
1195            em_width,
1196            gutter_width + gutter_margin,
1197            line_height,
1198            &style,
1199            &line_layouts,
1200            cx,
1201        );
1202
1203        let max_row = snapshot.max_point().row();
1204        let scroll_max = vec2f(
1205            ((scroll_width - text_size.x()) / em_width).max(0.0),
1206            max_row.saturating_sub(1) as f32,
1207        );
1208
1209        self.update_view(cx.app, |view, cx| {
1210            let clamped = view.clamp_scroll_left(scroll_max.x());
1211            let autoscrolled;
1212            if autoscroll_horizontally {
1213                autoscrolled = view.autoscroll_horizontally(
1214                    start_row,
1215                    text_size.x(),
1216                    scroll_width,
1217                    em_width,
1218                    &line_layouts,
1219                    cx,
1220                );
1221            } else {
1222                autoscrolled = false;
1223            }
1224
1225            if clamped || autoscrolled {
1226                snapshot = view.snapshot(cx);
1227            }
1228        });
1229
1230        let mut context_menu = None;
1231        let mut code_actions_indicator = None;
1232        let mut hover = None;
1233        cx.render(&self.view.upgrade(cx).unwrap(), |view, cx| {
1234            let newest_selection_head = view
1235                .selections
1236                .newest::<usize>(cx)
1237                .head()
1238                .to_display_point(&snapshot);
1239
1240            let style = view.style(cx);
1241            if (start_row..end_row).contains(&newest_selection_head.row()) {
1242                if view.context_menu_visible() {
1243                    context_menu =
1244                        view.render_context_menu(newest_selection_head, style.clone(), cx);
1245                }
1246
1247                code_actions_indicator = view
1248                    .render_code_actions_indicator(&style, cx)
1249                    .map(|indicator| (newest_selection_head.row(), indicator));
1250            }
1251
1252            hover = view.hover_state.popover.clone().and_then(|hover| {
1253                let (point, rendered) = hover.render(&snapshot, style.clone(), cx);
1254                if point.row() >= snapshot.scroll_position().y() as u32 {
1255                    if line_layouts.len() > (point.row() - start_row) as usize {
1256                        return Some((point, rendered));
1257                    }
1258                }
1259
1260                None
1261            });
1262        });
1263
1264        if let Some((_, context_menu)) = context_menu.as_mut() {
1265            context_menu.layout(
1266                SizeConstraint {
1267                    min: Vector2F::zero(),
1268                    max: vec2f(
1269                        cx.window_size.x() * 0.7,
1270                        (12. * line_height).min((size.y() - line_height) / 2.),
1271                    ),
1272                },
1273                cx,
1274            );
1275        }
1276
1277        if let Some((_, indicator)) = code_actions_indicator.as_mut() {
1278            indicator.layout(
1279                SizeConstraint::strict_along(Axis::Vertical, line_height * 0.618),
1280                cx,
1281            );
1282        }
1283
1284        if let Some((_, hover)) = hover.as_mut() {
1285            hover.layout(
1286                SizeConstraint {
1287                    min: Vector2F::zero(),
1288                    max: vec2f(
1289                        (120. * em_width) // Default size
1290                            .min(size.x() / 2.) // Shrink to half of the editor width
1291                            .max(20. * em_width), // Apply minimum width of 20 characters
1292                        (16. * line_height) // Default size
1293                            .min(size.y() / 2.) // Shrink to half of the editor height
1294                            .max(4. * line_height), // Apply minimum height of 4 lines
1295                    ),
1296                },
1297                cx,
1298            );
1299        }
1300
1301        (
1302            size,
1303            LayoutState {
1304                size,
1305                scroll_max,
1306                gutter_size,
1307                gutter_padding,
1308                text_size,
1309                gutter_margin,
1310                snapshot,
1311                active_rows,
1312                highlighted_rows,
1313                highlighted_ranges,
1314                line_layouts,
1315                line_number_layouts,
1316                blocks,
1317                line_height,
1318                em_width,
1319                em_advance,
1320                selections,
1321                context_menu,
1322                code_actions_indicator,
1323                hover,
1324            },
1325        )
1326    }
1327
1328    fn paint(
1329        &mut self,
1330        bounds: RectF,
1331        visible_bounds: RectF,
1332        layout: &mut Self::LayoutState,
1333        cx: &mut PaintContext,
1334    ) -> Self::PaintState {
1335        cx.scene.push_layer(Some(bounds));
1336
1337        let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
1338        let text_bounds = RectF::new(
1339            bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
1340            layout.text_size,
1341        );
1342
1343        let mut paint_state = PaintState {
1344            bounds,
1345            gutter_bounds,
1346            text_bounds,
1347            context_menu_bounds: None,
1348            hover_bounds: None,
1349        };
1350
1351        self.paint_background(gutter_bounds, text_bounds, layout, cx);
1352        if layout.gutter_size.x() > 0. {
1353            self.paint_gutter(gutter_bounds, visible_bounds, layout, cx);
1354        }
1355        self.paint_text(text_bounds, visible_bounds, layout, &mut paint_state, cx);
1356
1357        if !layout.blocks.is_empty() {
1358            cx.scene.push_layer(Some(bounds));
1359            self.paint_blocks(bounds, visible_bounds, layout, cx);
1360            cx.scene.pop_layer();
1361        }
1362
1363        cx.scene.pop_layer();
1364
1365        paint_state
1366    }
1367
1368    fn dispatch_event(
1369        &mut self,
1370        event: &Event,
1371        _: RectF,
1372        _: RectF,
1373        layout: &mut LayoutState,
1374        paint: &mut PaintState,
1375        cx: &mut EventContext,
1376    ) -> bool {
1377        if let Some((_, context_menu)) = &mut layout.context_menu {
1378            if context_menu.dispatch_event(event, cx) {
1379                return true;
1380            }
1381        }
1382
1383        if let Some((_, indicator)) = &mut layout.code_actions_indicator {
1384            if indicator.dispatch_event(event, cx) {
1385                return true;
1386            }
1387        }
1388
1389        if let Some((_, hover)) = &mut layout.hover {
1390            if hover.dispatch_event(event, cx) {
1391                return true;
1392            }
1393        }
1394
1395        for block in &mut layout.blocks {
1396            if block.element.dispatch_event(event, cx) {
1397                return true;
1398            }
1399        }
1400
1401        match event {
1402            Event::LeftMouseDown {
1403                position,
1404                cmd,
1405                alt,
1406                shift,
1407                click_count,
1408                ..
1409            } => self.mouse_down(
1410                *position,
1411                *cmd,
1412                *alt,
1413                *shift,
1414                *click_count,
1415                layout,
1416                paint,
1417                cx,
1418            ),
1419            Event::LeftMouseUp { position, .. } => self.mouse_up(*position, cx),
1420            Event::LeftMouseDragged { position } => {
1421                self.mouse_dragged(*position, layout, paint, cx)
1422            }
1423            Event::ScrollWheel {
1424                position,
1425                delta,
1426                precise,
1427            } => self.scroll(*position, *delta, *precise, layout, paint, cx),
1428            Event::KeyDown { input, .. } => self.key_down(input.as_deref(), cx),
1429            Event::MouseMoved { position, .. } => {
1430                // This will be handled more correctly once https://github.com/zed-industries/zed/issues/1218 is completed
1431                // Don't trigger hover popover if mouse is hovering over context menu
1432                if paint
1433                    .context_menu_bounds
1434                    .map_or(false, |context_menu_bounds| {
1435                        context_menu_bounds.contains_point(*position)
1436                    })
1437                {
1438                    return false;
1439                }
1440
1441                if paint
1442                    .hover_bounds
1443                    .map_or(false, |hover_bounds| hover_bounds.contains_point(*position))
1444                {
1445                    return false;
1446                }
1447                
1448                let point = if paint.text_bounds.contains_point(*position) {
1449                    let (point, overshoot) =
1450                        paint.point_for_position(&self.snapshot(cx), layout, *position);
1451                    if overshoot.is_zero() {
1452                        Some(point)
1453                    } else {
1454                        None
1455                    }
1456                } else {
1457                    None
1458                };
1459
1460                cx.dispatch_action(HoverAt { point });
1461                true
1462            }
1463            _ => false,
1464        }
1465    }
1466
1467    fn debug(
1468        &self,
1469        bounds: RectF,
1470        _: &Self::LayoutState,
1471        _: &Self::PaintState,
1472        _: &gpui::DebugContext,
1473    ) -> json::Value {
1474        json!({
1475            "type": "BufferElement",
1476            "bounds": bounds.to_json()
1477        })
1478    }
1479}
1480
1481pub struct LayoutState {
1482    size: Vector2F,
1483    scroll_max: Vector2F,
1484    gutter_size: Vector2F,
1485    gutter_padding: f32,
1486    gutter_margin: f32,
1487    text_size: Vector2F,
1488    snapshot: EditorSnapshot,
1489    active_rows: BTreeMap<u32, bool>,
1490    highlighted_rows: Option<Range<u32>>,
1491    line_layouts: Vec<text_layout::Line>,
1492    line_number_layouts: Vec<Option<text_layout::Line>>,
1493    blocks: Vec<BlockLayout>,
1494    line_height: f32,
1495    em_width: f32,
1496    em_advance: f32,
1497    highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
1498    selections: Vec<(ReplicaId, Vec<SelectionLayout>)>,
1499    context_menu: Option<(DisplayPoint, ElementBox)>,
1500    code_actions_indicator: Option<(u32, ElementBox)>,
1501    hover: Option<(DisplayPoint, ElementBox)>,
1502}
1503
1504struct BlockLayout {
1505    row: u32,
1506    element: ElementBox,
1507    style: BlockStyle,
1508}
1509
1510fn layout_line(
1511    row: u32,
1512    snapshot: &EditorSnapshot,
1513    style: &EditorStyle,
1514    layout_cache: &TextLayoutCache,
1515) -> text_layout::Line {
1516    let mut line = snapshot.line(row);
1517
1518    if line.len() > MAX_LINE_LEN {
1519        let mut len = MAX_LINE_LEN;
1520        while !line.is_char_boundary(len) {
1521            len -= 1;
1522        }
1523
1524        line.truncate(len);
1525    }
1526
1527    layout_cache.layout_str(
1528        &line,
1529        style.text.font_size,
1530        &[(
1531            snapshot.line_len(row) as usize,
1532            RunStyle {
1533                font_id: style.text.font_id,
1534                color: Color::black(),
1535                underline: Default::default(),
1536            },
1537        )],
1538    )
1539}
1540
1541pub struct PaintState {
1542    bounds: RectF,
1543    gutter_bounds: RectF,
1544    text_bounds: RectF,
1545    context_menu_bounds: Option<RectF>,
1546    hover_bounds: Option<RectF>,
1547}
1548
1549impl PaintState {
1550    /// Returns two display points. The first is the nearest valid
1551    /// position in the current buffer and the second is the distance to the
1552    /// nearest valid position if there was overshoot.
1553    fn point_for_position(
1554        &self,
1555        snapshot: &EditorSnapshot,
1556        layout: &LayoutState,
1557        position: Vector2F,
1558    ) -> (DisplayPoint, DisplayPoint) {
1559        let scroll_position = snapshot.scroll_position();
1560        let position = position - self.text_bounds.origin();
1561        let y = position.y().max(0.0).min(layout.size.y());
1562        let row = ((y / layout.line_height) + scroll_position.y()) as u32;
1563        let row_overshoot = row.saturating_sub(snapshot.max_point().row());
1564        let row = cmp::min(row, snapshot.max_point().row());
1565        let line = &layout.line_layouts[(row - scroll_position.y() as u32) as usize];
1566        let x = position.x() + (scroll_position.x() * layout.em_width);
1567
1568        let column = if x >= 0.0 {
1569            line.index_for_x(x)
1570                .map(|ix| ix as u32)
1571                .unwrap_or_else(|| snapshot.line_len(row))
1572        } else {
1573            0
1574        };
1575        let column_overshoot = (0f32.max(x - line.width()) / layout.em_advance) as u32;
1576
1577        (
1578            DisplayPoint::new(row, column),
1579            DisplayPoint::new(row_overshoot, column_overshoot),
1580        )
1581    }
1582}
1583
1584#[derive(Copy, Clone, PartialEq, Eq)]
1585pub enum CursorShape {
1586    Bar,
1587    Block,
1588    Underscore,
1589}
1590
1591impl Default for CursorShape {
1592    fn default() -> Self {
1593        CursorShape::Bar
1594    }
1595}
1596
1597struct Cursor {
1598    origin: Vector2F,
1599    block_width: f32,
1600    line_height: f32,
1601    color: Color,
1602    shape: CursorShape,
1603    block_text: Option<Line>,
1604}
1605
1606impl Cursor {
1607    fn paint(&self, cx: &mut PaintContext) {
1608        let bounds = match self.shape {
1609            CursorShape::Bar => RectF::new(self.origin, vec2f(2.0, self.line_height)),
1610            CursorShape::Block => {
1611                RectF::new(self.origin, vec2f(self.block_width, self.line_height))
1612            }
1613            CursorShape::Underscore => RectF::new(
1614                self.origin + Vector2F::new(0.0, self.line_height - 2.0),
1615                vec2f(self.block_width, 2.0),
1616            ),
1617        };
1618
1619        cx.scene.push_quad(Quad {
1620            bounds,
1621            background: Some(self.color),
1622            border: Border::new(0., Color::black()),
1623            corner_radius: 0.,
1624        });
1625
1626        if let Some(block_text) = &self.block_text {
1627            block_text.paint(self.origin, bounds, self.line_height, cx);
1628        }
1629    }
1630}
1631
1632#[derive(Debug)]
1633struct HighlightedRange {
1634    start_y: f32,
1635    line_height: f32,
1636    lines: Vec<HighlightedRangeLine>,
1637    color: Color,
1638    corner_radius: f32,
1639}
1640
1641#[derive(Debug)]
1642struct HighlightedRangeLine {
1643    start_x: f32,
1644    end_x: f32,
1645}
1646
1647impl HighlightedRange {
1648    fn paint(&self, bounds: RectF, scene: &mut Scene) {
1649        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
1650            self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
1651            self.paint_lines(
1652                self.start_y + self.line_height,
1653                &self.lines[1..],
1654                bounds,
1655                scene,
1656            );
1657        } else {
1658            self.paint_lines(self.start_y, &self.lines, bounds, scene);
1659        }
1660    }
1661
1662    fn paint_lines(
1663        &self,
1664        start_y: f32,
1665        lines: &[HighlightedRangeLine],
1666        bounds: RectF,
1667        scene: &mut Scene,
1668    ) {
1669        if lines.is_empty() {
1670            return;
1671        }
1672
1673        let mut path = PathBuilder::new();
1674        let first_line = lines.first().unwrap();
1675        let last_line = lines.last().unwrap();
1676
1677        let first_top_left = vec2f(first_line.start_x, start_y);
1678        let first_top_right = vec2f(first_line.end_x, start_y);
1679
1680        let curve_height = vec2f(0., self.corner_radius);
1681        let curve_width = |start_x: f32, end_x: f32| {
1682            let max = (end_x - start_x) / 2.;
1683            let width = if max < self.corner_radius {
1684                max
1685            } else {
1686                self.corner_radius
1687            };
1688
1689            vec2f(width, 0.)
1690        };
1691
1692        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
1693        path.reset(first_top_right - top_curve_width);
1694        path.curve_to(first_top_right + curve_height, first_top_right);
1695
1696        let mut iter = lines.iter().enumerate().peekable();
1697        while let Some((ix, line)) = iter.next() {
1698            let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
1699
1700            if let Some((_, next_line)) = iter.peek() {
1701                let next_top_right = vec2f(next_line.end_x, bottom_right.y());
1702
1703                match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
1704                    Ordering::Equal => {
1705                        path.line_to(bottom_right);
1706                    }
1707                    Ordering::Less => {
1708                        let curve_width = curve_width(next_top_right.x(), bottom_right.x());
1709                        path.line_to(bottom_right - curve_height);
1710                        if self.corner_radius > 0. {
1711                            path.curve_to(bottom_right - curve_width, bottom_right);
1712                        }
1713                        path.line_to(next_top_right + curve_width);
1714                        if self.corner_radius > 0. {
1715                            path.curve_to(next_top_right + curve_height, next_top_right);
1716                        }
1717                    }
1718                    Ordering::Greater => {
1719                        let curve_width = curve_width(bottom_right.x(), next_top_right.x());
1720                        path.line_to(bottom_right - curve_height);
1721                        if self.corner_radius > 0. {
1722                            path.curve_to(bottom_right + curve_width, bottom_right);
1723                        }
1724                        path.line_to(next_top_right - curve_width);
1725                        if self.corner_radius > 0. {
1726                            path.curve_to(next_top_right + curve_height, next_top_right);
1727                        }
1728                    }
1729                }
1730            } else {
1731                let curve_width = curve_width(line.start_x, line.end_x);
1732                path.line_to(bottom_right - curve_height);
1733                if self.corner_radius > 0. {
1734                    path.curve_to(bottom_right - curve_width, bottom_right);
1735                }
1736
1737                let bottom_left = vec2f(line.start_x, bottom_right.y());
1738                path.line_to(bottom_left + curve_width);
1739                if self.corner_radius > 0. {
1740                    path.curve_to(bottom_left - curve_height, bottom_left);
1741                }
1742            }
1743        }
1744
1745        if first_line.start_x > last_line.start_x {
1746            let curve_width = curve_width(last_line.start_x, first_line.start_x);
1747            let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
1748            path.line_to(second_top_left + curve_height);
1749            if self.corner_radius > 0. {
1750                path.curve_to(second_top_left + curve_width, second_top_left);
1751            }
1752            let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
1753            path.line_to(first_bottom_left - curve_width);
1754            if self.corner_radius > 0. {
1755                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
1756            }
1757        }
1758
1759        path.line_to(first_top_left + curve_height);
1760        if self.corner_radius > 0. {
1761            path.curve_to(first_top_left + top_curve_width, first_top_left);
1762        }
1763        path.line_to(first_top_right - top_curve_width);
1764
1765        scene.push_path(path.build(self.color, Some(bounds)));
1766    }
1767}
1768
1769fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
1770    delta.powf(1.5) / 100.0
1771}
1772
1773fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
1774    delta.powf(1.2) / 300.0
1775}
1776
1777#[cfg(test)]
1778mod tests {
1779    use std::sync::Arc;
1780
1781    use super::*;
1782    use crate::{
1783        display_map::{BlockDisposition, BlockProperties},
1784        Editor, MultiBuffer,
1785    };
1786    use settings::Settings;
1787    use util::test::sample_text;
1788
1789    #[gpui::test]
1790    fn test_layout_line_numbers(cx: &mut gpui::MutableAppContext) {
1791        cx.set_global(Settings::test(cx));
1792        let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
1793        let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1794            Editor::new(EditorMode::Full, buffer, None, None, None, cx)
1795        });
1796        let element = EditorElement::new(
1797            editor.downgrade(),
1798            editor.read(cx).style(cx),
1799            CursorShape::Bar,
1800        );
1801
1802        let layouts = editor.update(cx, |editor, cx| {
1803            let snapshot = editor.snapshot(cx);
1804            let mut presenter = cx.build_presenter(window_id, 30.);
1805            let mut layout_cx = presenter.build_layout_context(Vector2F::zero(), false, cx);
1806            element.layout_line_numbers(0..6, &Default::default(), &snapshot, &mut layout_cx)
1807        });
1808        assert_eq!(layouts.len(), 6);
1809    }
1810
1811    #[gpui::test]
1812    fn test_layout_with_placeholder_text_and_blocks(cx: &mut gpui::MutableAppContext) {
1813        cx.set_global(Settings::test(cx));
1814        let buffer = MultiBuffer::build_simple("", cx);
1815        let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1816            Editor::new(EditorMode::Full, buffer, None, None, None, cx)
1817        });
1818
1819        editor.update(cx, |editor, cx| {
1820            editor.set_placeholder_text("hello", cx);
1821            editor.insert_blocks(
1822                [BlockProperties {
1823                    style: BlockStyle::Fixed,
1824                    disposition: BlockDisposition::Above,
1825                    height: 3,
1826                    position: Anchor::min(),
1827                    render: Arc::new(|_| Empty::new().boxed()),
1828                }],
1829                cx,
1830            );
1831
1832            // Blur the editor so that it displays placeholder text.
1833            cx.blur();
1834        });
1835
1836        let mut element = EditorElement::new(
1837            editor.downgrade(),
1838            editor.read(cx).style(cx),
1839            CursorShape::Bar,
1840        );
1841
1842        let mut scene = Scene::new(1.0);
1843        let mut presenter = cx.build_presenter(window_id, 30.);
1844        let mut layout_cx = presenter.build_layout_context(Vector2F::zero(), false, cx);
1845        let (size, mut state) = element.layout(
1846            SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
1847            &mut layout_cx,
1848        );
1849
1850        assert_eq!(state.line_layouts.len(), 4);
1851        assert_eq!(
1852            state
1853                .line_number_layouts
1854                .iter()
1855                .map(Option::is_some)
1856                .collect::<Vec<_>>(),
1857            &[false, false, false, true]
1858        );
1859
1860        // Don't panic.
1861        let bounds = RectF::new(Default::default(), size);
1862        let mut paint_cx = presenter.build_paint_context(&mut scene, bounds.size(), cx);
1863        element.paint(bounds, bounds, &mut state, &mut paint_cx);
1864    }
1865}