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, MouseEvent, 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/jump.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(move |_, _, cx| cx.dispatch_action(jump_action.clone()))
 972                            .with_tooltip::<JumpIcon, _>(
 973                                *key,
 974                                "Jump to Buffer".to_string(),
 975                                Some(Box::new(crate::OpenExcerpts)),
 976                                tooltip_style.clone(),
 977                                cx,
 978                            )
 979                            .aligned()
 980                            .flex_float()
 981                            .boxed()
 982                        })
 983                    });
 984
 985                    if *starts_new_buffer {
 986                        let style = &self.style.diagnostic_path_header;
 987                        let font_size =
 988                            (style.text_scale_factor * self.style.text.font_size).round();
 989
 990                        let mut filename = None;
 991                        let mut parent_path = None;
 992                        if let Some(file) = buffer.file() {
 993                            let path = file.path();
 994                            filename = path.file_name().map(|f| f.to_string_lossy().to_string());
 995                            parent_path =
 996                                path.parent().map(|p| p.to_string_lossy().to_string() + "/");
 997                        }
 998
 999                        Flex::row()
1000                            .with_child(
1001                                Label::new(
1002                                    filename.unwrap_or_else(|| "untitled".to_string()),
1003                                    style.filename.text.clone().with_font_size(font_size),
1004                                )
1005                                .contained()
1006                                .with_style(style.filename.container)
1007                                .aligned()
1008                                .boxed(),
1009                            )
1010                            .with_children(parent_path.map(|path| {
1011                                Label::new(path, style.path.text.clone().with_font_size(font_size))
1012                                    .contained()
1013                                    .with_style(style.path.container)
1014                                    .aligned()
1015                                    .boxed()
1016                            }))
1017                            .with_children(jump_icon)
1018                            .contained()
1019                            .with_style(style.container)
1020                            .with_padding_left(gutter_padding)
1021                            .with_padding_right(gutter_padding)
1022                            .expanded()
1023                            .named("path header block")
1024                    } else {
1025                        let text_style = self.style.text.clone();
1026                        Flex::row()
1027                            .with_child(Label::new("".to_string(), text_style).boxed())
1028                            .with_children(jump_icon)
1029                            .contained()
1030                            .with_padding_left(gutter_padding)
1031                            .with_padding_right(gutter_padding)
1032                            .expanded()
1033                            .named("collapsed context")
1034                    }
1035                }
1036            };
1037
1038            element.layout(
1039                SizeConstraint {
1040                    min: Vector2F::zero(),
1041                    max: vec2f(width, block.height() as f32 * line_height),
1042                },
1043                cx,
1044            );
1045            element
1046        };
1047
1048        let mut fixed_block_max_width = 0f32;
1049        let mut blocks = Vec::new();
1050        for (row, block) in fixed_blocks {
1051            let element = render_block(block, f32::INFINITY);
1052            fixed_block_max_width = fixed_block_max_width.max(element.size().x() + em_width);
1053            blocks.push(BlockLayout {
1054                row,
1055                element,
1056                style: BlockStyle::Fixed,
1057            });
1058        }
1059        for (row, block) in non_fixed_blocks {
1060            let style = match block {
1061                TransformBlock::Custom(block) => block.style(),
1062                TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
1063            };
1064            let width = match style {
1065                BlockStyle::Sticky => editor_width,
1066                BlockStyle::Flex => editor_width
1067                    .max(fixed_block_max_width)
1068                    .max(gutter_width + scroll_width),
1069                BlockStyle::Fixed => unreachable!(),
1070            };
1071            let element = render_block(block, width);
1072            blocks.push(BlockLayout {
1073                row,
1074                element,
1075                style,
1076            });
1077        }
1078        (
1079            scroll_width.max(fixed_block_max_width - gutter_width),
1080            blocks,
1081        )
1082    }
1083}
1084
1085impl Element for EditorElement {
1086    type LayoutState = LayoutState;
1087    type PaintState = PaintState;
1088
1089    fn layout(
1090        &mut self,
1091        constraint: SizeConstraint,
1092        cx: &mut LayoutContext,
1093    ) -> (Vector2F, Self::LayoutState) {
1094        let mut size = constraint.max;
1095        if size.x().is_infinite() {
1096            unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
1097        }
1098
1099        let snapshot = self.snapshot(cx.app);
1100        let style = self.style.clone();
1101        let line_height = style.text.line_height(cx.font_cache);
1102
1103        let gutter_padding;
1104        let gutter_width;
1105        let gutter_margin;
1106        if snapshot.mode == EditorMode::Full {
1107            gutter_padding = style.text.em_width(cx.font_cache) * style.gutter_padding_factor;
1108            gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
1109            gutter_margin = -style.text.descent(cx.font_cache);
1110        } else {
1111            gutter_padding = 0.0;
1112            gutter_width = 0.0;
1113            gutter_margin = 0.0;
1114        };
1115
1116        let text_width = size.x() - gutter_width;
1117        let em_width = style.text.em_width(cx.font_cache);
1118        let em_advance = style.text.em_advance(cx.font_cache);
1119        let overscroll = vec2f(em_width, 0.);
1120        let snapshot = self.update_view(cx.app, |view, cx| {
1121            let wrap_width = match view.soft_wrap_mode(cx) {
1122                SoftWrap::None => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
1123                SoftWrap::EditorWidth => {
1124                    Some(text_width - gutter_margin - overscroll.x() - em_width)
1125                }
1126                SoftWrap::Column(column) => Some(column as f32 * em_advance),
1127            };
1128
1129            if view.set_wrap_width(wrap_width, cx) {
1130                view.snapshot(cx)
1131            } else {
1132                snapshot
1133            }
1134        });
1135
1136        let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
1137        if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
1138            size.set_y(
1139                scroll_height
1140                    .min(constraint.max_along(Axis::Vertical))
1141                    .max(constraint.min_along(Axis::Vertical))
1142                    .min(line_height * max_lines as f32),
1143            )
1144        } else if let EditorMode::SingleLine = snapshot.mode {
1145            size.set_y(
1146                line_height
1147                    .min(constraint.max_along(Axis::Vertical))
1148                    .max(constraint.min_along(Axis::Vertical)),
1149            )
1150        } else if size.y().is_infinite() {
1151            size.set_y(scroll_height);
1152        }
1153        let gutter_size = vec2f(gutter_width, size.y());
1154        let text_size = vec2f(text_width, size.y());
1155
1156        let (autoscroll_horizontally, mut snapshot) = self.update_view(cx.app, |view, cx| {
1157            let autoscroll_horizontally = view.autoscroll_vertically(size.y(), line_height, cx);
1158            let snapshot = view.snapshot(cx);
1159            (autoscroll_horizontally, snapshot)
1160        });
1161
1162        let scroll_position = snapshot.scroll_position();
1163        let start_row = scroll_position.y() as u32;
1164        let scroll_top = scroll_position.y() * line_height;
1165
1166        // Add 1 to ensure selections bleed off screen
1167        let end_row = 1 + cmp::min(
1168            ((scroll_top + size.y()) / line_height).ceil() as u32,
1169            snapshot.max_point().row(),
1170        );
1171
1172        let start_anchor = if start_row == 0 {
1173            Anchor::min()
1174        } else {
1175            snapshot
1176                .buffer_snapshot
1177                .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
1178        };
1179        let end_anchor = if end_row > snapshot.max_point().row() {
1180            Anchor::max()
1181        } else {
1182            snapshot
1183                .buffer_snapshot
1184                .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
1185        };
1186
1187        let mut selections: Vec<(ReplicaId, Vec<SelectionLayout>)> = Vec::new();
1188        let mut active_rows = BTreeMap::new();
1189        let mut highlighted_rows = None;
1190        let mut highlighted_ranges = Vec::new();
1191        self.update_view(cx.app, |view, cx| {
1192            let display_map = view.display_map.update(cx, |map, cx| map.snapshot(cx));
1193
1194            highlighted_rows = view.highlighted_rows();
1195            let theme = cx.global::<Settings>().theme.as_ref();
1196            highlighted_ranges = view.background_highlights_in_range(
1197                start_anchor.clone()..end_anchor.clone(),
1198                &display_map,
1199                theme,
1200            );
1201
1202            let mut remote_selections = HashMap::default();
1203            for (replica_id, line_mode, selection) in display_map
1204                .buffer_snapshot
1205                .remote_selections_in_range(&(start_anchor.clone()..end_anchor.clone()))
1206            {
1207                // The local selections match the leader's selections.
1208                if Some(replica_id) == view.leader_replica_id {
1209                    continue;
1210                }
1211                remote_selections
1212                    .entry(replica_id)
1213                    .or_insert(Vec::new())
1214                    .push(SelectionLayout::new(selection, line_mode, &display_map));
1215            }
1216            selections.extend(remote_selections);
1217
1218            if view.show_local_selections {
1219                let mut local_selections = view
1220                    .selections
1221                    .disjoint_in_range(start_anchor..end_anchor, cx);
1222                local_selections.extend(view.selections.pending(cx));
1223                for selection in &local_selections {
1224                    let is_empty = selection.start == selection.end;
1225                    let selection_start = snapshot.prev_line_boundary(selection.start).1;
1226                    let selection_end = snapshot.next_line_boundary(selection.end).1;
1227                    for row in cmp::max(selection_start.row(), start_row)
1228                        ..=cmp::min(selection_end.row(), end_row)
1229                    {
1230                        let contains_non_empty_selection =
1231                            active_rows.entry(row).or_insert(!is_empty);
1232                        *contains_non_empty_selection |= !is_empty;
1233                    }
1234                }
1235
1236                // Render the local selections in the leader's color when following.
1237                let local_replica_id = view.leader_replica_id.unwrap_or(view.replica_id(cx));
1238
1239                selections.push((
1240                    local_replica_id,
1241                    local_selections
1242                        .into_iter()
1243                        .map(|selection| {
1244                            SelectionLayout::new(selection, view.selections.line_mode, &display_map)
1245                        })
1246                        .collect(),
1247                ));
1248            }
1249        });
1250
1251        let line_number_layouts =
1252            self.layout_line_numbers(start_row..end_row, &active_rows, &snapshot, cx);
1253
1254        let mut max_visible_line_width = 0.0;
1255        let line_layouts = self.layout_lines(start_row..end_row, &snapshot, cx);
1256        for line in &line_layouts {
1257            if line.width() > max_visible_line_width {
1258                max_visible_line_width = line.width();
1259            }
1260        }
1261
1262        let style = self.style.clone();
1263        let longest_line_width = layout_line(
1264            snapshot.longest_row(),
1265            &snapshot,
1266            &style,
1267            cx.text_layout_cache,
1268        )
1269        .width();
1270        let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
1271        let em_width = style.text.em_width(cx.font_cache);
1272        let (scroll_width, blocks) = self.layout_blocks(
1273            start_row..end_row,
1274            &snapshot,
1275            size.x(),
1276            scroll_width,
1277            gutter_padding,
1278            gutter_width,
1279            em_width,
1280            gutter_width + gutter_margin,
1281            line_height,
1282            &style,
1283            &line_layouts,
1284            cx,
1285        );
1286
1287        let max_row = snapshot.max_point().row();
1288        let scroll_max = vec2f(
1289            ((scroll_width - text_size.x()) / em_width).max(0.0),
1290            max_row.saturating_sub(1) as f32,
1291        );
1292
1293        self.update_view(cx.app, |view, cx| {
1294            let clamped = view.clamp_scroll_left(scroll_max.x());
1295            let autoscrolled;
1296            if autoscroll_horizontally {
1297                autoscrolled = view.autoscroll_horizontally(
1298                    start_row,
1299                    text_size.x(),
1300                    scroll_width,
1301                    em_width,
1302                    &line_layouts,
1303                    cx,
1304                );
1305            } else {
1306                autoscrolled = false;
1307            }
1308
1309            if clamped || autoscrolled {
1310                snapshot = view.snapshot(cx);
1311            }
1312        });
1313
1314        let mut context_menu = None;
1315        let mut code_actions_indicator = None;
1316        let mut hover = None;
1317        cx.render(&self.view.upgrade(cx).unwrap(), |view, cx| {
1318            let newest_selection_head = view
1319                .selections
1320                .newest::<usize>(cx)
1321                .head()
1322                .to_display_point(&snapshot);
1323
1324            let style = view.style(cx);
1325            if (start_row..end_row).contains(&newest_selection_head.row()) {
1326                if view.context_menu_visible() {
1327                    context_menu =
1328                        view.render_context_menu(newest_selection_head, style.clone(), cx);
1329                }
1330
1331                code_actions_indicator = view
1332                    .render_code_actions_indicator(&style, cx)
1333                    .map(|indicator| (newest_selection_head.row(), indicator));
1334            }
1335
1336            hover = view.hover_state.popover.clone().and_then(|hover| {
1337                let (point, rendered) = hover.render(&snapshot, style.clone(), cx);
1338                if point.row() >= snapshot.scroll_position().y() as u32 {
1339                    if line_layouts.len() > (point.row() - start_row) as usize {
1340                        return Some((point, rendered));
1341                    }
1342                }
1343
1344                None
1345            });
1346        });
1347
1348        if let Some((_, context_menu)) = context_menu.as_mut() {
1349            context_menu.layout(
1350                SizeConstraint {
1351                    min: Vector2F::zero(),
1352                    max: vec2f(
1353                        cx.window_size.x() * 0.7,
1354                        (12. * line_height).min((size.y() - line_height) / 2.),
1355                    ),
1356                },
1357                cx,
1358            );
1359        }
1360
1361        if let Some((_, indicator)) = code_actions_indicator.as_mut() {
1362            indicator.layout(
1363                SizeConstraint::strict_along(Axis::Vertical, line_height * 0.618),
1364                cx,
1365            );
1366        }
1367
1368        if let Some((_, hover)) = hover.as_mut() {
1369            hover.layout(
1370                SizeConstraint {
1371                    min: Vector2F::zero(),
1372                    max: vec2f(
1373                        (120. * em_width) // Default size
1374                            .min(size.x() / 2.) // Shrink to half of the editor width
1375                            .max(20. * em_width), // Apply minimum width of 20 characters
1376                        (16. * line_height) // Default size
1377                            .min(size.y() / 2.) // Shrink to half of the editor height
1378                            .max(4. * line_height), // Apply minimum height of 4 lines
1379                    ),
1380                },
1381                cx,
1382            );
1383        }
1384
1385        (
1386            size,
1387            LayoutState {
1388                size,
1389                scroll_max,
1390                gutter_size,
1391                gutter_padding,
1392                text_size,
1393                gutter_margin,
1394                snapshot,
1395                active_rows,
1396                highlighted_rows,
1397                highlighted_ranges,
1398                line_layouts,
1399                line_number_layouts,
1400                blocks,
1401                line_height,
1402                em_width,
1403                em_advance,
1404                selections,
1405                context_menu,
1406                code_actions_indicator,
1407                hover,
1408            },
1409        )
1410    }
1411
1412    fn paint(
1413        &mut self,
1414        bounds: RectF,
1415        visible_bounds: RectF,
1416        layout: &mut Self::LayoutState,
1417        cx: &mut PaintContext,
1418    ) -> Self::PaintState {
1419        cx.scene.push_layer(Some(bounds));
1420
1421        let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
1422        let text_bounds = RectF::new(
1423            bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
1424            layout.text_size,
1425        );
1426
1427        let mut paint_state = PaintState {
1428            bounds,
1429            gutter_bounds,
1430            text_bounds,
1431            context_menu_bounds: None,
1432            hover_bounds: None,
1433        };
1434
1435        self.paint_background(gutter_bounds, text_bounds, layout, cx);
1436        if layout.gutter_size.x() > 0. {
1437            self.paint_gutter(gutter_bounds, visible_bounds, layout, cx);
1438        }
1439        self.paint_text(text_bounds, visible_bounds, layout, &mut paint_state, cx);
1440
1441        if !layout.blocks.is_empty() {
1442            cx.scene.push_layer(Some(bounds));
1443            self.paint_blocks(bounds, visible_bounds, layout, cx);
1444            cx.scene.pop_layer();
1445        }
1446
1447        cx.scene.pop_layer();
1448
1449        paint_state
1450    }
1451
1452    fn dispatch_event(
1453        &mut self,
1454        event: &Event,
1455        _: RectF,
1456        _: RectF,
1457        layout: &mut LayoutState,
1458        paint: &mut PaintState,
1459        cx: &mut EventContext,
1460    ) -> bool {
1461        if let Some((_, context_menu)) = &mut layout.context_menu {
1462            if context_menu.dispatch_event(event, cx) {
1463                return true;
1464            }
1465        }
1466
1467        if let Some((_, indicator)) = &mut layout.code_actions_indicator {
1468            if indicator.dispatch_event(event, cx) {
1469                return true;
1470            }
1471        }
1472
1473        if let Some((_, hover)) = &mut layout.hover {
1474            if hover.dispatch_event(event, cx) {
1475                return true;
1476            }
1477        }
1478
1479        for block in &mut layout.blocks {
1480            if block.element.dispatch_event(event, cx) {
1481                return true;
1482            }
1483        }
1484
1485        match event {
1486            Event::MouseDown(MouseEvent {
1487                button: MouseButton::Left,
1488                position,
1489                cmd,
1490                alt,
1491                shift,
1492                click_count,
1493                ..
1494            }) => self.mouse_down(
1495                *position,
1496                *cmd,
1497                *alt,
1498                *shift,
1499                *click_count,
1500                layout,
1501                paint,
1502                cx,
1503            ),
1504            Event::MouseDown(MouseEvent {
1505                button: MouseButton::Right,
1506                position,
1507                ..
1508            }) => self.mouse_right_down(*position, layout, paint, cx),
1509            Event::MouseUp(MouseEvent {
1510                button: MouseButton::Left,
1511                position,
1512                ..
1513            }) => self.mouse_up(*position, cx),
1514            Event::MouseMoved(MouseMovedEvent {
1515                pressed_button: Some(MouseButton::Left),
1516                position,
1517                ..
1518            }) => self.mouse_dragged(*position, layout, paint, cx),
1519            Event::ScrollWheel(ScrollWheelEvent {
1520                position,
1521                delta,
1522                precise,
1523            }) => self.scroll(*position, *delta, *precise, layout, paint, cx),
1524            Event::ModifiersChanged(ModifiersChangedEvent { cmd, .. }) => {
1525                self.modifiers_changed(*cmd, cx)
1526            }
1527            Event::MouseMoved(MouseMovedEvent { position, cmd, .. }) => {
1528                self.mouse_moved(*position, *cmd, layout, paint, cx)
1529            }
1530
1531            _ => false,
1532        }
1533    }
1534
1535    fn debug(
1536        &self,
1537        bounds: RectF,
1538        _: &Self::LayoutState,
1539        _: &Self::PaintState,
1540        _: &gpui::DebugContext,
1541    ) -> json::Value {
1542        json!({
1543            "type": "BufferElement",
1544            "bounds": bounds.to_json()
1545        })
1546    }
1547}
1548
1549pub struct LayoutState {
1550    size: Vector2F,
1551    scroll_max: Vector2F,
1552    gutter_size: Vector2F,
1553    gutter_padding: f32,
1554    gutter_margin: f32,
1555    text_size: Vector2F,
1556    snapshot: EditorSnapshot,
1557    active_rows: BTreeMap<u32, bool>,
1558    highlighted_rows: Option<Range<u32>>,
1559    line_layouts: Vec<text_layout::Line>,
1560    line_number_layouts: Vec<Option<text_layout::Line>>,
1561    blocks: Vec<BlockLayout>,
1562    line_height: f32,
1563    em_width: f32,
1564    em_advance: f32,
1565    highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
1566    selections: Vec<(ReplicaId, Vec<SelectionLayout>)>,
1567    context_menu: Option<(DisplayPoint, ElementBox)>,
1568    code_actions_indicator: Option<(u32, ElementBox)>,
1569    hover: Option<(DisplayPoint, ElementBox)>,
1570}
1571
1572struct BlockLayout {
1573    row: u32,
1574    element: ElementBox,
1575    style: BlockStyle,
1576}
1577
1578fn layout_line(
1579    row: u32,
1580    snapshot: &EditorSnapshot,
1581    style: &EditorStyle,
1582    layout_cache: &TextLayoutCache,
1583) -> text_layout::Line {
1584    let mut line = snapshot.line(row);
1585
1586    if line.len() > MAX_LINE_LEN {
1587        let mut len = MAX_LINE_LEN;
1588        while !line.is_char_boundary(len) {
1589            len -= 1;
1590        }
1591
1592        line.truncate(len);
1593    }
1594
1595    layout_cache.layout_str(
1596        &line,
1597        style.text.font_size,
1598        &[(
1599            snapshot.line_len(row) as usize,
1600            RunStyle {
1601                font_id: style.text.font_id,
1602                color: Color::black(),
1603                underline: Default::default(),
1604            },
1605        )],
1606    )
1607}
1608
1609pub struct PaintState {
1610    bounds: RectF,
1611    gutter_bounds: RectF,
1612    text_bounds: RectF,
1613    context_menu_bounds: Option<RectF>,
1614    hover_bounds: Option<RectF>,
1615}
1616
1617impl PaintState {
1618    /// Returns two display points. The first is the nearest valid
1619    /// position in the current buffer and the second is the distance to the
1620    /// nearest valid position if there was overshoot.
1621    fn point_for_position(
1622        &self,
1623        snapshot: &EditorSnapshot,
1624        layout: &LayoutState,
1625        position: Vector2F,
1626    ) -> (DisplayPoint, DisplayPoint) {
1627        let scroll_position = snapshot.scroll_position();
1628        let position = position - self.text_bounds.origin();
1629        let y = position.y().max(0.0).min(layout.size.y());
1630        let row = ((y / layout.line_height) + scroll_position.y()) as u32;
1631        let row_overshoot = row.saturating_sub(snapshot.max_point().row());
1632        let row = cmp::min(row, snapshot.max_point().row());
1633        let line = &layout.line_layouts[(row - scroll_position.y() as u32) as usize];
1634        let x = position.x() + (scroll_position.x() * layout.em_width);
1635
1636        let column = if x >= 0.0 {
1637            line.index_for_x(x)
1638                .map(|ix| ix as u32)
1639                .unwrap_or_else(|| snapshot.line_len(row))
1640        } else {
1641            0
1642        };
1643        let column_overshoot = (0f32.max(x - line.width()) / layout.em_advance) as u32;
1644
1645        (
1646            DisplayPoint::new(row, column),
1647            DisplayPoint::new(row_overshoot, column_overshoot),
1648        )
1649    }
1650}
1651
1652#[derive(Copy, Clone, PartialEq, Eq, Debug)]
1653pub enum CursorShape {
1654    Bar,
1655    Block,
1656    Underscore,
1657}
1658
1659impl Default for CursorShape {
1660    fn default() -> Self {
1661        CursorShape::Bar
1662    }
1663}
1664
1665#[derive(Debug)]
1666pub struct Cursor {
1667    origin: Vector2F,
1668    block_width: f32,
1669    line_height: f32,
1670    color: Color,
1671    shape: CursorShape,
1672    block_text: Option<Line>,
1673}
1674
1675impl Cursor {
1676    pub fn new(
1677        origin: Vector2F,
1678        block_width: f32,
1679        line_height: f32,
1680        color: Color,
1681        shape: CursorShape,
1682        block_text: Option<Line>,
1683    ) -> Cursor {
1684        Cursor {
1685            origin,
1686            block_width,
1687            line_height,
1688            color,
1689            shape,
1690            block_text,
1691        }
1692    }
1693
1694    pub fn paint(&self, origin: Vector2F, cx: &mut PaintContext) {
1695        let bounds = match self.shape {
1696            CursorShape::Bar => RectF::new(self.origin + origin, vec2f(2.0, self.line_height)),
1697            CursorShape::Block => RectF::new(
1698                self.origin + origin,
1699                vec2f(self.block_width, self.line_height),
1700            ),
1701            CursorShape::Underscore => RectF::new(
1702                self.origin + origin + Vector2F::new(0.0, self.line_height - 2.0),
1703                vec2f(self.block_width, 2.0),
1704            ),
1705        };
1706
1707        cx.scene.push_quad(Quad {
1708            bounds,
1709            background: Some(self.color),
1710            border: Border::new(0., Color::black()),
1711            corner_radius: 0.,
1712        });
1713
1714        if let Some(block_text) = &self.block_text {
1715            block_text.paint(self.origin + origin, bounds, self.line_height, cx);
1716        }
1717    }
1718}
1719
1720#[derive(Debug)]
1721pub struct HighlightedRange {
1722    pub start_y: f32,
1723    pub line_height: f32,
1724    pub lines: Vec<HighlightedRangeLine>,
1725    pub color: Color,
1726    pub corner_radius: f32,
1727}
1728
1729#[derive(Debug)]
1730pub struct HighlightedRangeLine {
1731    pub start_x: f32,
1732    pub end_x: f32,
1733}
1734
1735impl HighlightedRange {
1736    pub fn paint(&self, bounds: RectF, scene: &mut Scene) {
1737        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
1738            self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
1739            self.paint_lines(
1740                self.start_y + self.line_height,
1741                &self.lines[1..],
1742                bounds,
1743                scene,
1744            );
1745        } else {
1746            self.paint_lines(self.start_y, &self.lines, bounds, scene);
1747        }
1748    }
1749
1750    fn paint_lines(
1751        &self,
1752        start_y: f32,
1753        lines: &[HighlightedRangeLine],
1754        bounds: RectF,
1755        scene: &mut Scene,
1756    ) {
1757        if lines.is_empty() {
1758            return;
1759        }
1760
1761        let mut path = PathBuilder::new();
1762        let first_line = lines.first().unwrap();
1763        let last_line = lines.last().unwrap();
1764
1765        let first_top_left = vec2f(first_line.start_x, start_y);
1766        let first_top_right = vec2f(first_line.end_x, start_y);
1767
1768        let curve_height = vec2f(0., self.corner_radius);
1769        let curve_width = |start_x: f32, end_x: f32| {
1770            let max = (end_x - start_x) / 2.;
1771            let width = if max < self.corner_radius {
1772                max
1773            } else {
1774                self.corner_radius
1775            };
1776
1777            vec2f(width, 0.)
1778        };
1779
1780        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
1781        path.reset(first_top_right - top_curve_width);
1782        path.curve_to(first_top_right + curve_height, first_top_right);
1783
1784        let mut iter = lines.iter().enumerate().peekable();
1785        while let Some((ix, line)) = iter.next() {
1786            let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
1787
1788            if let Some((_, next_line)) = iter.peek() {
1789                let next_top_right = vec2f(next_line.end_x, bottom_right.y());
1790
1791                match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
1792                    Ordering::Equal => {
1793                        path.line_to(bottom_right);
1794                    }
1795                    Ordering::Less => {
1796                        let curve_width = curve_width(next_top_right.x(), bottom_right.x());
1797                        path.line_to(bottom_right - curve_height);
1798                        if self.corner_radius > 0. {
1799                            path.curve_to(bottom_right - curve_width, bottom_right);
1800                        }
1801                        path.line_to(next_top_right + curve_width);
1802                        if self.corner_radius > 0. {
1803                            path.curve_to(next_top_right + curve_height, next_top_right);
1804                        }
1805                    }
1806                    Ordering::Greater => {
1807                        let curve_width = curve_width(bottom_right.x(), next_top_right.x());
1808                        path.line_to(bottom_right - curve_height);
1809                        if self.corner_radius > 0. {
1810                            path.curve_to(bottom_right + curve_width, bottom_right);
1811                        }
1812                        path.line_to(next_top_right - curve_width);
1813                        if self.corner_radius > 0. {
1814                            path.curve_to(next_top_right + curve_height, next_top_right);
1815                        }
1816                    }
1817                }
1818            } else {
1819                let curve_width = curve_width(line.start_x, line.end_x);
1820                path.line_to(bottom_right - curve_height);
1821                if self.corner_radius > 0. {
1822                    path.curve_to(bottom_right - curve_width, bottom_right);
1823                }
1824
1825                let bottom_left = vec2f(line.start_x, bottom_right.y());
1826                path.line_to(bottom_left + curve_width);
1827                if self.corner_radius > 0. {
1828                    path.curve_to(bottom_left - curve_height, bottom_left);
1829                }
1830            }
1831        }
1832
1833        if first_line.start_x > last_line.start_x {
1834            let curve_width = curve_width(last_line.start_x, first_line.start_x);
1835            let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
1836            path.line_to(second_top_left + curve_height);
1837            if self.corner_radius > 0. {
1838                path.curve_to(second_top_left + curve_width, second_top_left);
1839            }
1840            let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
1841            path.line_to(first_bottom_left - curve_width);
1842            if self.corner_radius > 0. {
1843                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
1844            }
1845        }
1846
1847        path.line_to(first_top_left + curve_height);
1848        if self.corner_radius > 0. {
1849            path.curve_to(first_top_left + top_curve_width, first_top_left);
1850        }
1851        path.line_to(first_top_right - top_curve_width);
1852
1853        scene.push_path(path.build(self.color, Some(bounds)));
1854    }
1855}
1856
1857fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
1858    delta.powf(1.5) / 100.0
1859}
1860
1861fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
1862    delta.powf(1.2) / 300.0
1863}
1864
1865#[cfg(test)]
1866mod tests {
1867    use std::sync::Arc;
1868
1869    use super::*;
1870    use crate::{
1871        display_map::{BlockDisposition, BlockProperties},
1872        Editor, MultiBuffer,
1873    };
1874    use settings::Settings;
1875    use util::test::sample_text;
1876
1877    #[gpui::test]
1878    fn test_layout_line_numbers(cx: &mut gpui::MutableAppContext) {
1879        cx.set_global(Settings::test(cx));
1880        let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
1881        let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1882            Editor::new(EditorMode::Full, buffer, None, None, cx)
1883        });
1884        let element = EditorElement::new(
1885            editor.downgrade(),
1886            editor.read(cx).style(cx),
1887            CursorShape::Bar,
1888        );
1889
1890        let layouts = editor.update(cx, |editor, cx| {
1891            let snapshot = editor.snapshot(cx);
1892            let mut presenter = cx.build_presenter(window_id, 30.);
1893            let mut layout_cx = presenter.build_layout_context(Vector2F::zero(), false, cx);
1894            element.layout_line_numbers(0..6, &Default::default(), &snapshot, &mut layout_cx)
1895        });
1896        assert_eq!(layouts.len(), 6);
1897    }
1898
1899    #[gpui::test]
1900    fn test_layout_with_placeholder_text_and_blocks(cx: &mut gpui::MutableAppContext) {
1901        cx.set_global(Settings::test(cx));
1902        let buffer = MultiBuffer::build_simple("", cx);
1903        let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1904            Editor::new(EditorMode::Full, buffer, None, None, cx)
1905        });
1906
1907        editor.update(cx, |editor, cx| {
1908            editor.set_placeholder_text("hello", cx);
1909            editor.insert_blocks(
1910                [BlockProperties {
1911                    style: BlockStyle::Fixed,
1912                    disposition: BlockDisposition::Above,
1913                    height: 3,
1914                    position: Anchor::min(),
1915                    render: Arc::new(|_| Empty::new().boxed()),
1916                }],
1917                cx,
1918            );
1919
1920            // Blur the editor so that it displays placeholder text.
1921            cx.blur();
1922        });
1923
1924        let mut element = EditorElement::new(
1925            editor.downgrade(),
1926            editor.read(cx).style(cx),
1927            CursorShape::Bar,
1928        );
1929
1930        let mut scene = Scene::new(1.0);
1931        let mut presenter = cx.build_presenter(window_id, 30.);
1932        let mut layout_cx = presenter.build_layout_context(Vector2F::zero(), false, cx);
1933        let (size, mut state) = element.layout(
1934            SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
1935            &mut layout_cx,
1936        );
1937
1938        assert_eq!(state.line_layouts.len(), 4);
1939        assert_eq!(
1940            state
1941                .line_number_layouts
1942                .iter()
1943                .map(Option::is_some)
1944                .collect::<Vec<_>>(),
1945            &[false, false, false, true]
1946        );
1947
1948        // Don't panic.
1949        let bounds = RectF::new(Default::default(), size);
1950        let mut paint_cx = presenter.build_paint_context(&mut scene, bounds.size(), cx);
1951        element.paint(bounds, bounds, &mut state, &mut paint_cx);
1952    }
1953}