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