element.rs

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