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