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 let CursorShape::Block = self.cursor_shape {
 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: 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(content_origin, 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            let cursor_row_layout = &layout.line_layouts[(position.row() - start_row) as usize];
 556            let x = cursor_row_layout.x_for_index(position.column() as usize) - scroll_left;
 557            let y = (position.row() + 1) as f32 * layout.line_height - scroll_top;
 558            let mut list_origin = content_origin + vec2f(x, y);
 559            let list_width = context_menu.size().x();
 560            let list_height = context_menu.size().y();
 561
 562            // Snap the right edge of the list to the right edge of the window if
 563            // its horizontal bounds overflow.
 564            if list_origin.x() + list_width > cx.window_size.x() {
 565                list_origin.set_x((cx.window_size.x() - list_width).max(0.));
 566            }
 567
 568            if list_origin.y() + list_height > bounds.max_y() {
 569                list_origin.set_y(list_origin.y() - layout.line_height - list_height);
 570            }
 571
 572            context_menu.paint(
 573                list_origin,
 574                RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
 575                cx,
 576            );
 577
 578            paint.context_menu_bounds = Some(RectF::new(list_origin, context_menu.size()));
 579
 580            cx.scene.pop_stacking_context();
 581        }
 582
 583        if let Some((position, hover_popover)) = layout.hover.as_mut() {
 584            cx.scene.push_stacking_context(None);
 585
 586            // This is safe because we check on layout whether the required row is available
 587            let hovered_row_layout = &layout.line_layouts[(position.row() - start_row) as usize];
 588            let size = hover_popover.size();
 589            let x = hovered_row_layout.x_for_index(position.column() as usize) - scroll_left;
 590            let y = position.row() as f32 * layout.line_height - scroll_top - size.y();
 591            let mut popover_origin = content_origin + vec2f(x, y);
 592
 593            if popover_origin.y() < 0.0 {
 594                popover_origin.set_y(popover_origin.y() + layout.line_height + size.y());
 595            }
 596
 597            let x_out_of_bounds = bounds.max_x() - (popover_origin.x() + size.x());
 598            if x_out_of_bounds < 0.0 {
 599                popover_origin.set_x(popover_origin.x() + x_out_of_bounds);
 600            }
 601
 602            hover_popover.paint(
 603                popover_origin,
 604                RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
 605                cx,
 606            );
 607
 608            paint.hover_bounds = Some(
 609                RectF::new(popover_origin, hover_popover.size()).dilate(Vector2F::new(0., 5.)),
 610            );
 611
 612            cx.scene.pop_stacking_context();
 613        }
 614
 615        cx.scene.pop_layer();
 616    }
 617
 618    fn paint_highlighted_range(
 619        &self,
 620        range: Range<DisplayPoint>,
 621        start_row: u32,
 622        end_row: u32,
 623        color: Color,
 624        corner_radius: f32,
 625        line_end_overshoot: f32,
 626        layout: &LayoutState,
 627        content_origin: Vector2F,
 628        scroll_top: f32,
 629        scroll_left: f32,
 630        bounds: RectF,
 631        cx: &mut PaintContext,
 632    ) {
 633        if range.start != range.end {
 634            let row_range = if range.end.column() == 0 {
 635                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
 636            } else {
 637                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
 638            };
 639
 640            let highlighted_range = HighlightedRange {
 641                color,
 642                line_height: layout.line_height,
 643                corner_radius,
 644                start_y: content_origin.y() + row_range.start as f32 * layout.line_height
 645                    - scroll_top,
 646                lines: row_range
 647                    .into_iter()
 648                    .map(|row| {
 649                        let line_layout = &layout.line_layouts[(row - start_row) as usize];
 650                        HighlightedRangeLine {
 651                            start_x: if row == range.start.row() {
 652                                content_origin.x()
 653                                    + line_layout.x_for_index(range.start.column() as usize)
 654                                    - scroll_left
 655                            } else {
 656                                content_origin.x() - scroll_left
 657                            },
 658                            end_x: if row == range.end.row() {
 659                                content_origin.x()
 660                                    + line_layout.x_for_index(range.end.column() as usize)
 661                                    - scroll_left
 662                            } else {
 663                                content_origin.x() + line_layout.width() + line_end_overshoot
 664                                    - scroll_left
 665                            },
 666                        }
 667                    })
 668                    .collect(),
 669            };
 670
 671            highlighted_range.paint(bounds, cx.scene);
 672        }
 673    }
 674
 675    fn paint_blocks(
 676        &mut self,
 677        bounds: RectF,
 678        visible_bounds: RectF,
 679        layout: &mut LayoutState,
 680        cx: &mut PaintContext,
 681    ) {
 682        let scroll_position = layout.snapshot.scroll_position();
 683        let scroll_left = scroll_position.x() * layout.em_width;
 684        let scroll_top = scroll_position.y() * layout.line_height;
 685
 686        for block in &mut layout.blocks {
 687            let mut origin =
 688                bounds.origin() + vec2f(0., block.row as f32 * layout.line_height - scroll_top);
 689            if !matches!(block.style, BlockStyle::Sticky) {
 690                origin += vec2f(-scroll_left, 0.);
 691            }
 692            block.element.paint(origin, visible_bounds, cx);
 693        }
 694    }
 695
 696    fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &LayoutContext) -> f32 {
 697        let digit_count = (snapshot.max_buffer_row() as f32).log10().floor() as usize + 1;
 698        let style = &self.style;
 699
 700        cx.text_layout_cache
 701            .layout_str(
 702                "1".repeat(digit_count).as_str(),
 703                style.text.font_size,
 704                &[(
 705                    digit_count,
 706                    RunStyle {
 707                        font_id: style.text.font_id,
 708                        color: Color::black(),
 709                        underline: Default::default(),
 710                    },
 711                )],
 712            )
 713            .width()
 714    }
 715
 716    fn layout_line_numbers(
 717        &self,
 718        rows: Range<u32>,
 719        active_rows: &BTreeMap<u32, bool>,
 720        snapshot: &EditorSnapshot,
 721        cx: &LayoutContext,
 722    ) -> Vec<Option<text_layout::Line>> {
 723        let style = &self.style;
 724        let include_line_numbers = snapshot.mode == EditorMode::Full;
 725        let mut line_number_layouts = Vec::with_capacity(rows.len());
 726        let mut line_number = String::new();
 727        for (ix, row) in snapshot
 728            .buffer_rows(rows.start)
 729            .take((rows.end - rows.start) as usize)
 730            .enumerate()
 731        {
 732            let display_row = rows.start + ix as u32;
 733            let color = if active_rows.contains_key(&display_row) {
 734                style.line_number_active
 735            } else {
 736                style.line_number
 737            };
 738            if let Some(buffer_row) = row {
 739                if include_line_numbers {
 740                    line_number.clear();
 741                    write!(&mut line_number, "{}", buffer_row + 1).unwrap();
 742                    line_number_layouts.push(Some(cx.text_layout_cache.layout_str(
 743                        &line_number,
 744                        style.text.font_size,
 745                        &[(
 746                            line_number.len(),
 747                            RunStyle {
 748                                font_id: style.text.font_id,
 749                                color,
 750                                underline: Default::default(),
 751                            },
 752                        )],
 753                    )));
 754                }
 755            } else {
 756                line_number_layouts.push(None);
 757            }
 758        }
 759
 760        line_number_layouts
 761    }
 762
 763    fn layout_lines(
 764        &mut self,
 765        rows: Range<u32>,
 766        snapshot: &EditorSnapshot,
 767        cx: &LayoutContext,
 768    ) -> Vec<text_layout::Line> {
 769        if rows.start >= rows.end {
 770            return Vec::new();
 771        }
 772
 773        // When the editor is empty and unfocused, then show the placeholder.
 774        if snapshot.is_empty() && !snapshot.is_focused() {
 775            let placeholder_style = self
 776                .style
 777                .placeholder_text
 778                .as_ref()
 779                .unwrap_or_else(|| &self.style.text);
 780            let placeholder_text = snapshot.placeholder_text();
 781            let placeholder_lines = placeholder_text
 782                .as_ref()
 783                .map_or("", AsRef::as_ref)
 784                .split('\n')
 785                .skip(rows.start as usize)
 786                .chain(iter::repeat(""))
 787                .take(rows.len());
 788            return placeholder_lines
 789                .map(|line| {
 790                    cx.text_layout_cache.layout_str(
 791                        line,
 792                        placeholder_style.font_size,
 793                        &[(
 794                            line.len(),
 795                            RunStyle {
 796                                font_id: placeholder_style.font_id,
 797                                color: placeholder_style.color,
 798                                underline: Default::default(),
 799                            },
 800                        )],
 801                    )
 802                })
 803                .collect();
 804        } else {
 805            let style = &self.style;
 806            let chunks = snapshot.chunks(rows.clone(), true).map(|chunk| {
 807                let mut highlight_style = chunk
 808                    .syntax_highlight_id
 809                    .and_then(|id| id.style(&style.syntax));
 810
 811                if let Some(chunk_highlight) = chunk.highlight_style {
 812                    if let Some(highlight_style) = highlight_style.as_mut() {
 813                        highlight_style.highlight(chunk_highlight);
 814                    } else {
 815                        highlight_style = Some(chunk_highlight);
 816                    }
 817                }
 818
 819                let mut diagnostic_highlight = HighlightStyle::default();
 820
 821                if chunk.is_unnecessary {
 822                    diagnostic_highlight.fade_out = Some(style.unnecessary_code_fade);
 823                }
 824
 825                if let Some(severity) = chunk.diagnostic_severity {
 826                    // Omit underlines for HINT/INFO diagnostics on 'unnecessary' code.
 827                    if severity <= DiagnosticSeverity::WARNING || !chunk.is_unnecessary {
 828                        let diagnostic_style = super::diagnostic_style(severity, true, style);
 829                        diagnostic_highlight.underline = Some(Underline {
 830                            color: Some(diagnostic_style.message.text.color),
 831                            thickness: 1.0.into(),
 832                            squiggly: true,
 833                        });
 834                    }
 835                }
 836
 837                if let Some(highlight_style) = highlight_style.as_mut() {
 838                    highlight_style.highlight(diagnostic_highlight);
 839                } else {
 840                    highlight_style = Some(diagnostic_highlight);
 841                }
 842
 843                (chunk.text, highlight_style)
 844            });
 845            layout_highlighted_chunks(
 846                chunks,
 847                &style.text,
 848                &cx.text_layout_cache,
 849                &cx.font_cache,
 850                MAX_LINE_LEN,
 851                rows.len() as usize,
 852            )
 853        }
 854    }
 855
 856    fn layout_blocks(
 857        &mut self,
 858        rows: Range<u32>,
 859        snapshot: &EditorSnapshot,
 860        editor_width: f32,
 861        scroll_width: f32,
 862        gutter_padding: f32,
 863        gutter_width: f32,
 864        em_width: f32,
 865        text_x: f32,
 866        line_height: f32,
 867        style: &EditorStyle,
 868        line_layouts: &[text_layout::Line],
 869        cx: &mut LayoutContext,
 870    ) -> (f32, Vec<BlockLayout>) {
 871        let editor = if let Some(editor) = self.view.upgrade(cx) {
 872            editor
 873        } else {
 874            return Default::default();
 875        };
 876
 877        let tooltip_style = cx.global::<Settings>().theme.tooltip.clone();
 878        let scroll_x = snapshot.scroll_position.x();
 879        let (fixed_blocks, non_fixed_blocks) = snapshot
 880            .blocks_in_range(rows.clone())
 881            .partition::<Vec<_>, _>(|(_, block)| match block {
 882                TransformBlock::ExcerptHeader { .. } => false,
 883                TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
 884            });
 885        let mut render_block = |block: &TransformBlock, width: f32| {
 886            let mut element = match block {
 887                TransformBlock::Custom(block) => {
 888                    let align_to = block
 889                        .position()
 890                        .to_point(&snapshot.buffer_snapshot)
 891                        .to_display_point(snapshot);
 892                    let anchor_x = text_x
 893                        + if rows.contains(&align_to.row()) {
 894                            line_layouts[(align_to.row() - rows.start) as usize]
 895                                .x_for_index(align_to.column() as usize)
 896                        } else {
 897                            layout_line(align_to.row(), snapshot, style, cx.text_layout_cache)
 898                                .x_for_index(align_to.column() as usize)
 899                        };
 900
 901                    cx.render(&editor, |_, cx| {
 902                        block.render(&mut BlockContext {
 903                            cx,
 904                            anchor_x,
 905                            gutter_padding,
 906                            line_height,
 907                            scroll_x,
 908                            gutter_width,
 909                            em_width,
 910                        })
 911                    })
 912                }
 913                TransformBlock::ExcerptHeader {
 914                    key,
 915                    buffer,
 916                    range,
 917                    starts_new_buffer,
 918                    ..
 919                } => {
 920                    let jump_icon = project::File::from_dyn(buffer.file()).map(|file| {
 921                        let jump_position = range
 922                            .primary
 923                            .as_ref()
 924                            .map_or(range.context.start, |primary| primary.start);
 925                        let jump_action = crate::Jump {
 926                            path: ProjectPath {
 927                                worktree_id: file.worktree_id(cx),
 928                                path: file.path.clone(),
 929                            },
 930                            position: language::ToPoint::to_point(&jump_position, buffer),
 931                            anchor: jump_position,
 932                        };
 933
 934                        enum JumpIcon {}
 935                        cx.render(&editor, |_, cx| {
 936                            MouseEventHandler::new::<JumpIcon, _, _>(*key, cx, |state, _| {
 937                                let style = style.jump_icon.style_for(state, false);
 938                                Svg::new("icons/jump.svg")
 939                                    .with_color(style.color)
 940                                    .constrained()
 941                                    .with_width(style.icon_width)
 942                                    .aligned()
 943                                    .contained()
 944                                    .with_style(style.container)
 945                                    .constrained()
 946                                    .with_width(style.button_width)
 947                                    .with_height(style.button_width)
 948                                    .boxed()
 949                            })
 950                            .with_cursor_style(CursorStyle::PointingHand)
 951                            .on_click(move |_, _, cx| cx.dispatch_action(jump_action.clone()))
 952                            .with_tooltip::<JumpIcon, _>(
 953                                *key,
 954                                "Jump to Buffer".to_string(),
 955                                Some(Box::new(crate::OpenExcerpts)),
 956                                tooltip_style.clone(),
 957                                cx,
 958                            )
 959                            .aligned()
 960                            .flex_float()
 961                            .boxed()
 962                        })
 963                    });
 964
 965                    if *starts_new_buffer {
 966                        let style = &self.style.diagnostic_path_header;
 967                        let font_size =
 968                            (style.text_scale_factor * self.style.text.font_size).round();
 969
 970                        let mut filename = None;
 971                        let mut parent_path = None;
 972                        if let Some(file) = buffer.file() {
 973                            let path = file.path();
 974                            filename = path.file_name().map(|f| f.to_string_lossy().to_string());
 975                            parent_path =
 976                                path.parent().map(|p| p.to_string_lossy().to_string() + "/");
 977                        }
 978
 979                        Flex::row()
 980                            .with_child(
 981                                Label::new(
 982                                    filename.unwrap_or_else(|| "untitled".to_string()),
 983                                    style.filename.text.clone().with_font_size(font_size),
 984                                )
 985                                .contained()
 986                                .with_style(style.filename.container)
 987                                .aligned()
 988                                .boxed(),
 989                            )
 990                            .with_children(parent_path.map(|path| {
 991                                Label::new(path, style.path.text.clone().with_font_size(font_size))
 992                                    .contained()
 993                                    .with_style(style.path.container)
 994                                    .aligned()
 995                                    .boxed()
 996                            }))
 997                            .with_children(jump_icon)
 998                            .contained()
 999                            .with_style(style.container)
1000                            .with_padding_left(gutter_padding)
1001                            .with_padding_right(gutter_padding)
1002                            .expanded()
1003                            .named("path header block")
1004                    } else {
1005                        let text_style = self.style.text.clone();
1006                        Flex::row()
1007                            .with_child(Label::new("".to_string(), text_style).boxed())
1008                            .with_children(jump_icon)
1009                            .contained()
1010                            .with_padding_left(gutter_padding)
1011                            .with_padding_right(gutter_padding)
1012                            .expanded()
1013                            .named("collapsed context")
1014                    }
1015                }
1016            };
1017
1018            element.layout(
1019                SizeConstraint {
1020                    min: Vector2F::zero(),
1021                    max: vec2f(width, block.height() as f32 * line_height),
1022                },
1023                cx,
1024            );
1025            element
1026        };
1027
1028        let mut fixed_block_max_width = 0f32;
1029        let mut blocks = Vec::new();
1030        for (row, block) in fixed_blocks {
1031            let element = render_block(block, f32::INFINITY);
1032            fixed_block_max_width = fixed_block_max_width.max(element.size().x() + em_width);
1033            blocks.push(BlockLayout {
1034                row,
1035                element,
1036                style: BlockStyle::Fixed,
1037            });
1038        }
1039        for (row, block) in non_fixed_blocks {
1040            let style = match block {
1041                TransformBlock::Custom(block) => block.style(),
1042                TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
1043            };
1044            let width = match style {
1045                BlockStyle::Sticky => editor_width,
1046                BlockStyle::Flex => editor_width
1047                    .max(fixed_block_max_width)
1048                    .max(gutter_width + scroll_width),
1049                BlockStyle::Fixed => unreachable!(),
1050            };
1051            let element = render_block(block, width);
1052            blocks.push(BlockLayout {
1053                row,
1054                element,
1055                style,
1056            });
1057        }
1058        (
1059            scroll_width.max(fixed_block_max_width - gutter_width),
1060            blocks,
1061        )
1062    }
1063}
1064
1065impl Element for EditorElement {
1066    type LayoutState = LayoutState;
1067    type PaintState = PaintState;
1068
1069    fn layout(
1070        &mut self,
1071        constraint: SizeConstraint,
1072        cx: &mut LayoutContext,
1073    ) -> (Vector2F, Self::LayoutState) {
1074        let mut size = constraint.max;
1075        if size.x().is_infinite() {
1076            unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
1077        }
1078
1079        let snapshot = self.snapshot(cx.app);
1080        let style = self.style.clone();
1081        let line_height = style.text.line_height(cx.font_cache);
1082
1083        let gutter_padding;
1084        let gutter_width;
1085        let gutter_margin;
1086        if snapshot.mode == EditorMode::Full {
1087            gutter_padding = style.text.em_width(cx.font_cache) * style.gutter_padding_factor;
1088            gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
1089            gutter_margin = -style.text.descent(cx.font_cache);
1090        } else {
1091            gutter_padding = 0.0;
1092            gutter_width = 0.0;
1093            gutter_margin = 0.0;
1094        };
1095
1096        let text_width = size.x() - gutter_width;
1097        let em_width = style.text.em_width(cx.font_cache);
1098        let em_advance = style.text.em_advance(cx.font_cache);
1099        let overscroll = vec2f(em_width, 0.);
1100        let snapshot = self.update_view(cx.app, |view, cx| {
1101            let wrap_width = match view.soft_wrap_mode(cx) {
1102                SoftWrap::None => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
1103                SoftWrap::EditorWidth => {
1104                    Some(text_width - gutter_margin - overscroll.x() - em_width)
1105                }
1106                SoftWrap::Column(column) => Some(column as f32 * em_advance),
1107            };
1108
1109            if view.set_wrap_width(wrap_width, cx) {
1110                view.snapshot(cx)
1111            } else {
1112                snapshot
1113            }
1114        });
1115
1116        let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
1117        if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
1118            size.set_y(
1119                scroll_height
1120                    .min(constraint.max_along(Axis::Vertical))
1121                    .max(constraint.min_along(Axis::Vertical))
1122                    .min(line_height * max_lines as f32),
1123            )
1124        } else if let EditorMode::SingleLine = snapshot.mode {
1125            size.set_y(
1126                line_height
1127                    .min(constraint.max_along(Axis::Vertical))
1128                    .max(constraint.min_along(Axis::Vertical)),
1129            )
1130        } else if size.y().is_infinite() {
1131            size.set_y(scroll_height);
1132        }
1133        let gutter_size = vec2f(gutter_width, size.y());
1134        let text_size = vec2f(text_width, size.y());
1135
1136        let (autoscroll_horizontally, mut snapshot) = self.update_view(cx.app, |view, cx| {
1137            let autoscroll_horizontally = view.autoscroll_vertically(size.y(), line_height, cx);
1138            let snapshot = view.snapshot(cx);
1139            (autoscroll_horizontally, snapshot)
1140        });
1141
1142        let scroll_position = snapshot.scroll_position();
1143        let start_row = scroll_position.y() as u32;
1144        let scroll_top = scroll_position.y() * line_height;
1145
1146        // Add 1 to ensure selections bleed off screen
1147        let end_row = 1 + cmp::min(
1148            ((scroll_top + size.y()) / line_height).ceil() as u32,
1149            snapshot.max_point().row(),
1150        );
1151
1152        let start_anchor = if start_row == 0 {
1153            Anchor::min()
1154        } else {
1155            snapshot
1156                .buffer_snapshot
1157                .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
1158        };
1159        let end_anchor = if end_row > snapshot.max_point().row() {
1160            Anchor::max()
1161        } else {
1162            snapshot
1163                .buffer_snapshot
1164                .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
1165        };
1166
1167        let mut selections: Vec<(ReplicaId, Vec<SelectionLayout>)> = Vec::new();
1168        let mut active_rows = BTreeMap::new();
1169        let mut highlighted_rows = None;
1170        let mut highlighted_ranges = Vec::new();
1171        self.update_view(cx.app, |view, cx| {
1172            let display_map = view.display_map.update(cx, |map, cx| map.snapshot(cx));
1173
1174            highlighted_rows = view.highlighted_rows();
1175            let theme = cx.global::<Settings>().theme.as_ref();
1176            highlighted_ranges = view.background_highlights_in_range(
1177                start_anchor.clone()..end_anchor.clone(),
1178                &display_map,
1179                theme,
1180            );
1181
1182            let mut remote_selections = HashMap::default();
1183            for (replica_id, line_mode, selection) in display_map
1184                .buffer_snapshot
1185                .remote_selections_in_range(&(start_anchor.clone()..end_anchor.clone()))
1186            {
1187                // The local selections match the leader's selections.
1188                if Some(replica_id) == view.leader_replica_id {
1189                    continue;
1190                }
1191                remote_selections
1192                    .entry(replica_id)
1193                    .or_insert(Vec::new())
1194                    .push(SelectionLayout::new(selection, line_mode, &display_map));
1195            }
1196            selections.extend(remote_selections);
1197
1198            if view.show_local_selections {
1199                let mut local_selections = view
1200                    .selections
1201                    .disjoint_in_range(start_anchor..end_anchor, cx);
1202                local_selections.extend(view.selections.pending(cx));
1203                for selection in &local_selections {
1204                    let is_empty = selection.start == selection.end;
1205                    let selection_start = snapshot.prev_line_boundary(selection.start).1;
1206                    let selection_end = snapshot.next_line_boundary(selection.end).1;
1207                    for row in cmp::max(selection_start.row(), start_row)
1208                        ..=cmp::min(selection_end.row(), end_row)
1209                    {
1210                        let contains_non_empty_selection =
1211                            active_rows.entry(row).or_insert(!is_empty);
1212                        *contains_non_empty_selection |= !is_empty;
1213                    }
1214                }
1215
1216                // Render the local selections in the leader's color when following.
1217                let local_replica_id = view.leader_replica_id.unwrap_or(view.replica_id(cx));
1218
1219                selections.push((
1220                    local_replica_id,
1221                    local_selections
1222                        .into_iter()
1223                        .map(|selection| {
1224                            SelectionLayout::new(selection, view.selections.line_mode, &display_map)
1225                        })
1226                        .collect(),
1227                ));
1228            }
1229        });
1230
1231        let line_number_layouts =
1232            self.layout_line_numbers(start_row..end_row, &active_rows, &snapshot, cx);
1233
1234        let mut max_visible_line_width = 0.0;
1235        let line_layouts = self.layout_lines(start_row..end_row, &snapshot, cx);
1236        for line in &line_layouts {
1237            if line.width() > max_visible_line_width {
1238                max_visible_line_width = line.width();
1239            }
1240        }
1241
1242        let style = self.style.clone();
1243        let longest_line_width = layout_line(
1244            snapshot.longest_row(),
1245            &snapshot,
1246            &style,
1247            cx.text_layout_cache,
1248        )
1249        .width();
1250        let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
1251        let em_width = style.text.em_width(cx.font_cache);
1252        let (scroll_width, blocks) = self.layout_blocks(
1253            start_row..end_row,
1254            &snapshot,
1255            size.x(),
1256            scroll_width,
1257            gutter_padding,
1258            gutter_width,
1259            em_width,
1260            gutter_width + gutter_margin,
1261            line_height,
1262            &style,
1263            &line_layouts,
1264            cx,
1265        );
1266
1267        let max_row = snapshot.max_point().row();
1268        let scroll_max = vec2f(
1269            ((scroll_width - text_size.x()) / em_width).max(0.0),
1270            max_row.saturating_sub(1) as f32,
1271        );
1272
1273        self.update_view(cx.app, |view, cx| {
1274            let clamped = view.clamp_scroll_left(scroll_max.x());
1275            let autoscrolled;
1276            if autoscroll_horizontally {
1277                autoscrolled = view.autoscroll_horizontally(
1278                    start_row,
1279                    text_size.x(),
1280                    scroll_width,
1281                    em_width,
1282                    &line_layouts,
1283                    cx,
1284                );
1285            } else {
1286                autoscrolled = false;
1287            }
1288
1289            if clamped || autoscrolled {
1290                snapshot = view.snapshot(cx);
1291            }
1292        });
1293
1294        let mut context_menu = None;
1295        let mut code_actions_indicator = None;
1296        let mut hover = None;
1297        cx.render(&self.view.upgrade(cx).unwrap(), |view, cx| {
1298            let newest_selection_head = view
1299                .selections
1300                .newest::<usize>(cx)
1301                .head()
1302                .to_display_point(&snapshot);
1303
1304            let style = view.style(cx);
1305            if (start_row..end_row).contains(&newest_selection_head.row()) {
1306                if view.context_menu_visible() {
1307                    context_menu =
1308                        view.render_context_menu(newest_selection_head, style.clone(), cx);
1309                }
1310
1311                code_actions_indicator = view
1312                    .render_code_actions_indicator(&style, cx)
1313                    .map(|indicator| (newest_selection_head.row(), indicator));
1314            }
1315
1316            hover = view.hover_state.popover.clone().and_then(|hover| {
1317                let (point, rendered) = hover.render(&snapshot, style.clone(), cx);
1318                if point.row() >= snapshot.scroll_position().y() as u32 {
1319                    if line_layouts.len() > (point.row() - start_row) as usize {
1320                        return Some((point, rendered));
1321                    }
1322                }
1323
1324                None
1325            });
1326        });
1327
1328        if let Some((_, context_menu)) = context_menu.as_mut() {
1329            context_menu.layout(
1330                SizeConstraint {
1331                    min: Vector2F::zero(),
1332                    max: vec2f(
1333                        cx.window_size.x() * 0.7,
1334                        (12. * line_height).min((size.y() - line_height) / 2.),
1335                    ),
1336                },
1337                cx,
1338            );
1339        }
1340
1341        if let Some((_, indicator)) = code_actions_indicator.as_mut() {
1342            indicator.layout(
1343                SizeConstraint::strict_along(Axis::Vertical, line_height * 0.618),
1344                cx,
1345            );
1346        }
1347
1348        if let Some((_, hover)) = hover.as_mut() {
1349            hover.layout(
1350                SizeConstraint {
1351                    min: Vector2F::zero(),
1352                    max: vec2f(
1353                        (120. * em_width) // Default size
1354                            .min(size.x() / 2.) // Shrink to half of the editor width
1355                            .max(20. * em_width), // Apply minimum width of 20 characters
1356                        (16. * line_height) // Default size
1357                            .min(size.y() / 2.) // Shrink to half of the editor height
1358                            .max(4. * line_height), // Apply minimum height of 4 lines
1359                    ),
1360                },
1361                cx,
1362            );
1363        }
1364
1365        (
1366            size,
1367            LayoutState {
1368                size,
1369                scroll_max,
1370                gutter_size,
1371                gutter_padding,
1372                text_size,
1373                gutter_margin,
1374                snapshot,
1375                active_rows,
1376                highlighted_rows,
1377                highlighted_ranges,
1378                line_layouts,
1379                line_number_layouts,
1380                blocks,
1381                line_height,
1382                em_width,
1383                em_advance,
1384                selections,
1385                context_menu,
1386                code_actions_indicator,
1387                hover,
1388            },
1389        )
1390    }
1391
1392    fn paint(
1393        &mut self,
1394        bounds: RectF,
1395        visible_bounds: RectF,
1396        layout: &mut Self::LayoutState,
1397        cx: &mut PaintContext,
1398    ) -> Self::PaintState {
1399        cx.scene.push_layer(Some(bounds));
1400
1401        let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
1402        let text_bounds = RectF::new(
1403            bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
1404            layout.text_size,
1405        );
1406
1407        let mut paint_state = PaintState {
1408            bounds,
1409            gutter_bounds,
1410            text_bounds,
1411            context_menu_bounds: None,
1412            hover_bounds: None,
1413        };
1414
1415        self.paint_background(gutter_bounds, text_bounds, layout, cx);
1416        if layout.gutter_size.x() > 0. {
1417            self.paint_gutter(gutter_bounds, visible_bounds, layout, cx);
1418        }
1419        self.paint_text(text_bounds, visible_bounds, layout, &mut paint_state, cx);
1420
1421        if !layout.blocks.is_empty() {
1422            cx.scene.push_layer(Some(bounds));
1423            self.paint_blocks(bounds, visible_bounds, layout, cx);
1424            cx.scene.pop_layer();
1425        }
1426
1427        cx.scene.pop_layer();
1428
1429        paint_state
1430    }
1431
1432    fn dispatch_event(
1433        &mut self,
1434        event: &Event,
1435        _: RectF,
1436        _: RectF,
1437        layout: &mut LayoutState,
1438        paint: &mut PaintState,
1439        cx: &mut EventContext,
1440    ) -> bool {
1441        if let Some((_, context_menu)) = &mut layout.context_menu {
1442            if context_menu.dispatch_event(event, cx) {
1443                return true;
1444            }
1445        }
1446
1447        if let Some((_, indicator)) = &mut layout.code_actions_indicator {
1448            if indicator.dispatch_event(event, cx) {
1449                return true;
1450            }
1451        }
1452
1453        if let Some((_, hover)) = &mut layout.hover {
1454            if hover.dispatch_event(event, cx) {
1455                return true;
1456            }
1457        }
1458
1459        for block in &mut layout.blocks {
1460            if block.element.dispatch_event(event, cx) {
1461                return true;
1462            }
1463        }
1464
1465        match event {
1466            Event::LeftMouseDown {
1467                position,
1468                cmd,
1469                alt,
1470                shift,
1471                click_count,
1472                ..
1473            } => self.mouse_down(
1474                *position,
1475                *cmd,
1476                *alt,
1477                *shift,
1478                *click_count,
1479                layout,
1480                paint,
1481                cx,
1482            ),
1483            Event::LeftMouseUp { position, .. } => self.mouse_up(*position, cx),
1484            Event::LeftMouseDragged { position, .. } => {
1485                self.mouse_dragged(*position, layout, paint, cx)
1486            }
1487            Event::ScrollWheel {
1488                position,
1489                delta,
1490                precise,
1491            } => self.scroll(*position, *delta, *precise, layout, paint, cx),
1492            Event::KeyDown { input, .. } => self.key_down(input.as_deref(), cx),
1493            Event::ModifiersChanged { cmd, .. } => self.modifiers_changed(*cmd, cx),
1494            Event::MouseMoved { position, cmd, .. } => {
1495                self.mouse_moved(*position, *cmd, layout, paint, cx)
1496            }
1497
1498            _ => false,
1499        }
1500    }
1501
1502    fn debug(
1503        &self,
1504        bounds: RectF,
1505        _: &Self::LayoutState,
1506        _: &Self::PaintState,
1507        _: &gpui::DebugContext,
1508    ) -> json::Value {
1509        json!({
1510            "type": "BufferElement",
1511            "bounds": bounds.to_json()
1512        })
1513    }
1514}
1515
1516pub struct LayoutState {
1517    size: Vector2F,
1518    scroll_max: Vector2F,
1519    gutter_size: Vector2F,
1520    gutter_padding: f32,
1521    gutter_margin: f32,
1522    text_size: Vector2F,
1523    snapshot: EditorSnapshot,
1524    active_rows: BTreeMap<u32, bool>,
1525    highlighted_rows: Option<Range<u32>>,
1526    line_layouts: Vec<text_layout::Line>,
1527    line_number_layouts: Vec<Option<text_layout::Line>>,
1528    blocks: Vec<BlockLayout>,
1529    line_height: f32,
1530    em_width: f32,
1531    em_advance: f32,
1532    highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
1533    selections: Vec<(ReplicaId, Vec<SelectionLayout>)>,
1534    context_menu: Option<(DisplayPoint, ElementBox)>,
1535    code_actions_indicator: Option<(u32, ElementBox)>,
1536    hover: Option<(DisplayPoint, ElementBox)>,
1537}
1538
1539struct BlockLayout {
1540    row: u32,
1541    element: ElementBox,
1542    style: BlockStyle,
1543}
1544
1545fn layout_line(
1546    row: u32,
1547    snapshot: &EditorSnapshot,
1548    style: &EditorStyle,
1549    layout_cache: &TextLayoutCache,
1550) -> text_layout::Line {
1551    let mut line = snapshot.line(row);
1552
1553    if line.len() > MAX_LINE_LEN {
1554        let mut len = MAX_LINE_LEN;
1555        while !line.is_char_boundary(len) {
1556            len -= 1;
1557        }
1558
1559        line.truncate(len);
1560    }
1561
1562    layout_cache.layout_str(
1563        &line,
1564        style.text.font_size,
1565        &[(
1566            snapshot.line_len(row) as usize,
1567            RunStyle {
1568                font_id: style.text.font_id,
1569                color: Color::black(),
1570                underline: Default::default(),
1571            },
1572        )],
1573    )
1574}
1575
1576pub struct PaintState {
1577    bounds: RectF,
1578    gutter_bounds: RectF,
1579    text_bounds: RectF,
1580    context_menu_bounds: Option<RectF>,
1581    hover_bounds: Option<RectF>,
1582}
1583
1584impl PaintState {
1585    /// Returns two display points. The first is the nearest valid
1586    /// position in the current buffer and the second is the distance to the
1587    /// nearest valid position if there was overshoot.
1588    fn point_for_position(
1589        &self,
1590        snapshot: &EditorSnapshot,
1591        layout: &LayoutState,
1592        position: Vector2F,
1593    ) -> (DisplayPoint, DisplayPoint) {
1594        let scroll_position = snapshot.scroll_position();
1595        let position = position - self.text_bounds.origin();
1596        let y = position.y().max(0.0).min(layout.size.y());
1597        let row = ((y / layout.line_height) + scroll_position.y()) as u32;
1598        let row_overshoot = row.saturating_sub(snapshot.max_point().row());
1599        let row = cmp::min(row, snapshot.max_point().row());
1600        let line = &layout.line_layouts[(row - scroll_position.y() as u32) as usize];
1601        let x = position.x() + (scroll_position.x() * layout.em_width);
1602
1603        let column = if x >= 0.0 {
1604            line.index_for_x(x)
1605                .map(|ix| ix as u32)
1606                .unwrap_or_else(|| snapshot.line_len(row))
1607        } else {
1608            0
1609        };
1610        let column_overshoot = (0f32.max(x - line.width()) / layout.em_advance) as u32;
1611
1612        (
1613            DisplayPoint::new(row, column),
1614            DisplayPoint::new(row_overshoot, column_overshoot),
1615        )
1616    }
1617}
1618
1619#[derive(Copy, Clone, PartialEq, Eq)]
1620pub enum CursorShape {
1621    Bar,
1622    Block,
1623    Underscore,
1624}
1625
1626impl Default for CursorShape {
1627    fn default() -> Self {
1628        CursorShape::Bar
1629    }
1630}
1631
1632pub struct Cursor {
1633    origin: Vector2F,
1634    block_width: f32,
1635    line_height: f32,
1636    color: Color,
1637    shape: CursorShape,
1638    block_text: Option<Line>,
1639}
1640
1641impl Cursor {
1642    pub fn new(
1643        origin: Vector2F,
1644        block_width: f32,
1645        line_height: f32,
1646        color: Color,
1647        shape: CursorShape,
1648        block_text: Option<Line>,
1649    ) -> Cursor {
1650        Cursor {
1651            origin,
1652            block_width,
1653            line_height,
1654            color,
1655            shape,
1656            block_text,
1657        }
1658    }
1659
1660    pub fn paint(&self, origin: Vector2F, cx: &mut PaintContext) {
1661        let bounds = match self.shape {
1662            CursorShape::Bar => RectF::new(self.origin + origin, vec2f(2.0, self.line_height)),
1663            CursorShape::Block => RectF::new(
1664                self.origin + origin,
1665                vec2f(self.block_width, self.line_height),
1666            ),
1667            CursorShape::Underscore => RectF::new(
1668                self.origin + origin + Vector2F::new(0.0, self.line_height - 2.0),
1669                vec2f(self.block_width, 2.0),
1670            ),
1671        };
1672
1673        cx.scene.push_quad(Quad {
1674            bounds,
1675            background: Some(self.color),
1676            border: Border::new(0., Color::black()),
1677            corner_radius: 0.,
1678        });
1679
1680        if let Some(block_text) = &self.block_text {
1681            block_text.paint(self.origin + origin, bounds, self.line_height, cx);
1682        }
1683    }
1684}
1685
1686#[derive(Debug)]
1687struct HighlightedRange {
1688    start_y: f32,
1689    line_height: f32,
1690    lines: Vec<HighlightedRangeLine>,
1691    color: Color,
1692    corner_radius: f32,
1693}
1694
1695#[derive(Debug)]
1696struct HighlightedRangeLine {
1697    start_x: f32,
1698    end_x: f32,
1699}
1700
1701impl HighlightedRange {
1702    fn paint(&self, bounds: RectF, scene: &mut Scene) {
1703        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
1704            self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
1705            self.paint_lines(
1706                self.start_y + self.line_height,
1707                &self.lines[1..],
1708                bounds,
1709                scene,
1710            );
1711        } else {
1712            self.paint_lines(self.start_y, &self.lines, bounds, scene);
1713        }
1714    }
1715
1716    fn paint_lines(
1717        &self,
1718        start_y: f32,
1719        lines: &[HighlightedRangeLine],
1720        bounds: RectF,
1721        scene: &mut Scene,
1722    ) {
1723        if lines.is_empty() {
1724            return;
1725        }
1726
1727        let mut path = PathBuilder::new();
1728        let first_line = lines.first().unwrap();
1729        let last_line = lines.last().unwrap();
1730
1731        let first_top_left = vec2f(first_line.start_x, start_y);
1732        let first_top_right = vec2f(first_line.end_x, start_y);
1733
1734        let curve_height = vec2f(0., self.corner_radius);
1735        let curve_width = |start_x: f32, end_x: f32| {
1736            let max = (end_x - start_x) / 2.;
1737            let width = if max < self.corner_radius {
1738                max
1739            } else {
1740                self.corner_radius
1741            };
1742
1743            vec2f(width, 0.)
1744        };
1745
1746        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
1747        path.reset(first_top_right - top_curve_width);
1748        path.curve_to(first_top_right + curve_height, first_top_right);
1749
1750        let mut iter = lines.iter().enumerate().peekable();
1751        while let Some((ix, line)) = iter.next() {
1752            let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
1753
1754            if let Some((_, next_line)) = iter.peek() {
1755                let next_top_right = vec2f(next_line.end_x, bottom_right.y());
1756
1757                match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
1758                    Ordering::Equal => {
1759                        path.line_to(bottom_right);
1760                    }
1761                    Ordering::Less => {
1762                        let curve_width = curve_width(next_top_right.x(), bottom_right.x());
1763                        path.line_to(bottom_right - curve_height);
1764                        if self.corner_radius > 0. {
1765                            path.curve_to(bottom_right - curve_width, bottom_right);
1766                        }
1767                        path.line_to(next_top_right + curve_width);
1768                        if self.corner_radius > 0. {
1769                            path.curve_to(next_top_right + curve_height, next_top_right);
1770                        }
1771                    }
1772                    Ordering::Greater => {
1773                        let curve_width = curve_width(bottom_right.x(), next_top_right.x());
1774                        path.line_to(bottom_right - curve_height);
1775                        if self.corner_radius > 0. {
1776                            path.curve_to(bottom_right + curve_width, bottom_right);
1777                        }
1778                        path.line_to(next_top_right - curve_width);
1779                        if self.corner_radius > 0. {
1780                            path.curve_to(next_top_right + curve_height, next_top_right);
1781                        }
1782                    }
1783                }
1784            } else {
1785                let curve_width = curve_width(line.start_x, line.end_x);
1786                path.line_to(bottom_right - curve_height);
1787                if self.corner_radius > 0. {
1788                    path.curve_to(bottom_right - curve_width, bottom_right);
1789                }
1790
1791                let bottom_left = vec2f(line.start_x, bottom_right.y());
1792                path.line_to(bottom_left + curve_width);
1793                if self.corner_radius > 0. {
1794                    path.curve_to(bottom_left - curve_height, bottom_left);
1795                }
1796            }
1797        }
1798
1799        if first_line.start_x > last_line.start_x {
1800            let curve_width = curve_width(last_line.start_x, first_line.start_x);
1801            let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
1802            path.line_to(second_top_left + curve_height);
1803            if self.corner_radius > 0. {
1804                path.curve_to(second_top_left + curve_width, second_top_left);
1805            }
1806            let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
1807            path.line_to(first_bottom_left - curve_width);
1808            if self.corner_radius > 0. {
1809                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
1810            }
1811        }
1812
1813        path.line_to(first_top_left + curve_height);
1814        if self.corner_radius > 0. {
1815            path.curve_to(first_top_left + top_curve_width, first_top_left);
1816        }
1817        path.line_to(first_top_right - top_curve_width);
1818
1819        scene.push_path(path.build(self.color, Some(bounds)));
1820    }
1821}
1822
1823fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
1824    delta.powf(1.5) / 100.0
1825}
1826
1827fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
1828    delta.powf(1.2) / 300.0
1829}
1830
1831#[cfg(test)]
1832mod tests {
1833    use std::sync::Arc;
1834
1835    use super::*;
1836    use crate::{
1837        display_map::{BlockDisposition, BlockProperties},
1838        Editor, MultiBuffer,
1839    };
1840    use settings::Settings;
1841    use util::test::sample_text;
1842
1843    #[gpui::test]
1844    fn test_layout_line_numbers(cx: &mut gpui::MutableAppContext) {
1845        cx.set_global(Settings::test(cx));
1846        let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
1847        let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1848            Editor::new(EditorMode::Full, buffer, None, None, cx)
1849        });
1850        let element = EditorElement::new(
1851            editor.downgrade(),
1852            editor.read(cx).style(cx),
1853            CursorShape::Bar,
1854        );
1855
1856        let layouts = editor.update(cx, |editor, cx| {
1857            let snapshot = editor.snapshot(cx);
1858            let mut presenter = cx.build_presenter(window_id, 30.);
1859            let mut layout_cx = presenter.build_layout_context(Vector2F::zero(), false, cx);
1860            element.layout_line_numbers(0..6, &Default::default(), &snapshot, &mut layout_cx)
1861        });
1862        assert_eq!(layouts.len(), 6);
1863    }
1864
1865    #[gpui::test]
1866    fn test_layout_with_placeholder_text_and_blocks(cx: &mut gpui::MutableAppContext) {
1867        cx.set_global(Settings::test(cx));
1868        let buffer = MultiBuffer::build_simple("", cx);
1869        let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1870            Editor::new(EditorMode::Full, buffer, None, None, cx)
1871        });
1872
1873        editor.update(cx, |editor, cx| {
1874            editor.set_placeholder_text("hello", cx);
1875            editor.insert_blocks(
1876                [BlockProperties {
1877                    style: BlockStyle::Fixed,
1878                    disposition: BlockDisposition::Above,
1879                    height: 3,
1880                    position: Anchor::min(),
1881                    render: Arc::new(|_| Empty::new().boxed()),
1882                }],
1883                cx,
1884            );
1885
1886            // Blur the editor so that it displays placeholder text.
1887            cx.blur();
1888        });
1889
1890        let mut element = EditorElement::new(
1891            editor.downgrade(),
1892            editor.read(cx).style(cx),
1893            CursorShape::Bar,
1894        );
1895
1896        let mut scene = Scene::new(1.0);
1897        let mut presenter = cx.build_presenter(window_id, 30.);
1898        let mut layout_cx = presenter.build_layout_context(Vector2F::zero(), false, cx);
1899        let (size, mut state) = element.layout(
1900            SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
1901            &mut layout_cx,
1902        );
1903
1904        assert_eq!(state.line_layouts.len(), 4);
1905        assert_eq!(
1906            state
1907                .line_number_layouts
1908                .iter()
1909                .map(Option::is_some)
1910                .collect::<Vec<_>>(),
1911            &[false, false, false, true]
1912        );
1913
1914        // Don't panic.
1915        let bounds = RectF::new(Default::default(), size);
1916        let mut paint_cx = presenter.build_paint_context(&mut scene, bounds.size(), cx);
1917        element.paint(bounds, bounds, &mut state, &mut paint_cx);
1918    }
1919}