element.rs

   1use super::{
   2    display_map::{BlockContext, ToDisplayPoint},
   3    Anchor, DisplayPoint, Editor, EditorMode, EditorSnapshot, Select, SelectPhase, SoftWrap,
   4    ToPoint, MAX_LINE_LEN,
   5};
   6use crate::{
   7    display_map::{BlockStyle, DisplayRow, DisplaySnapshot, FoldStatus, TransformBlock},
   8    git::{diff_hunk_to_display, DisplayDiffHunk},
   9    hover_popover::{
  10        HideHover, HoverAt, HOVER_POPOVER_GAP, MIN_POPOVER_CHARACTER_WIDTH, MIN_POPOVER_LINE_HEIGHT,
  11    },
  12    link_go_to_definition::{
  13        GoToFetchedDefinition, GoToFetchedTypeDefinition, UpdateGoToDefinitionLink,
  14    },
  15    mouse_context_menu::DeployMouseContextMenu,
  16    scroll::actions::Scroll,
  17    EditorStyle, GutterHover, TextClickedCallback, UnfoldAt,
  18};
  19use clock::ReplicaId;
  20use collections::{BTreeMap, HashMap};
  21use git::diff::DiffHunkStatus;
  22use gpui::{
  23    color::Color,
  24    elements::*,
  25    fonts::{HighlightStyle, Underline},
  26    geometry::{
  27        rect::RectF,
  28        vector::{vec2f, Vector2F},
  29        PathBuilder,
  30    },
  31    json::{self, ToJson},
  32    platform::CursorStyle,
  33    scene::MouseClick,
  34    text_layout::{self, Line, RunStyle, TextLayoutCache},
  35    AppContext, Axis, Border, CursorRegion, Element, ElementBox, EventContext, LayoutContext,
  36    Modifiers, MouseButton, MouseButtonEvent, MouseMovedEvent, MouseRegion, MutableAppContext,
  37    PaintContext, Quad, SceneBuilder, SizeConstraint, ViewContext, WeakViewHandle,
  38};
  39use itertools::Itertools;
  40use json::json;
  41use language::{Bias, CursorShape, DiagnosticSeverity, OffsetUtf16, Selection};
  42use project::ProjectPath;
  43use settings::{GitGutter, Settings};
  44use smallvec::SmallVec;
  45use std::{
  46    cmp::{self, Ordering},
  47    fmt::Write,
  48    iter,
  49    ops::{DerefMut, Range},
  50    sync::Arc,
  51};
  52use workspace::item::Item;
  53
  54struct SelectionLayout {
  55    head: DisplayPoint,
  56    cursor_shape: CursorShape,
  57    range: Range<DisplayPoint>,
  58}
  59
  60impl SelectionLayout {
  61    fn new<T: ToPoint + ToDisplayPoint + Clone>(
  62        selection: Selection<T>,
  63        line_mode: bool,
  64        cursor_shape: CursorShape,
  65        map: &DisplaySnapshot,
  66    ) -> Self {
  67        if line_mode {
  68            let selection = selection.map(|p| p.to_point(&map.buffer_snapshot));
  69            let point_range = map.expand_to_line(selection.range());
  70            Self {
  71                head: selection.head().to_display_point(map),
  72                cursor_shape,
  73                range: point_range.start.to_display_point(map)
  74                    ..point_range.end.to_display_point(map),
  75            }
  76        } else {
  77            let selection = selection.map(|p| p.to_display_point(map));
  78            Self {
  79                head: selection.head(),
  80                cursor_shape,
  81                range: selection.range(),
  82            }
  83        }
  84    }
  85}
  86
  87#[derive(Clone)]
  88pub struct EditorElement {
  89    view: WeakViewHandle<Editor>,
  90    style: Arc<EditorStyle>,
  91}
  92
  93impl EditorElement {
  94    pub fn new(view: WeakViewHandle<Editor>, style: EditorStyle) -> Self {
  95        Self {
  96            view,
  97            style: Arc::new(style),
  98        }
  99    }
 100
 101    fn view<'a>(&self, cx: &'a AppContext) -> &'a Editor {
 102        self.view.upgrade(cx).unwrap().read(cx)
 103    }
 104
 105    fn update_view<F, T>(&self, cx: &mut MutableAppContext, f: F) -> T
 106    where
 107        F: FnOnce(&mut Editor, &mut ViewContext<Editor>) -> T,
 108    {
 109        self.view.upgrade(cx).unwrap().update(cx, f)
 110    }
 111
 112    fn snapshot(&self, cx: &mut MutableAppContext) -> EditorSnapshot {
 113        self.update_view(cx, |view, cx| view.snapshot(cx))
 114    }
 115
 116    fn attach_mouse_handlers(
 117        view: &WeakViewHandle<Editor>,
 118        position_map: &Arc<PositionMap>,
 119        click_ranges: Arc<Vec<(Range<DisplayPoint>, TextClickedCallback)>>,
 120        has_popovers: bool,
 121        visible_bounds: RectF,
 122        text_bounds: RectF,
 123        gutter_bounds: RectF,
 124        bounds: RectF,
 125        cx: &mut PaintContext,
 126    ) {
 127        enum EditorElementMouseHandlers {}
 128        cx.scene.push_mouse_region(
 129            MouseRegion::new::<EditorElementMouseHandlers>(view.id(), view.id(), visible_bounds)
 130                .on_down(MouseButton::Left, {
 131                    let position_map = position_map.clone();
 132                    move |e, cx| {
 133                        if !Self::mouse_down(
 134                            e.platform_event,
 135                            position_map.as_ref(),
 136                            text_bounds,
 137                            gutter_bounds,
 138                            cx,
 139                        ) {
 140                            cx.propagate_event();
 141                        }
 142                    }
 143                })
 144                .on_down(MouseButton::Right, {
 145                    let position_map = position_map.clone();
 146                    move |e, cx| {
 147                        if !Self::mouse_right_down(
 148                            e.position,
 149                            position_map.as_ref(),
 150                            text_bounds,
 151                            cx,
 152                        ) {
 153                            cx.propagate_event();
 154                        }
 155                    }
 156                })
 157                .on_up(MouseButton::Left, {
 158                    let view = view.clone();
 159                    let position_map = position_map.clone();
 160                    move |e, cx| {
 161                        if !Self::mouse_up(
 162                            view.clone(),
 163                            e.position,
 164                            e.cmd,
 165                            e.shift,
 166                            position_map.as_ref(),
 167                            text_bounds,
 168                            cx,
 169                        ) {
 170                            cx.propagate_event()
 171                        }
 172                    }
 173                })
 174                .on_drag(MouseButton::Left, {
 175                    let view = view.clone();
 176                    let position_map = position_map.clone();
 177                    move |e, cx| {
 178                        if !Self::mouse_dragged(
 179                            view.clone(),
 180                            e.platform_event,
 181                            position_map.as_ref(),
 182                            text_bounds,
 183                            cx,
 184                        ) {
 185                            cx.propagate_event()
 186                        }
 187                    }
 188                })
 189                .on_move({
 190                    let position_map = position_map.clone();
 191                    move |e, cx| {
 192                        if !Self::mouse_moved(e.platform_event, &position_map, text_bounds, cx) {
 193                            cx.propagate_event()
 194                        }
 195                    }
 196                })
 197                .on_move_out(move |_, cx| {
 198                    if has_popovers {
 199                        cx.dispatch_action(HideHover);
 200                    }
 201                })
 202                .on_scroll({
 203                    let position_map = position_map.clone();
 204                    move |e, cx| {
 205                        if !Self::scroll(
 206                            e.position,
 207                            *e.delta.raw(),
 208                            e.delta.precise(),
 209                            &position_map,
 210                            bounds,
 211                            cx,
 212                        ) {
 213                            cx.propagate_event()
 214                        }
 215                    }
 216                })
 217                .on_click(MouseButton::Left, {
 218                    let position_map = position_map.clone();
 219                    move |e, cx| {
 220                        let point =
 221                            position_to_display_point(e.position, text_bounds, &position_map);
 222                        if let Some(point) = point {
 223                            for (range, callback) in click_ranges.iter() {
 224                                if range.contains(&point) {
 225                                    callback(&e, range, &position_map.snapshot, cx)
 226                                }
 227                            }
 228                        }
 229                    }
 230                }),
 231        );
 232
 233        enum GutterHandlers {}
 234        cx.scene.push_mouse_region(
 235            MouseRegion::new::<GutterHandlers>(view.id(), view.id() + 1, gutter_bounds).on_hover(
 236                |hover, cx| {
 237                    cx.dispatch_action(GutterHover {
 238                        hovered: hover.started,
 239                    })
 240                },
 241            ),
 242        )
 243    }
 244
 245    fn mouse_down(
 246        MouseButtonEvent {
 247            position,
 248            modifiers:
 249                Modifiers {
 250                    shift,
 251                    ctrl,
 252                    alt,
 253                    cmd,
 254                    ..
 255                },
 256            mut click_count,
 257            ..
 258        }: MouseButtonEvent,
 259        position_map: &PositionMap,
 260        text_bounds: RectF,
 261        gutter_bounds: RectF,
 262        cx: &mut EventContext,
 263    ) -> bool {
 264        if gutter_bounds.contains_point(position) {
 265            click_count = 3; // Simulate triple-click when clicking the gutter to select lines
 266        } else if !text_bounds.contains_point(position) {
 267            return false;
 268        }
 269
 270        let (position, target_position) = position_map.point_for_position(text_bounds, position);
 271
 272        if shift && alt {
 273            cx.dispatch_action(Select(SelectPhase::BeginColumnar {
 274                position,
 275                goal_column: target_position.column(),
 276            }));
 277        } else if shift && !ctrl && !alt && !cmd {
 278            cx.dispatch_action(Select(SelectPhase::Extend {
 279                position,
 280                click_count,
 281            }));
 282        } else {
 283            cx.dispatch_action(Select(SelectPhase::Begin {
 284                position,
 285                add: alt,
 286                click_count,
 287            }));
 288        }
 289
 290        true
 291    }
 292
 293    fn mouse_right_down(
 294        position: Vector2F,
 295        position_map: &PositionMap,
 296        text_bounds: RectF,
 297        cx: &mut EventContext,
 298    ) -> bool {
 299        if !text_bounds.contains_point(position) {
 300            return false;
 301        }
 302
 303        let (point, _) = position_map.point_for_position(text_bounds, position);
 304
 305        cx.dispatch_action(DeployMouseContextMenu { position, point });
 306        true
 307    }
 308
 309    fn mouse_up(
 310        view: WeakViewHandle<Editor>,
 311        position: Vector2F,
 312        cmd: bool,
 313        shift: bool,
 314        position_map: &PositionMap,
 315        text_bounds: RectF,
 316        cx: &mut EventContext,
 317    ) -> bool {
 318        let view = view.upgrade(cx.app).unwrap().read(cx.app);
 319        let end_selection = view.has_pending_selection();
 320        let pending_nonempty_selections = view.has_pending_nonempty_selection();
 321
 322        if end_selection {
 323            cx.dispatch_action(Select(SelectPhase::End));
 324        }
 325
 326        if !pending_nonempty_selections && cmd && text_bounds.contains_point(position) {
 327            let (point, target_point) = position_map.point_for_position(text_bounds, position);
 328
 329            if point == target_point {
 330                if shift {
 331                    cx.dispatch_action(GoToFetchedTypeDefinition { point });
 332                } else {
 333                    cx.dispatch_action(GoToFetchedDefinition { point });
 334                }
 335
 336                return true;
 337            }
 338        }
 339
 340        end_selection
 341    }
 342
 343    fn mouse_dragged(
 344        view: WeakViewHandle<Editor>,
 345        MouseMovedEvent {
 346            modifiers: Modifiers { cmd, shift, .. },
 347            position,
 348            ..
 349        }: MouseMovedEvent,
 350        position_map: &PositionMap,
 351        text_bounds: RectF,
 352        cx: &mut EventContext,
 353    ) -> bool {
 354        // This will be handled more correctly once https://github.com/zed-industries/zed/issues/1218 is completed
 355        // Don't trigger hover popover if mouse is hovering over context menu
 356        let point = if text_bounds.contains_point(position) {
 357            let (point, target_point) = position_map.point_for_position(text_bounds, position);
 358            if point == target_point {
 359                Some(point)
 360            } else {
 361                None
 362            }
 363        } else {
 364            None
 365        };
 366
 367        cx.dispatch_action(UpdateGoToDefinitionLink {
 368            point,
 369            cmd_held: cmd,
 370            shift_held: shift,
 371        });
 372
 373        let view = view.upgrade(cx.app).unwrap().read(cx.app);
 374        if view.has_pending_selection() {
 375            let mut scroll_delta = Vector2F::zero();
 376
 377            let vertical_margin = position_map.line_height.min(text_bounds.height() / 3.0);
 378            let top = text_bounds.origin_y() + vertical_margin;
 379            let bottom = text_bounds.lower_left().y() - vertical_margin;
 380            if position.y() < top {
 381                scroll_delta.set_y(-scale_vertical_mouse_autoscroll_delta(top - position.y()))
 382            }
 383            if position.y() > bottom {
 384                scroll_delta.set_y(scale_vertical_mouse_autoscroll_delta(position.y() - bottom))
 385            }
 386
 387            let horizontal_margin = position_map.line_height.min(text_bounds.width() / 3.0);
 388            let left = text_bounds.origin_x() + horizontal_margin;
 389            let right = text_bounds.upper_right().x() - horizontal_margin;
 390            if position.x() < left {
 391                scroll_delta.set_x(-scale_horizontal_mouse_autoscroll_delta(
 392                    left - position.x(),
 393                ))
 394            }
 395            if position.x() > right {
 396                scroll_delta.set_x(scale_horizontal_mouse_autoscroll_delta(
 397                    position.x() - right,
 398                ))
 399            }
 400
 401            let (position, target_position) =
 402                position_map.point_for_position(text_bounds, position);
 403
 404            cx.dispatch_action(Select(SelectPhase::Update {
 405                position,
 406                goal_column: target_position.column(),
 407                scroll_position: (position_map.snapshot.scroll_position() + scroll_delta)
 408                    .clamp(Vector2F::zero(), position_map.scroll_max),
 409            }));
 410
 411            cx.dispatch_action(HoverAt { point });
 412            true
 413        } else {
 414            cx.dispatch_action(HoverAt { point });
 415            false
 416        }
 417    }
 418
 419    fn mouse_moved(
 420        MouseMovedEvent {
 421            modifiers: Modifiers { shift, cmd, .. },
 422            position,
 423            ..
 424        }: MouseMovedEvent,
 425        position_map: &PositionMap,
 426        text_bounds: RectF,
 427        cx: &mut EventContext,
 428    ) -> bool {
 429        // This will be handled more correctly once https://github.com/zed-industries/zed/issues/1218 is completed
 430        // Don't trigger hover popover if mouse is hovering over context menu
 431        let point = position_to_display_point(position, text_bounds, position_map);
 432
 433        cx.dispatch_action(UpdateGoToDefinitionLink {
 434            point,
 435            cmd_held: cmd,
 436            shift_held: shift,
 437        });
 438
 439        cx.dispatch_action(HoverAt { point });
 440
 441        true
 442    }
 443
 444    fn scroll(
 445        position: Vector2F,
 446        mut delta: Vector2F,
 447        precise: bool,
 448        position_map: &PositionMap,
 449        bounds: RectF,
 450        cx: &mut EventContext,
 451    ) -> bool {
 452        if !bounds.contains_point(position) {
 453            return false;
 454        }
 455
 456        let line_height = position_map.line_height;
 457        let max_glyph_width = position_map.em_width;
 458
 459        let axis = if precise {
 460            //Trackpad
 461            position_map.snapshot.ongoing_scroll.filter(&mut delta)
 462        } else {
 463            //Not trackpad
 464            delta *= vec2f(max_glyph_width, line_height);
 465            None //Resets ongoing scroll
 466        };
 467
 468        let scroll_position = position_map.snapshot.scroll_position();
 469        let x = (scroll_position.x() * max_glyph_width - delta.x()) / max_glyph_width;
 470        let y = (scroll_position.y() * line_height - delta.y()) / line_height;
 471        let scroll_position = vec2f(x, y).clamp(Vector2F::zero(), position_map.scroll_max);
 472
 473        cx.dispatch_action(Scroll {
 474            scroll_position,
 475            axis,
 476        });
 477
 478        true
 479    }
 480
 481    fn paint_background(
 482        &self,
 483        gutter_bounds: RectF,
 484        text_bounds: RectF,
 485        layout: &LayoutState,
 486        cx: &mut PaintContext,
 487    ) {
 488        let bounds = gutter_bounds.union_rect(text_bounds);
 489        let scroll_top =
 490            layout.position_map.snapshot.scroll_position().y() * layout.position_map.line_height;
 491        cx.scene.push_quad(Quad {
 492            bounds: gutter_bounds,
 493            background: Some(self.style.gutter_background),
 494            border: Border::new(0., Color::transparent_black()),
 495            corner_radius: 0.,
 496        });
 497        cx.scene.push_quad(Quad {
 498            bounds: text_bounds,
 499            background: Some(self.style.background),
 500            border: Border::new(0., Color::transparent_black()),
 501            corner_radius: 0.,
 502        });
 503
 504        if let EditorMode::Full = layout.mode {
 505            let mut active_rows = layout.active_rows.iter().peekable();
 506            while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
 507                let mut end_row = *start_row;
 508                while active_rows.peek().map_or(false, |r| {
 509                    *r.0 == end_row + 1 && r.1 == contains_non_empty_selection
 510                }) {
 511                    active_rows.next().unwrap();
 512                    end_row += 1;
 513                }
 514
 515                if !contains_non_empty_selection {
 516                    let origin = vec2f(
 517                        bounds.origin_x(),
 518                        bounds.origin_y() + (layout.position_map.line_height * *start_row as f32)
 519                            - scroll_top,
 520                    );
 521                    let size = vec2f(
 522                        bounds.width(),
 523                        layout.position_map.line_height * (end_row - start_row + 1) as f32,
 524                    );
 525                    cx.scene.push_quad(Quad {
 526                        bounds: RectF::new(origin, size),
 527                        background: Some(self.style.active_line_background),
 528                        border: Border::default(),
 529                        corner_radius: 0.,
 530                    });
 531                }
 532            }
 533
 534            if let Some(highlighted_rows) = &layout.highlighted_rows {
 535                let origin = vec2f(
 536                    bounds.origin_x(),
 537                    bounds.origin_y()
 538                        + (layout.position_map.line_height * highlighted_rows.start as f32)
 539                        - scroll_top,
 540                );
 541                let size = vec2f(
 542                    bounds.width(),
 543                    layout.position_map.line_height * highlighted_rows.len() as f32,
 544                );
 545                cx.scene.push_quad(Quad {
 546                    bounds: RectF::new(origin, size),
 547                    background: Some(self.style.highlighted_line_background),
 548                    border: Border::default(),
 549                    corner_radius: 0.,
 550                });
 551            }
 552        }
 553    }
 554
 555    fn paint_gutter(
 556        &mut self,
 557        bounds: RectF,
 558        visible_bounds: RectF,
 559        layout: &mut LayoutState,
 560        cx: &mut PaintContext,
 561    ) {
 562        let line_height = layout.position_map.line_height;
 563
 564        let scroll_position = layout.position_map.snapshot.scroll_position();
 565        let scroll_top = scroll_position.y() * line_height;
 566
 567        let show_gutter = matches!(
 568            &cx.global::<Settings>()
 569                .git_overrides
 570                .git_gutter
 571                .unwrap_or_default(),
 572            GitGutter::TrackedFiles
 573        );
 574
 575        if show_gutter {
 576            Self::paint_diff_hunks(bounds, layout, cx);
 577        }
 578
 579        for (ix, line) in layout.line_number_layouts.iter().enumerate() {
 580            if let Some(line) = line {
 581                let line_origin = bounds.origin()
 582                    + vec2f(
 583                        bounds.width() - line.width() - layout.gutter_padding,
 584                        ix as f32 * line_height - (scroll_top % line_height),
 585                    );
 586
 587                line.paint(line_origin, visible_bounds, line_height, cx);
 588            }
 589        }
 590
 591        if let Some((row, indicator)) = layout.code_actions_indicator.as_mut() {
 592            let mut x = 0.;
 593            let mut y = *row as f32 * line_height - scroll_top;
 594            x += ((layout.gutter_padding + layout.gutter_margin) - indicator.size().x()) / 2.;
 595            y += (line_height - indicator.size().y()) / 2.;
 596            indicator.paint(bounds.origin() + vec2f(x, y), visible_bounds, cx);
 597        }
 598
 599        layout.fold_indicators.as_mut().map(|fold_indicators| {
 600            for (line, fold_indicator) in fold_indicators.iter_mut() {
 601                let mut x = bounds.width() - layout.gutter_padding;
 602                let mut y = *line as f32 * line_height - scroll_top;
 603
 604                x += ((layout.gutter_padding + layout.gutter_margin) - fold_indicator.size().x())
 605                    / 2.;
 606                y += (line_height - fold_indicator.size().y()) / 2.;
 607
 608                fold_indicator.paint(bounds.origin() + vec2f(x, y), visible_bounds, cx);
 609            }
 610        });
 611    }
 612
 613    fn paint_diff_hunks(bounds: RectF, layout: &mut LayoutState, cx: &mut PaintContext) {
 614        let diff_style = &cx.global::<Settings>().theme.editor.diff.clone();
 615        let line_height = layout.position_map.line_height;
 616
 617        let scroll_position = layout.position_map.snapshot.scroll_position();
 618        let scroll_top = scroll_position.y() * line_height;
 619
 620        for hunk in &layout.display_hunks {
 621            let (display_row_range, status) = match hunk {
 622                //TODO: This rendering is entirely a horrible hack
 623                &DisplayDiffHunk::Folded { display_row: row } => {
 624                    let start_y = row as f32 * line_height - scroll_top;
 625                    let end_y = start_y + line_height;
 626
 627                    let width = diff_style.removed_width_em * line_height;
 628                    let highlight_origin = bounds.origin() + vec2f(-width, start_y);
 629                    let highlight_size = vec2f(width * 2., end_y - start_y);
 630                    let highlight_bounds = RectF::new(highlight_origin, highlight_size);
 631
 632                    cx.scene.push_quad(Quad {
 633                        bounds: highlight_bounds,
 634                        background: Some(diff_style.modified),
 635                        border: Border::new(0., Color::transparent_black()),
 636                        corner_radius: 1. * line_height,
 637                    });
 638
 639                    continue;
 640                }
 641
 642                DisplayDiffHunk::Unfolded {
 643                    display_row_range,
 644                    status,
 645                } => (display_row_range, status),
 646            };
 647
 648            let color = match status {
 649                DiffHunkStatus::Added => diff_style.inserted,
 650                DiffHunkStatus::Modified => diff_style.modified,
 651
 652                //TODO: This rendering is entirely a horrible hack
 653                DiffHunkStatus::Removed => {
 654                    let row = *display_row_range.start();
 655
 656                    let offset = line_height / 2.;
 657                    let start_y = row as f32 * line_height - offset - scroll_top;
 658                    let end_y = start_y + line_height;
 659
 660                    let width = diff_style.removed_width_em * line_height;
 661                    let highlight_origin = bounds.origin() + vec2f(-width, start_y);
 662                    let highlight_size = vec2f(width * 2., end_y - start_y);
 663                    let highlight_bounds = RectF::new(highlight_origin, highlight_size);
 664
 665                    cx.scene.push_quad(Quad {
 666                        bounds: highlight_bounds,
 667                        background: Some(diff_style.deleted),
 668                        border: Border::new(0., Color::transparent_black()),
 669                        corner_radius: 1. * line_height,
 670                    });
 671
 672                    continue;
 673                }
 674            };
 675
 676            let start_row = *display_row_range.start();
 677            let end_row = *display_row_range.end();
 678
 679            let start_y = start_row as f32 * line_height - scroll_top;
 680            let end_y = end_row as f32 * line_height - scroll_top + line_height;
 681
 682            let width = diff_style.width_em * line_height;
 683            let highlight_origin = bounds.origin() + vec2f(-width, start_y);
 684            let highlight_size = vec2f(width * 2., end_y - start_y);
 685            let highlight_bounds = RectF::new(highlight_origin, highlight_size);
 686
 687            cx.scene.push_quad(Quad {
 688                bounds: highlight_bounds,
 689                background: Some(color),
 690                border: Border::new(0., Color::transparent_black()),
 691                corner_radius: diff_style.corner_radius * line_height,
 692            });
 693        }
 694    }
 695
 696    fn paint_text(
 697        &mut self,
 698        bounds: RectF,
 699        visible_bounds: RectF,
 700        layout: &mut LayoutState,
 701        cx: &mut PaintContext,
 702    ) {
 703        let view = self.view(cx.app);
 704        let style = &self.style;
 705        let local_replica_id = view.replica_id(cx);
 706        let scroll_position = layout.position_map.snapshot.scroll_position();
 707        let start_row = layout.visible_display_row_range.start;
 708        let scroll_top = scroll_position.y() * layout.position_map.line_height;
 709        let max_glyph_width = layout.position_map.em_width;
 710        let scroll_left = scroll_position.x() * max_glyph_width;
 711        let content_origin = bounds.origin() + vec2f(layout.gutter_margin, 0.);
 712        let line_end_overshoot = 0.15 * layout.position_map.line_height;
 713
 714        cx.scene.push_layer(Some(bounds));
 715
 716        cx.scene.push_cursor_region(CursorRegion {
 717            bounds,
 718            style: if !view.link_go_to_definition_state.definitions.is_empty() {
 719                CursorStyle::PointingHand
 720            } else {
 721                CursorStyle::IBeam
 722            },
 723        });
 724
 725        for (range, _) in layout.click_ranges.iter() {
 726            for bound in range_to_bounds(
 727                range,
 728                content_origin,
 729                scroll_left,
 730                scroll_top,
 731                &layout.visible_display_row_range,
 732                line_end_overshoot,
 733                &layout.position_map,
 734            ) {
 735                cx.scene.push_cursor_region(CursorRegion {
 736                    bounds: bound,
 737                    style: CursorStyle::PointingHand,
 738                });
 739            }
 740        }
 741
 742        for (range, color) in &layout.highlighted_ranges {
 743            self.paint_highlighted_range(
 744                range.clone(),
 745                *color,
 746                0.,
 747                line_end_overshoot,
 748                layout,
 749                content_origin,
 750                scroll_top,
 751                scroll_left,
 752                bounds,
 753                cx,
 754            );
 755        }
 756
 757        let mut cursors = SmallVec::<[Cursor; 32]>::new();
 758        for (replica_id, selections) in &layout.selections {
 759            let selection_style = style.replica_selection_style(*replica_id);
 760            let corner_radius = 0.15 * layout.position_map.line_height;
 761
 762            for selection in selections {
 763                self.paint_highlighted_range(
 764                    selection.range.clone(),
 765                    selection_style.selection,
 766                    corner_radius,
 767                    corner_radius * 2.,
 768                    layout,
 769                    content_origin,
 770                    scroll_top,
 771                    scroll_left,
 772                    bounds,
 773                    cx,
 774                );
 775
 776                if view.show_local_cursors(cx) || *replica_id != local_replica_id {
 777                    let cursor_position = selection.head;
 778                    if layout
 779                        .visible_display_row_range
 780                        .contains(&cursor_position.row())
 781                    {
 782                        let cursor_row_layout = &layout.position_map.line_layouts
 783                            [(cursor_position.row() - start_row) as usize];
 784                        let cursor_column = cursor_position.column() as usize;
 785
 786                        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 787                        let mut block_width =
 788                            cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
 789                        if block_width == 0.0 {
 790                            block_width = layout.position_map.em_width;
 791                        }
 792                        let block_text = if let CursorShape::Block = selection.cursor_shape {
 793                            layout
 794                                .position_map
 795                                .snapshot
 796                                .chars_at(cursor_position)
 797                                .next()
 798                                .and_then(|(character, _)| {
 799                                    let font_id =
 800                                        cursor_row_layout.font_for_index(cursor_column)?;
 801                                    let text = character.to_string();
 802
 803                                    Some(cx.text_layout_cache.layout_str(
 804                                        &text,
 805                                        cursor_row_layout.font_size(),
 806                                        &[(
 807                                            text.len(),
 808                                            RunStyle {
 809                                                font_id,
 810                                                color: style.background,
 811                                                underline: Default::default(),
 812                                            },
 813                                        )],
 814                                    ))
 815                                })
 816                        } else {
 817                            None
 818                        };
 819
 820                        let x = cursor_character_x - scroll_left;
 821                        let y = cursor_position.row() as f32 * layout.position_map.line_height
 822                            - scroll_top;
 823                        cursors.push(Cursor {
 824                            color: selection_style.cursor,
 825                            block_width,
 826                            origin: vec2f(x, y),
 827                            line_height: layout.position_map.line_height,
 828                            shape: selection.cursor_shape,
 829                            block_text,
 830                        });
 831                    }
 832                }
 833            }
 834        }
 835
 836        if let Some(visible_text_bounds) = bounds.intersection(visible_bounds) {
 837            // Draw glyphs
 838            for (ix, line) in layout.position_map.line_layouts.iter().enumerate() {
 839                let row = start_row + ix as u32;
 840                line.paint(
 841                    content_origin
 842                        + vec2f(
 843                            -scroll_left,
 844                            row as f32 * layout.position_map.line_height - scroll_top,
 845                        ),
 846                    visible_text_bounds,
 847                    layout.position_map.line_height,
 848                    cx,
 849                );
 850            }
 851        }
 852
 853        cx.scene.push_layer(Some(bounds));
 854        for cursor in cursors {
 855            cursor.paint(content_origin, cx);
 856        }
 857        cx.scene.pop_layer();
 858
 859        if let Some((position, context_menu)) = layout.context_menu.as_mut() {
 860            cx.scene.push_stacking_context(None, None);
 861            let cursor_row_layout =
 862                &layout.position_map.line_layouts[(position.row() - start_row) as usize];
 863            let x = cursor_row_layout.x_for_index(position.column() as usize) - scroll_left;
 864            let y = (position.row() + 1) as f32 * layout.position_map.line_height - scroll_top;
 865            let mut list_origin = content_origin + vec2f(x, y);
 866            let list_width = context_menu.size().x();
 867            let list_height = context_menu.size().y();
 868
 869            // Snap the right edge of the list to the right edge of the window if
 870            // its horizontal bounds overflow.
 871            if list_origin.x() + list_width > cx.window_size.x() {
 872                list_origin.set_x((cx.window_size.x() - list_width).max(0.));
 873            }
 874
 875            if list_origin.y() + list_height > bounds.max_y() {
 876                list_origin.set_y(list_origin.y() - layout.position_map.line_height - list_height);
 877            }
 878
 879            context_menu.paint(
 880                list_origin,
 881                RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
 882                cx,
 883            );
 884
 885            cx.scene.pop_stacking_context();
 886        }
 887
 888        if let Some((position, hover_popovers)) = layout.hover_popovers.as_mut() {
 889            cx.scene.push_stacking_context(None, None);
 890
 891            // This is safe because we check on layout whether the required row is available
 892            let hovered_row_layout =
 893                &layout.position_map.line_layouts[(position.row() - start_row) as usize];
 894
 895            // Minimum required size: Take the first popover, and add 1.5 times the minimum popover
 896            // height. This is the size we will use to decide whether to render popovers above or below
 897            // the hovered line.
 898            let first_size = hover_popovers[0].size();
 899            let height_to_reserve = first_size.y()
 900                + 1.5 * MIN_POPOVER_LINE_HEIGHT as f32 * layout.position_map.line_height;
 901
 902            // Compute Hovered Point
 903            let x = hovered_row_layout.x_for_index(position.column() as usize) - scroll_left;
 904            let y = position.row() as f32 * layout.position_map.line_height - scroll_top;
 905            let hovered_point = content_origin + vec2f(x, y);
 906
 907            if hovered_point.y() - height_to_reserve > 0.0 {
 908                // There is enough space above. Render popovers above the hovered point
 909                let mut current_y = hovered_point.y();
 910                for hover_popover in hover_popovers {
 911                    let size = hover_popover.size();
 912                    let mut popover_origin = vec2f(hovered_point.x(), current_y - size.y());
 913
 914                    let x_out_of_bounds = bounds.max_x() - (popover_origin.x() + size.x());
 915                    if x_out_of_bounds < 0.0 {
 916                        popover_origin.set_x(popover_origin.x() + x_out_of_bounds);
 917                    }
 918
 919                    hover_popover.paint(
 920                        popover_origin,
 921                        RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
 922                        cx,
 923                    );
 924
 925                    current_y = popover_origin.y() - HOVER_POPOVER_GAP;
 926                }
 927            } else {
 928                // There is not enough space above. Render popovers below the hovered point
 929                let mut current_y = hovered_point.y() + layout.position_map.line_height;
 930                for hover_popover in hover_popovers {
 931                    let size = hover_popover.size();
 932                    let mut popover_origin = vec2f(hovered_point.x(), current_y);
 933
 934                    let x_out_of_bounds = bounds.max_x() - (popover_origin.x() + size.x());
 935                    if x_out_of_bounds < 0.0 {
 936                        popover_origin.set_x(popover_origin.x() + x_out_of_bounds);
 937                    }
 938
 939                    hover_popover.paint(
 940                        popover_origin,
 941                        RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
 942                        cx,
 943                    );
 944
 945                    current_y = popover_origin.y() + size.y() + HOVER_POPOVER_GAP;
 946                }
 947            }
 948
 949            cx.scene.pop_stacking_context();
 950        }
 951
 952        cx.scene.pop_layer();
 953    }
 954
 955    fn paint_scrollbar(&mut self, bounds: RectF, layout: &mut LayoutState, cx: &mut PaintContext) {
 956        enum ScrollbarMouseHandlers {}
 957        if layout.mode != EditorMode::Full {
 958            return;
 959        }
 960
 961        let view = self.view.clone();
 962        let style = &self.style.theme.scrollbar;
 963
 964        let top = bounds.min_y();
 965        let bottom = bounds.max_y();
 966        let right = bounds.max_x();
 967        let left = right - style.width;
 968        let row_range = &layout.scrollbar_row_range;
 969        let max_row = layout.max_row as f32 + (row_range.end - row_range.start);
 970
 971        let mut height = bounds.height();
 972        let mut first_row_y_offset = 0.0;
 973
 974        // Impose a minimum height on the scrollbar thumb
 975        let min_thumb_height =
 976            style.min_height_factor * cx.font_cache.line_height(self.style.text.font_size);
 977        let thumb_height = (row_range.end - row_range.start) * height / max_row;
 978        if thumb_height < min_thumb_height {
 979            first_row_y_offset = (min_thumb_height - thumb_height) / 2.0;
 980            height -= min_thumb_height - thumb_height;
 981        }
 982
 983        let y_for_row = |row: f32| -> f32 { top + first_row_y_offset + row * height / max_row };
 984
 985        let thumb_top = y_for_row(row_range.start) - first_row_y_offset;
 986        let thumb_bottom = y_for_row(row_range.end) + first_row_y_offset;
 987        let track_bounds = RectF::from_points(vec2f(left, top), vec2f(right, bottom));
 988        let thumb_bounds = RectF::from_points(vec2f(left, thumb_top), vec2f(right, thumb_bottom));
 989
 990        if layout.show_scrollbars {
 991            cx.scene.push_quad(Quad {
 992                bounds: track_bounds,
 993                border: style.track.border,
 994                background: style.track.background_color,
 995                ..Default::default()
 996            });
 997            cx.scene.push_quad(Quad {
 998                bounds: thumb_bounds,
 999                border: style.thumb.border,
1000                background: style.thumb.background_color,
1001                corner_radius: style.thumb.corner_radius,
1002            });
1003        }
1004
1005        cx.scene.push_cursor_region(CursorRegion {
1006            bounds: track_bounds,
1007            style: CursorStyle::Arrow,
1008        });
1009        cx.scene.push_mouse_region(
1010            MouseRegion::new::<ScrollbarMouseHandlers>(view.id(), view.id(), track_bounds)
1011                .on_move({
1012                    let view = view.clone();
1013                    move |_, cx| {
1014                        if let Some(view) = view.upgrade(cx.deref_mut()) {
1015                            view.update(cx.deref_mut(), |view, cx| {
1016                                view.scroll_manager.show_scrollbar(cx);
1017                            });
1018                        }
1019                    }
1020                })
1021                .on_down(MouseButton::Left, {
1022                    let view = view.clone();
1023                    let row_range = row_range.clone();
1024                    move |e, cx| {
1025                        let y = e.position.y();
1026                        if let Some(view) = view.upgrade(cx.deref_mut()) {
1027                            view.update(cx.deref_mut(), |view, cx| {
1028                                if y < thumb_top || thumb_bottom < y {
1029                                    let center_row =
1030                                        ((y - top) * max_row as f32 / height).round() as u32;
1031                                    let top_row = center_row.saturating_sub(
1032                                        (row_range.end - row_range.start) as u32 / 2,
1033                                    );
1034                                    let mut position = view.scroll_position(cx);
1035                                    position.set_y(top_row as f32);
1036                                    view.set_scroll_position(position, cx);
1037                                } else {
1038                                    view.scroll_manager.show_scrollbar(cx);
1039                                }
1040                            });
1041                        }
1042                    }
1043                })
1044                .on_drag(MouseButton::Left, {
1045                    let view = view.clone();
1046                    move |e, cx| {
1047                        let y = e.prev_mouse_position.y();
1048                        let new_y = e.position.y();
1049                        if thumb_top < y && y < thumb_bottom {
1050                            if let Some(view) = view.upgrade(cx.deref_mut()) {
1051                                view.update(cx.deref_mut(), |view, cx| {
1052                                    let mut position = view.scroll_position(cx);
1053                                    position.set_y(
1054                                        position.y() + (new_y - y) * (max_row as f32) / height,
1055                                    );
1056                                    if position.y() < 0.0 {
1057                                        position.set_y(0.);
1058                                    }
1059                                    view.set_scroll_position(position, cx);
1060                                });
1061                            }
1062                        }
1063                    }
1064                }),
1065        );
1066    }
1067
1068    #[allow(clippy::too_many_arguments)]
1069    fn paint_highlighted_range(
1070        &self,
1071        range: Range<DisplayPoint>,
1072        color: Color,
1073        corner_radius: f32,
1074        line_end_overshoot: f32,
1075        layout: &LayoutState,
1076        content_origin: Vector2F,
1077        scroll_top: f32,
1078        scroll_left: f32,
1079        bounds: RectF,
1080        cx: &mut PaintContext,
1081    ) {
1082        let start_row = layout.visible_display_row_range.start;
1083        let end_row = layout.visible_display_row_range.end;
1084        if range.start != range.end {
1085            let row_range = if range.end.column() == 0 {
1086                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
1087            } else {
1088                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
1089            };
1090
1091            let highlighted_range = HighlightedRange {
1092                color,
1093                line_height: layout.position_map.line_height,
1094                corner_radius,
1095                start_y: content_origin.y()
1096                    + row_range.start as f32 * layout.position_map.line_height
1097                    - scroll_top,
1098                lines: row_range
1099                    .into_iter()
1100                    .map(|row| {
1101                        let line_layout =
1102                            &layout.position_map.line_layouts[(row - start_row) as usize];
1103                        HighlightedRangeLine {
1104                            start_x: if row == range.start.row() {
1105                                content_origin.x()
1106                                    + line_layout.x_for_index(range.start.column() as usize)
1107                                    - scroll_left
1108                            } else {
1109                                content_origin.x() - scroll_left
1110                            },
1111                            end_x: if row == range.end.row() {
1112                                content_origin.x()
1113                                    + line_layout.x_for_index(range.end.column() as usize)
1114                                    - scroll_left
1115                            } else {
1116                                content_origin.x() + line_layout.width() + line_end_overshoot
1117                                    - scroll_left
1118                            },
1119                        }
1120                    })
1121                    .collect(),
1122            };
1123
1124            highlighted_range.paint(bounds, cx.scene);
1125        }
1126    }
1127
1128    fn paint_blocks(
1129        &mut self,
1130        bounds: RectF,
1131        visible_bounds: RectF,
1132        layout: &mut LayoutState,
1133        cx: &mut PaintContext,
1134    ) {
1135        let scroll_position = layout.position_map.snapshot.scroll_position();
1136        let scroll_left = scroll_position.x() * layout.position_map.em_width;
1137        let scroll_top = scroll_position.y() * layout.position_map.line_height;
1138
1139        for block in &mut layout.blocks {
1140            let mut origin = bounds.origin()
1141                + vec2f(
1142                    0.,
1143                    block.row as f32 * layout.position_map.line_height - scroll_top,
1144                );
1145            if !matches!(block.style, BlockStyle::Sticky) {
1146                origin += vec2f(-scroll_left, 0.);
1147            }
1148            block.element.paint(origin, visible_bounds, cx);
1149        }
1150    }
1151
1152    fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &LayoutContext) -> f32 {
1153        let digit_count = (snapshot.max_buffer_row() as f32).log10().floor() as usize + 1;
1154        let style = &self.style;
1155
1156        cx.text_layout_cache
1157            .layout_str(
1158                "1".repeat(digit_count).as_str(),
1159                style.text.font_size,
1160                &[(
1161                    digit_count,
1162                    RunStyle {
1163                        font_id: style.text.font_id,
1164                        color: Color::black(),
1165                        underline: Default::default(),
1166                    },
1167                )],
1168            )
1169            .width()
1170    }
1171
1172    fn get_fold_indicators(
1173        &self,
1174        is_singleton: bool,
1175        display_rows: Range<u32>,
1176        snapshot: &EditorSnapshot,
1177    ) -> Option<Vec<(u32, FoldStatus)>> {
1178        is_singleton.then(|| {
1179            display_rows
1180                .into_iter()
1181                .filter_map(|display_row| {
1182                    snapshot
1183                        .fold_for_line(display_row)
1184                        .map(|fold_status| (display_row, fold_status))
1185                })
1186                .collect()
1187        })
1188    }
1189
1190    //Folds contained in a hunk are ignored apart from shrinking visual size
1191    //If a fold contains any hunks then that fold line is marked as modified
1192    fn layout_git_gutters(
1193        &self,
1194        display_rows: Range<u32>,
1195        snapshot: &EditorSnapshot,
1196    ) -> Vec<DisplayDiffHunk> {
1197        let buffer_snapshot = &snapshot.buffer_snapshot;
1198
1199        let buffer_start_row = DisplayPoint::new(display_rows.start, 0)
1200            .to_point(snapshot)
1201            .row;
1202        let buffer_end_row = DisplayPoint::new(display_rows.end, 0)
1203            .to_point(snapshot)
1204            .row;
1205
1206        buffer_snapshot
1207            .git_diff_hunks_in_range(buffer_start_row..buffer_end_row, false)
1208            .map(|hunk| diff_hunk_to_display(hunk, snapshot))
1209            .dedup()
1210            .collect()
1211    }
1212
1213    fn layout_line_numbers(
1214        &self,
1215        rows: Range<u32>,
1216        active_rows: &BTreeMap<u32, bool>,
1217        snapshot: &EditorSnapshot,
1218        cx: &LayoutContext,
1219    ) -> Vec<Option<text_layout::Line>> {
1220        let style = &self.style;
1221        let include_line_numbers = snapshot.mode == EditorMode::Full;
1222        let mut line_number_layouts = Vec::with_capacity(rows.len());
1223        let mut line_number = String::new();
1224        for (ix, row) in snapshot
1225            .buffer_rows(rows.start)
1226            .take((rows.end - rows.start) as usize)
1227            .enumerate()
1228        {
1229            let display_row = rows.start + ix as u32;
1230            let color = if active_rows.contains_key(&display_row) {
1231                style.line_number_active
1232            } else {
1233                style.line_number
1234            };
1235            if let Some(buffer_row) = row {
1236                if include_line_numbers {
1237                    line_number.clear();
1238                    write!(&mut line_number, "{}", buffer_row + 1).unwrap();
1239                    line_number_layouts.push(Some(cx.text_layout_cache.layout_str(
1240                        &line_number,
1241                        style.text.font_size,
1242                        &[(
1243                            line_number.len(),
1244                            RunStyle {
1245                                font_id: style.text.font_id,
1246                                color,
1247                                underline: Default::default(),
1248                            },
1249                        )],
1250                    )));
1251                }
1252            } else {
1253                line_number_layouts.push(None);
1254            }
1255        }
1256
1257        line_number_layouts
1258    }
1259
1260    fn layout_lines(
1261        &mut self,
1262        rows: Range<u32>,
1263        snapshot: &EditorSnapshot,
1264        cx: &LayoutContext,
1265    ) -> Vec<text_layout::Line> {
1266        if rows.start >= rows.end {
1267            return Vec::new();
1268        }
1269
1270        // When the editor is empty and unfocused, then show the placeholder.
1271        if snapshot.is_empty() {
1272            let placeholder_style = self
1273                .style
1274                .placeholder_text
1275                .as_ref()
1276                .unwrap_or(&self.style.text);
1277            let placeholder_text = snapshot.placeholder_text();
1278            let placeholder_lines = placeholder_text
1279                .as_ref()
1280                .map_or("", AsRef::as_ref)
1281                .split('\n')
1282                .skip(rows.start as usize)
1283                .chain(iter::repeat(""))
1284                .take(rows.len());
1285            placeholder_lines
1286                .map(|line| {
1287                    cx.text_layout_cache.layout_str(
1288                        line,
1289                        placeholder_style.font_size,
1290                        &[(
1291                            line.len(),
1292                            RunStyle {
1293                                font_id: placeholder_style.font_id,
1294                                color: placeholder_style.color,
1295                                underline: Default::default(),
1296                            },
1297                        )],
1298                    )
1299                })
1300                .collect()
1301        } else {
1302            let style = &self.style;
1303            let chunks = snapshot.chunks(rows.clone(), true).map(|chunk| {
1304                let mut highlight_style = chunk
1305                    .syntax_highlight_id
1306                    .and_then(|id| id.style(&style.syntax));
1307
1308                if let Some(chunk_highlight) = chunk.highlight_style {
1309                    if let Some(highlight_style) = highlight_style.as_mut() {
1310                        highlight_style.highlight(chunk_highlight);
1311                    } else {
1312                        highlight_style = Some(chunk_highlight);
1313                    }
1314                }
1315
1316                let mut diagnostic_highlight = HighlightStyle::default();
1317
1318                if chunk.is_unnecessary {
1319                    diagnostic_highlight.fade_out = Some(style.unnecessary_code_fade);
1320                }
1321
1322                if let Some(severity) = chunk.diagnostic_severity {
1323                    // Omit underlines for HINT/INFO diagnostics on 'unnecessary' code.
1324                    if severity <= DiagnosticSeverity::WARNING || !chunk.is_unnecessary {
1325                        let diagnostic_style = super::diagnostic_style(severity, true, style);
1326                        diagnostic_highlight.underline = Some(Underline {
1327                            color: Some(diagnostic_style.message.text.color),
1328                            thickness: 1.0.into(),
1329                            squiggly: true,
1330                        });
1331                    }
1332                }
1333
1334                if let Some(highlight_style) = highlight_style.as_mut() {
1335                    highlight_style.highlight(diagnostic_highlight);
1336                } else {
1337                    highlight_style = Some(diagnostic_highlight);
1338                }
1339
1340                (chunk.text, highlight_style)
1341            });
1342            layout_highlighted_chunks(
1343                chunks,
1344                &style.text,
1345                cx.text_layout_cache,
1346                cx.font_cache,
1347                MAX_LINE_LEN,
1348                rows.len() as usize,
1349            )
1350        }
1351    }
1352
1353    #[allow(clippy::too_many_arguments)]
1354    fn layout_blocks(
1355        &mut self,
1356        rows: Range<u32>,
1357        snapshot: &EditorSnapshot,
1358        editor_width: f32,
1359        scroll_width: f32,
1360        gutter_padding: f32,
1361        gutter_width: f32,
1362        em_width: f32,
1363        text_x: f32,
1364        line_height: f32,
1365        style: &EditorStyle,
1366        line_layouts: &[text_layout::Line],
1367        include_root: bool,
1368        cx: &mut LayoutContext,
1369    ) -> (f32, Vec<BlockLayout>) {
1370        let editor = if let Some(editor) = self.view.upgrade(cx) {
1371            editor
1372        } else {
1373            return Default::default();
1374        };
1375
1376        let tooltip_style = cx.global::<Settings>().theme.tooltip.clone();
1377        let scroll_x = snapshot.scroll_anchor.offset.x();
1378        let (fixed_blocks, non_fixed_blocks) = snapshot
1379            .blocks_in_range(rows.clone())
1380            .partition::<Vec<_>, _>(|(_, block)| match block {
1381                TransformBlock::ExcerptHeader { .. } => false,
1382                TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
1383            });
1384        let mut render_block = |block: &TransformBlock, width: f32| {
1385            let mut element = match block {
1386                TransformBlock::Custom(block) => {
1387                    let align_to = block
1388                        .position()
1389                        .to_point(&snapshot.buffer_snapshot)
1390                        .to_display_point(snapshot);
1391                    let anchor_x = text_x
1392                        + if rows.contains(&align_to.row()) {
1393                            line_layouts[(align_to.row() - rows.start) as usize]
1394                                .x_for_index(align_to.column() as usize)
1395                        } else {
1396                            layout_line(align_to.row(), snapshot, style, cx.text_layout_cache)
1397                                .x_for_index(align_to.column() as usize)
1398                        };
1399
1400                    cx.render(&editor, |_, cx| {
1401                        block.render(&mut BlockContext {
1402                            cx,
1403                            anchor_x,
1404                            gutter_padding,
1405                            line_height,
1406                            scroll_x,
1407                            gutter_width,
1408                            em_width,
1409                        })
1410                    })
1411                }
1412                TransformBlock::ExcerptHeader {
1413                    id,
1414                    buffer,
1415                    range,
1416                    starts_new_buffer,
1417                    ..
1418                } => {
1419                    let id = *id;
1420                    let jump_icon = project::File::from_dyn(buffer.file()).map(|file| {
1421                        let jump_position = range
1422                            .primary
1423                            .as_ref()
1424                            .map_or(range.context.start, |primary| primary.start);
1425                        let jump_action = crate::Jump {
1426                            path: ProjectPath {
1427                                worktree_id: file.worktree_id(cx),
1428                                path: file.path.clone(),
1429                            },
1430                            position: language::ToPoint::to_point(&jump_position, buffer),
1431                            anchor: jump_position,
1432                        };
1433
1434                        enum JumpIcon {}
1435                        cx.render(&editor, |_, cx| {
1436                            MouseEventHandler::<JumpIcon>::new(id.into(), cx, |state, _| {
1437                                let style = style.jump_icon.style_for(state, false);
1438                                Svg::new("icons/arrow_up_right_8.svg")
1439                                    .with_color(style.color)
1440                                    .constrained()
1441                                    .with_width(style.icon_width)
1442                                    .aligned()
1443                                    .contained()
1444                                    .with_style(style.container)
1445                                    .constrained()
1446                                    .with_width(style.button_width)
1447                                    .with_height(style.button_width)
1448                                    .boxed()
1449                            })
1450                            .with_cursor_style(CursorStyle::PointingHand)
1451                            .on_click(MouseButton::Left, move |_, cx| {
1452                                cx.dispatch_action(jump_action.clone())
1453                            })
1454                            .with_tooltip::<JumpIcon, _>(
1455                                id.into(),
1456                                "Jump to Buffer".to_string(),
1457                                Some(Box::new(crate::OpenExcerpts)),
1458                                tooltip_style.clone(),
1459                                cx,
1460                            )
1461                            .aligned()
1462                            .flex_float()
1463                            .boxed()
1464                        })
1465                    });
1466
1467                    if *starts_new_buffer {
1468                        let style = &self.style.diagnostic_path_header;
1469                        let font_size =
1470                            (style.text_scale_factor * self.style.text.font_size).round();
1471
1472                        let path = buffer.resolve_file_path(cx, include_root);
1473                        let mut filename = None;
1474                        let mut parent_path = None;
1475                        // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
1476                        if let Some(path) = path {
1477                            filename = path.file_name().map(|f| f.to_string_lossy().to_string());
1478                            parent_path =
1479                                path.parent().map(|p| p.to_string_lossy().to_string() + "/");
1480                        }
1481
1482                        Flex::row()
1483                            .with_child(
1484                                Label::new(
1485                                    filename.unwrap_or_else(|| "untitled".to_string()),
1486                                    style.filename.text.clone().with_font_size(font_size),
1487                                )
1488                                .contained()
1489                                .with_style(style.filename.container)
1490                                .aligned()
1491                                .boxed(),
1492                            )
1493                            .with_children(parent_path.map(|path| {
1494                                Label::new(path, style.path.text.clone().with_font_size(font_size))
1495                                    .contained()
1496                                    .with_style(style.path.container)
1497                                    .aligned()
1498                                    .boxed()
1499                            }))
1500                            .with_children(jump_icon)
1501                            .contained()
1502                            .with_style(style.container)
1503                            .with_padding_left(gutter_padding)
1504                            .with_padding_right(gutter_padding)
1505                            .expanded()
1506                            .named("path header block")
1507                    } else {
1508                        let text_style = self.style.text.clone();
1509                        Flex::row()
1510                            .with_child(Label::new("", text_style).boxed())
1511                            .with_children(jump_icon)
1512                            .contained()
1513                            .with_padding_left(gutter_padding)
1514                            .with_padding_right(gutter_padding)
1515                            .expanded()
1516                            .named("collapsed context")
1517                    }
1518                }
1519            };
1520
1521            element.layout(
1522                SizeConstraint {
1523                    min: Vector2F::zero(),
1524                    max: vec2f(width, block.height() as f32 * line_height),
1525                },
1526                cx,
1527            );
1528            element
1529        };
1530
1531        let mut fixed_block_max_width = 0f32;
1532        let mut blocks = Vec::new();
1533        for (row, block) in fixed_blocks {
1534            let element = render_block(block, f32::INFINITY);
1535            fixed_block_max_width = fixed_block_max_width.max(element.size().x() + em_width);
1536            blocks.push(BlockLayout {
1537                row,
1538                element,
1539                style: BlockStyle::Fixed,
1540            });
1541        }
1542        for (row, block) in non_fixed_blocks {
1543            let style = match block {
1544                TransformBlock::Custom(block) => block.style(),
1545                TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
1546            };
1547            let width = match style {
1548                BlockStyle::Sticky => editor_width,
1549                BlockStyle::Flex => editor_width
1550                    .max(fixed_block_max_width)
1551                    .max(gutter_width + scroll_width),
1552                BlockStyle::Fixed => unreachable!(),
1553            };
1554            let element = render_block(block, width);
1555            blocks.push(BlockLayout {
1556                row,
1557                element,
1558                style,
1559            });
1560        }
1561        (
1562            scroll_width.max(fixed_block_max_width - gutter_width),
1563            blocks,
1564        )
1565    }
1566}
1567
1568impl Element for EditorElement {
1569    type LayoutState = LayoutState;
1570    type PaintState = ();
1571
1572    fn layout(
1573        &mut self,
1574        constraint: SizeConstraint,
1575        cx: &mut LayoutContext,
1576    ) -> (Vector2F, Self::LayoutState) {
1577        let mut size = constraint.max;
1578        if size.x().is_infinite() {
1579            unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
1580        }
1581
1582        let snapshot = self.snapshot(cx.app);
1583        let style = self.style.clone();
1584        let line_height = style.text.line_height(cx.font_cache);
1585
1586        let gutter_padding;
1587        let gutter_width;
1588        let gutter_margin;
1589        if snapshot.mode == EditorMode::Full {
1590            gutter_padding = style.text.em_width(cx.font_cache) * style.gutter_padding_factor;
1591            gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
1592            gutter_margin = -style.text.descent(cx.font_cache);
1593        } else {
1594            gutter_padding = 0.0;
1595            gutter_width = 0.0;
1596            gutter_margin = 0.0;
1597        };
1598
1599        let text_width = size.x() - gutter_width;
1600        let em_width = style.text.em_width(cx.font_cache);
1601        let em_advance = style.text.em_advance(cx.font_cache);
1602        let overscroll = vec2f(em_width, 0.);
1603        let snapshot = self.update_view(cx.app, |view, cx| {
1604            view.set_visible_line_count(size.y() / line_height);
1605
1606            let editor_width = text_width - gutter_margin - overscroll.x() - em_width;
1607            let wrap_width = match view.soft_wrap_mode(cx) {
1608                SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
1609                SoftWrap::EditorWidth => editor_width,
1610                SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
1611            };
1612
1613            if view.set_wrap_width(Some(wrap_width), cx) {
1614                view.snapshot(cx)
1615            } else {
1616                snapshot
1617            }
1618        });
1619
1620        let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
1621        if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
1622            size.set_y(
1623                scroll_height
1624                    .min(constraint.max_along(Axis::Vertical))
1625                    .max(constraint.min_along(Axis::Vertical))
1626                    .min(line_height * max_lines as f32),
1627            )
1628        } else if let EditorMode::SingleLine = snapshot.mode {
1629            size.set_y(
1630                line_height
1631                    .min(constraint.max_along(Axis::Vertical))
1632                    .max(constraint.min_along(Axis::Vertical)),
1633            )
1634        } else if size.y().is_infinite() {
1635            size.set_y(scroll_height);
1636        }
1637        let gutter_size = vec2f(gutter_width, size.y());
1638        let text_size = vec2f(text_width, size.y());
1639
1640        let (autoscroll_horizontally, mut snapshot) = self.update_view(cx.app, |view, cx| {
1641            let autoscroll_horizontally = view.autoscroll_vertically(size.y(), line_height, cx);
1642            let snapshot = view.snapshot(cx);
1643            (autoscroll_horizontally, snapshot)
1644        });
1645
1646        let scroll_position = snapshot.scroll_position();
1647        // The scroll position is a fractional point, the whole number of which represents
1648        // the top of the window in terms of display rows.
1649        let start_row = scroll_position.y() as u32;
1650        let height_in_lines = size.y() / line_height;
1651        let max_row = snapshot.max_point().row();
1652
1653        // Add 1 to ensure selections bleed off screen
1654        let end_row = 1 + cmp::min(
1655            (scroll_position.y() + height_in_lines).ceil() as u32,
1656            max_row,
1657        );
1658
1659        let start_anchor = if start_row == 0 {
1660            Anchor::min()
1661        } else {
1662            snapshot
1663                .buffer_snapshot
1664                .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
1665        };
1666        let end_anchor = if end_row > max_row {
1667            Anchor::max()
1668        } else {
1669            snapshot
1670                .buffer_snapshot
1671                .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
1672        };
1673
1674        let mut selections: Vec<(ReplicaId, Vec<SelectionLayout>)> = Vec::new();
1675        let mut active_rows = BTreeMap::new();
1676        let mut highlighted_rows = None;
1677        let mut highlighted_ranges = Vec::new();
1678        let mut click_ranges = Vec::new();
1679        let mut show_scrollbars = false;
1680        let mut include_root = false;
1681        let mut is_singleton = false;
1682        self.update_view(cx.app, |view, cx| {
1683            is_singleton = view.is_singleton(cx);
1684
1685            let display_map = view.display_map.update(cx, |map, cx| map.snapshot(cx));
1686
1687            highlighted_rows = view.highlighted_rows();
1688            let theme = cx.global::<Settings>().theme.as_ref();
1689            highlighted_ranges =
1690                view.background_highlights_in_range(start_anchor..end_anchor, &display_map, theme);
1691            click_ranges = view.click_ranges_in_range(start_anchor..end_anchor, &display_map);
1692
1693            let mut remote_selections = HashMap::default();
1694            for (replica_id, line_mode, cursor_shape, selection) in display_map
1695                .buffer_snapshot
1696                .remote_selections_in_range(&(start_anchor..end_anchor))
1697            {
1698                // The local selections match the leader's selections.
1699                if Some(replica_id) == view.leader_replica_id {
1700                    continue;
1701                }
1702                remote_selections
1703                    .entry(replica_id)
1704                    .or_insert(Vec::new())
1705                    .push(SelectionLayout::new(
1706                        selection,
1707                        line_mode,
1708                        cursor_shape,
1709                        &display_map,
1710                    ));
1711            }
1712            selections.extend(remote_selections);
1713
1714            if view.show_local_selections {
1715                let mut local_selections = view
1716                    .selections
1717                    .disjoint_in_range(start_anchor..end_anchor, cx);
1718                local_selections.extend(view.selections.pending(cx));
1719                for selection in &local_selections {
1720                    let is_empty = selection.start == selection.end;
1721                    let selection_start = snapshot.prev_line_boundary(selection.start).1;
1722                    let selection_end = snapshot.next_line_boundary(selection.end).1;
1723                    for row in cmp::max(selection_start.row(), start_row)
1724                        ..=cmp::min(selection_end.row(), end_row)
1725                    {
1726                        let contains_non_empty_selection =
1727                            active_rows.entry(row).or_insert(!is_empty);
1728                        *contains_non_empty_selection |= !is_empty;
1729                    }
1730                }
1731
1732                // Render the local selections in the leader's color when following.
1733                let local_replica_id = view
1734                    .leader_replica_id
1735                    .unwrap_or_else(|| view.replica_id(cx));
1736
1737                selections.push((
1738                    local_replica_id,
1739                    local_selections
1740                        .into_iter()
1741                        .map(|selection| {
1742                            SelectionLayout::new(
1743                                selection,
1744                                view.selections.line_mode,
1745                                view.cursor_shape,
1746                                &display_map,
1747                            )
1748                        })
1749                        .collect(),
1750                ));
1751            }
1752
1753            show_scrollbars = view.scroll_manager.scrollbars_visible();
1754            include_root = view
1755                .project
1756                .as_ref()
1757                .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
1758                .unwrap_or_default()
1759        });
1760
1761        let line_number_layouts =
1762            self.layout_line_numbers(start_row..end_row, &active_rows, &snapshot, cx);
1763
1764        let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
1765
1766        let folds = self.get_fold_indicators(is_singleton, start_row..end_row, &snapshot);
1767
1768        let scrollbar_row_range = scroll_position.y()..(scroll_position.y() + height_in_lines);
1769
1770        let mut max_visible_line_width = 0.0;
1771        let line_layouts = self.layout_lines(start_row..end_row, &snapshot, cx);
1772        for line in &line_layouts {
1773            if line.width() > max_visible_line_width {
1774                max_visible_line_width = line.width();
1775            }
1776        }
1777
1778        let style = self.style.clone();
1779        let longest_line_width = layout_line(
1780            snapshot.longest_row(),
1781            &snapshot,
1782            &style,
1783            cx.text_layout_cache,
1784        )
1785        .width();
1786        let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
1787        let em_width = style.text.em_width(cx.font_cache);
1788        let (scroll_width, blocks) = self.layout_blocks(
1789            start_row..end_row,
1790            &snapshot,
1791            size.x(),
1792            scroll_width,
1793            gutter_padding,
1794            gutter_width,
1795            em_width,
1796            gutter_width + gutter_margin,
1797            line_height,
1798            &style,
1799            &line_layouts,
1800            include_root,
1801            cx,
1802        );
1803
1804        let scroll_max = vec2f(
1805            ((scroll_width - text_size.x()) / em_width).max(0.0),
1806            max_row as f32,
1807        );
1808
1809        self.update_view(cx.app, |view, cx| {
1810            let clamped = view.scroll_manager.clamp_scroll_left(scroll_max.x());
1811
1812            let autoscrolled = if autoscroll_horizontally {
1813                view.autoscroll_horizontally(
1814                    start_row,
1815                    text_size.x(),
1816                    scroll_width,
1817                    em_width,
1818                    &line_layouts,
1819                    cx,
1820                )
1821            } else {
1822                false
1823            };
1824
1825            if clamped || autoscrolled {
1826                snapshot = view.snapshot(cx);
1827            }
1828        });
1829
1830        let mut context_menu = None;
1831        let mut code_actions_indicator = None;
1832        let mut hover = None;
1833        let mut mode = EditorMode::Full;
1834        let mut fold_indicators = cx.render(&self.view.upgrade(cx).unwrap(), |view, cx| {
1835            let newest_selection_head = view
1836                .selections
1837                .newest::<usize>(cx)
1838                .head()
1839                .to_display_point(&snapshot);
1840
1841            let style = view.style(cx);
1842            if (start_row..end_row).contains(&newest_selection_head.row()) {
1843                if view.context_menu_visible() {
1844                    context_menu =
1845                        view.render_context_menu(newest_selection_head, style.clone(), cx);
1846                }
1847
1848                let active = matches!(view.context_menu, Some(crate::ContextMenu::CodeActions(_)));
1849
1850                code_actions_indicator = view
1851                    .render_code_actions_indicator(&style, active, cx)
1852                    .map(|indicator| (newest_selection_head.row(), indicator));
1853            }
1854
1855            let visible_rows = start_row..start_row + line_layouts.len() as u32;
1856            hover = view.hover_state.render(&snapshot, &style, visible_rows, cx);
1857            mode = view.mode;
1858
1859            view.render_fold_indicators(
1860                folds,
1861                &style,
1862                view.gutter_hovered,
1863                line_height,
1864                gutter_margin,
1865                cx,
1866            )
1867        });
1868
1869        if let Some((_, context_menu)) = context_menu.as_mut() {
1870            context_menu.layout(
1871                SizeConstraint {
1872                    min: Vector2F::zero(),
1873                    max: vec2f(
1874                        cx.window_size.x() * 0.7,
1875                        (12. * line_height).min((size.y() - line_height) / 2.),
1876                    ),
1877                },
1878                cx,
1879            );
1880        }
1881
1882        if let Some((_, indicator)) = code_actions_indicator.as_mut() {
1883            indicator.layout(
1884                SizeConstraint::strict_along(
1885                    Axis::Vertical,
1886                    line_height * style.code_actions.vertical_scale,
1887                ),
1888                cx,
1889            );
1890        }
1891
1892        fold_indicators.as_mut().map(|fold_indicators| {
1893            for (_, indicator) in fold_indicators.iter_mut() {
1894                indicator.layout(
1895                    SizeConstraint::strict_along(
1896                        Axis::Vertical,
1897                        line_height * style.code_actions.vertical_scale,
1898                    ),
1899                    cx,
1900                );
1901            }
1902        });
1903
1904        if let Some((_, hover_popovers)) = hover.as_mut() {
1905            for hover_popover in hover_popovers.iter_mut() {
1906                hover_popover.layout(
1907                    SizeConstraint {
1908                        min: Vector2F::zero(),
1909                        max: vec2f(
1910                            (120. * em_width) // Default size
1911                                .min(size.x() / 2.) // Shrink to half of the editor width
1912                                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
1913                            (16. * line_height) // Default size
1914                                .min(size.y() / 2.) // Shrink to half of the editor height
1915                                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
1916                        ),
1917                    },
1918                    cx,
1919                );
1920            }
1921        }
1922
1923        (
1924            size,
1925            LayoutState {
1926                mode,
1927                position_map: Arc::new(PositionMap {
1928                    size,
1929                    scroll_max,
1930                    line_layouts,
1931                    line_height,
1932                    em_width,
1933                    em_advance,
1934                    snapshot,
1935                }),
1936                visible_display_row_range: start_row..end_row,
1937                gutter_size,
1938                gutter_padding,
1939                text_size,
1940                scrollbar_row_range,
1941                show_scrollbars,
1942                max_row,
1943                gutter_margin,
1944                active_rows,
1945                highlighted_rows,
1946                highlighted_ranges,
1947                click_ranges: Arc::new(click_ranges),
1948                line_number_layouts,
1949                display_hunks,
1950                blocks,
1951                selections,
1952                context_menu,
1953                code_actions_indicator,
1954                fold_indicators,
1955                hover_popovers: hover,
1956            },
1957        )
1958    }
1959
1960    fn paint(
1961        &mut self,
1962        bounds: RectF,
1963        visible_bounds: RectF,
1964        layout: &mut Self::LayoutState,
1965        cx: &mut PaintContext,
1966    ) -> Self::PaintState {
1967        let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
1968        cx.scene.push_layer(Some(visible_bounds));
1969
1970        let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
1971        let text_bounds = RectF::new(
1972            bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
1973            layout.text_size,
1974        );
1975
1976        Self::attach_mouse_handlers(
1977            &self.view,
1978            &layout.position_map,
1979            layout.click_ranges.clone(), // No need to clone the vec
1980            layout.hover_popovers.is_some(),
1981            visible_bounds,
1982            text_bounds,
1983            gutter_bounds,
1984            bounds,
1985            cx,
1986        );
1987
1988        self.paint_background(gutter_bounds, text_bounds, layout, cx);
1989        if layout.gutter_size.x() > 0. {
1990            self.paint_gutter(gutter_bounds, visible_bounds, layout, cx);
1991        }
1992        self.paint_text(text_bounds, visible_bounds, layout, cx);
1993
1994        cx.scene.push_layer(Some(bounds));
1995        if !layout.blocks.is_empty() {
1996            self.paint_blocks(bounds, visible_bounds, layout, cx);
1997        }
1998        self.paint_scrollbar(bounds, layout, cx);
1999        cx.scene.pop_layer();
2000
2001        cx.scene.pop_layer();
2002    }
2003
2004    fn rect_for_text_range(
2005        &self,
2006        range_utf16: Range<usize>,
2007        bounds: RectF,
2008        _: RectF,
2009        layout: &Self::LayoutState,
2010        _: &Self::PaintState,
2011        _: &gpui::MeasurementContext,
2012    ) -> Option<RectF> {
2013        let text_bounds = RectF::new(
2014            bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
2015            layout.text_size,
2016        );
2017        let content_origin = text_bounds.origin() + vec2f(layout.gutter_margin, 0.);
2018        let scroll_position = layout.position_map.snapshot.scroll_position();
2019        let start_row = scroll_position.y() as u32;
2020        let scroll_top = scroll_position.y() * layout.position_map.line_height;
2021        let scroll_left = scroll_position.x() * layout.position_map.em_width;
2022
2023        let range_start = OffsetUtf16(range_utf16.start)
2024            .to_display_point(&layout.position_map.snapshot.display_snapshot);
2025        if range_start.row() < start_row {
2026            return None;
2027        }
2028
2029        let line = layout
2030            .position_map
2031            .line_layouts
2032            .get((range_start.row() - start_row) as usize)?;
2033        let range_start_x = line.x_for_index(range_start.column() as usize);
2034        let range_start_y = range_start.row() as f32 * layout.position_map.line_height;
2035        Some(RectF::new(
2036            content_origin
2037                + vec2f(
2038                    range_start_x,
2039                    range_start_y + layout.position_map.line_height,
2040                )
2041                - vec2f(scroll_left, scroll_top),
2042            vec2f(
2043                layout.position_map.em_width,
2044                layout.position_map.line_height,
2045            ),
2046        ))
2047    }
2048
2049    fn debug(
2050        &self,
2051        bounds: RectF,
2052        _: &Self::LayoutState,
2053        _: &Self::PaintState,
2054        _: &gpui::DebugContext,
2055    ) -> json::Value {
2056        json!({
2057            "type": "BufferElement",
2058            "bounds": bounds.to_json()
2059        })
2060    }
2061}
2062
2063pub struct LayoutState {
2064    position_map: Arc<PositionMap>,
2065    gutter_size: Vector2F,
2066    gutter_padding: f32,
2067    gutter_margin: f32,
2068    text_size: Vector2F,
2069    mode: EditorMode,
2070    visible_display_row_range: Range<u32>,
2071    active_rows: BTreeMap<u32, bool>,
2072    highlighted_rows: Option<Range<u32>>,
2073    line_number_layouts: Vec<Option<text_layout::Line>>,
2074    display_hunks: Vec<DisplayDiffHunk>,
2075    blocks: Vec<BlockLayout>,
2076    highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
2077    click_ranges: Arc<Vec<(Range<DisplayPoint>, TextClickedCallback)>>,
2078    selections: Vec<(ReplicaId, Vec<SelectionLayout>)>,
2079    scrollbar_row_range: Range<f32>,
2080    show_scrollbars: bool,
2081    max_row: u32,
2082    context_menu: Option<(DisplayPoint, ElementBox)>,
2083    code_actions_indicator: Option<(u32, ElementBox)>,
2084    hover_popovers: Option<(DisplayPoint, Vec<ElementBox>)>,
2085    fold_indicators: Option<Vec<(u32, ElementBox)>>,
2086}
2087
2088pub struct PositionMap {
2089    size: Vector2F,
2090    line_height: f32,
2091    scroll_max: Vector2F,
2092    em_width: f32,
2093    em_advance: f32,
2094    line_layouts: Vec<text_layout::Line>,
2095    snapshot: EditorSnapshot,
2096}
2097
2098impl PositionMap {
2099    /// Returns two display points:
2100    /// 1. The nearest *valid* position in the editor
2101    /// 2. An unclipped, potentially *invalid* position that maps directly to
2102    ///    the given pixel position.
2103    fn point_for_position(
2104        &self,
2105        text_bounds: RectF,
2106        position: Vector2F,
2107    ) -> (DisplayPoint, DisplayPoint) {
2108        let scroll_position = self.snapshot.scroll_position();
2109        let position = position - text_bounds.origin();
2110        let y = position.y().max(0.0).min(self.size.y());
2111        let x = position.x() + (scroll_position.x() * self.em_width);
2112        let row = (y / self.line_height + scroll_position.y()) as u32;
2113        let (column, x_overshoot) = if let Some(line) = self
2114            .line_layouts
2115            .get(row as usize - scroll_position.y() as usize)
2116        {
2117            if let Some(ix) = line.index_for_x(x) {
2118                (ix as u32, 0.0)
2119            } else {
2120                (line.len() as u32, 0f32.max(x - line.width()))
2121            }
2122        } else {
2123            (0, x)
2124        };
2125
2126        let mut target_point = DisplayPoint::new(row, column);
2127        let point = self.snapshot.clip_point(target_point, Bias::Left);
2128        *target_point.column_mut() += (x_overshoot / self.em_advance) as u32;
2129
2130        (point, target_point)
2131    }
2132}
2133
2134struct BlockLayout {
2135    row: u32,
2136    element: ElementBox,
2137    style: BlockStyle,
2138}
2139
2140fn layout_line(
2141    row: u32,
2142    snapshot: &EditorSnapshot,
2143    style: &EditorStyle,
2144    layout_cache: &TextLayoutCache,
2145) -> text_layout::Line {
2146    let mut line = snapshot.line(row);
2147
2148    if line.len() > MAX_LINE_LEN {
2149        let mut len = MAX_LINE_LEN;
2150        while !line.is_char_boundary(len) {
2151            len -= 1;
2152        }
2153
2154        line.truncate(len);
2155    }
2156
2157    layout_cache.layout_str(
2158        &line,
2159        style.text.font_size,
2160        &[(
2161            snapshot.line_len(row) as usize,
2162            RunStyle {
2163                font_id: style.text.font_id,
2164                color: Color::black(),
2165                underline: Default::default(),
2166            },
2167        )],
2168    )
2169}
2170
2171#[derive(Debug)]
2172pub struct Cursor {
2173    origin: Vector2F,
2174    block_width: f32,
2175    line_height: f32,
2176    color: Color,
2177    shape: CursorShape,
2178    block_text: Option<Line>,
2179}
2180
2181impl Cursor {
2182    pub fn new(
2183        origin: Vector2F,
2184        block_width: f32,
2185        line_height: f32,
2186        color: Color,
2187        shape: CursorShape,
2188        block_text: Option<Line>,
2189    ) -> Cursor {
2190        Cursor {
2191            origin,
2192            block_width,
2193            line_height,
2194            color,
2195            shape,
2196            block_text,
2197        }
2198    }
2199
2200    pub fn bounding_rect(&self, origin: Vector2F) -> RectF {
2201        RectF::new(
2202            self.origin + origin,
2203            vec2f(self.block_width, self.line_height),
2204        )
2205    }
2206
2207    pub fn paint(&self, origin: Vector2F, cx: &mut PaintContext) {
2208        let bounds = match self.shape {
2209            CursorShape::Bar => RectF::new(self.origin + origin, vec2f(2.0, self.line_height)),
2210            CursorShape::Block | CursorShape::Hollow => RectF::new(
2211                self.origin + origin,
2212                vec2f(self.block_width, self.line_height),
2213            ),
2214            CursorShape::Underscore => RectF::new(
2215                self.origin + origin + Vector2F::new(0.0, self.line_height - 2.0),
2216                vec2f(self.block_width, 2.0),
2217            ),
2218        };
2219
2220        //Draw background or border quad
2221        if matches!(self.shape, CursorShape::Hollow) {
2222            cx.scene.push_quad(Quad {
2223                bounds,
2224                background: None,
2225                border: Border::all(1., self.color),
2226                corner_radius: 0.,
2227            });
2228        } else {
2229            cx.scene.push_quad(Quad {
2230                bounds,
2231                background: Some(self.color),
2232                border: Default::default(),
2233                corner_radius: 0.,
2234            });
2235        }
2236
2237        if let Some(block_text) = &self.block_text {
2238            block_text.paint(self.origin + origin, bounds, self.line_height, cx);
2239        }
2240    }
2241
2242    pub fn shape(&self) -> CursorShape {
2243        self.shape
2244    }
2245}
2246
2247#[derive(Debug)]
2248pub struct HighlightedRange {
2249    pub start_y: f32,
2250    pub line_height: f32,
2251    pub lines: Vec<HighlightedRangeLine>,
2252    pub color: Color,
2253    pub corner_radius: f32,
2254}
2255
2256#[derive(Debug)]
2257pub struct HighlightedRangeLine {
2258    pub start_x: f32,
2259    pub end_x: f32,
2260}
2261
2262impl HighlightedRange {
2263    pub fn paint(&self, bounds: RectF, scene: &mut SceneBuilder) {
2264        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
2265            self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
2266            self.paint_lines(
2267                self.start_y + self.line_height,
2268                &self.lines[1..],
2269                bounds,
2270                scene,
2271            );
2272        } else {
2273            self.paint_lines(self.start_y, &self.lines, bounds, scene);
2274        }
2275    }
2276
2277    fn paint_lines(
2278        &self,
2279        start_y: f32,
2280        lines: &[HighlightedRangeLine],
2281        bounds: RectF,
2282        scene: &mut SceneBuilder,
2283    ) {
2284        if lines.is_empty() {
2285            return;
2286        }
2287
2288        let mut path = PathBuilder::new();
2289        let first_line = lines.first().unwrap();
2290        let last_line = lines.last().unwrap();
2291
2292        let first_top_left = vec2f(first_line.start_x, start_y);
2293        let first_top_right = vec2f(first_line.end_x, start_y);
2294
2295        let curve_height = vec2f(0., self.corner_radius);
2296        let curve_width = |start_x: f32, end_x: f32| {
2297            let max = (end_x - start_x) / 2.;
2298            let width = if max < self.corner_radius {
2299                max
2300            } else {
2301                self.corner_radius
2302            };
2303
2304            vec2f(width, 0.)
2305        };
2306
2307        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
2308        path.reset(first_top_right - top_curve_width);
2309        path.curve_to(first_top_right + curve_height, first_top_right);
2310
2311        let mut iter = lines.iter().enumerate().peekable();
2312        while let Some((ix, line)) = iter.next() {
2313            let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
2314
2315            if let Some((_, next_line)) = iter.peek() {
2316                let next_top_right = vec2f(next_line.end_x, bottom_right.y());
2317
2318                match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
2319                    Ordering::Equal => {
2320                        path.line_to(bottom_right);
2321                    }
2322                    Ordering::Less => {
2323                        let curve_width = curve_width(next_top_right.x(), bottom_right.x());
2324                        path.line_to(bottom_right - curve_height);
2325                        if self.corner_radius > 0. {
2326                            path.curve_to(bottom_right - curve_width, bottom_right);
2327                        }
2328                        path.line_to(next_top_right + curve_width);
2329                        if self.corner_radius > 0. {
2330                            path.curve_to(next_top_right + curve_height, next_top_right);
2331                        }
2332                    }
2333                    Ordering::Greater => {
2334                        let curve_width = curve_width(bottom_right.x(), next_top_right.x());
2335                        path.line_to(bottom_right - curve_height);
2336                        if self.corner_radius > 0. {
2337                            path.curve_to(bottom_right + curve_width, bottom_right);
2338                        }
2339                        path.line_to(next_top_right - curve_width);
2340                        if self.corner_radius > 0. {
2341                            path.curve_to(next_top_right + curve_height, next_top_right);
2342                        }
2343                    }
2344                }
2345            } else {
2346                let curve_width = curve_width(line.start_x, line.end_x);
2347                path.line_to(bottom_right - curve_height);
2348                if self.corner_radius > 0. {
2349                    path.curve_to(bottom_right - curve_width, bottom_right);
2350                }
2351
2352                let bottom_left = vec2f(line.start_x, bottom_right.y());
2353                path.line_to(bottom_left + curve_width);
2354                if self.corner_radius > 0. {
2355                    path.curve_to(bottom_left - curve_height, bottom_left);
2356                }
2357            }
2358        }
2359
2360        if first_line.start_x > last_line.start_x {
2361            let curve_width = curve_width(last_line.start_x, first_line.start_x);
2362            let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
2363            path.line_to(second_top_left + curve_height);
2364            if self.corner_radius > 0. {
2365                path.curve_to(second_top_left + curve_width, second_top_left);
2366            }
2367            let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
2368            path.line_to(first_bottom_left - curve_width);
2369            if self.corner_radius > 0. {
2370                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
2371            }
2372        }
2373
2374        path.line_to(first_top_left + curve_height);
2375        if self.corner_radius > 0. {
2376            path.curve_to(first_top_left + top_curve_width, first_top_left);
2377        }
2378        path.line_to(first_top_right - top_curve_width);
2379
2380        scene.push_path(path.build(self.color, Some(bounds)));
2381    }
2382}
2383
2384pub trait ClickRange: 'static {
2385    fn click_handler(
2386        click: &MouseClick,
2387        range: &Range<DisplayPoint>,
2388        snapshot: &EditorSnapshot,
2389        cx: &mut EventContext,
2390    );
2391}
2392
2393pub enum FoldMarker {}
2394impl ClickRange for FoldMarker {
2395    fn click_handler(
2396        _click: &MouseClick,
2397        range: &Range<DisplayPoint>,
2398        _snapshot: &EditorSnapshot,
2399        cx: &mut EventContext,
2400    ) {
2401        cx.dispatch_action(UnfoldAt {
2402            display_row: DisplayRow(range.start.row()),
2403        })
2404    }
2405}
2406
2407pub fn position_to_display_point(
2408    position: Vector2F,
2409    text_bounds: RectF,
2410    position_map: &PositionMap,
2411) -> Option<DisplayPoint> {
2412    if text_bounds.contains_point(position) {
2413        let (point, target_point) = position_map.point_for_position(text_bounds, position);
2414        if point == target_point {
2415            Some(point)
2416        } else {
2417            None
2418        }
2419    } else {
2420        None
2421    }
2422}
2423
2424pub fn range_to_bounds(
2425    range: &Range<DisplayPoint>,
2426    content_origin: Vector2F,
2427    scroll_left: f32,
2428    scroll_top: f32,
2429    visible_row_range: &Range<u32>,
2430    line_end_overshoot: f32,
2431    position_map: &PositionMap,
2432) -> impl Iterator<Item = RectF> {
2433    let mut bounds: SmallVec<[RectF; 1]> = SmallVec::new();
2434
2435    if range.start == range.end {
2436        return bounds.into_iter();
2437    }
2438
2439    let start_row = visible_row_range.start;
2440    let end_row = visible_row_range.end;
2441
2442    let row_range = if range.end.column() == 0 {
2443        cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
2444    } else {
2445        cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
2446    };
2447
2448    let first_y =
2449        content_origin.y() + row_range.start as f32 * position_map.line_height - scroll_top;
2450
2451    for (idx, row) in row_range.enumerate() {
2452        let line_layout = &position_map.line_layouts[(row - start_row) as usize];
2453
2454        let start_x = if row == range.start.row() {
2455            content_origin.x() + line_layout.x_for_index(range.start.column() as usize)
2456                - scroll_left
2457        } else {
2458            content_origin.x() - scroll_left
2459        };
2460
2461        let end_x = if row == range.end.row() {
2462            content_origin.x() + line_layout.x_for_index(range.end.column() as usize) - scroll_left
2463        } else {
2464            content_origin.x() + line_layout.width() + line_end_overshoot - scroll_left
2465        };
2466
2467        bounds.push(RectF::from_points(
2468            vec2f(start_x, first_y + position_map.line_height * idx as f32),
2469            vec2f(end_x, first_y + position_map.line_height * (idx + 1) as f32),
2470        ))
2471    }
2472
2473    bounds.into_iter()
2474}
2475
2476pub fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
2477    delta.powf(1.5) / 100.0
2478}
2479
2480fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
2481    delta.powf(1.2) / 300.0
2482}
2483
2484#[cfg(test)]
2485mod tests {
2486    use std::sync::Arc;
2487
2488    use super::*;
2489    use crate::{
2490        display_map::{BlockDisposition, BlockProperties},
2491        Editor, MultiBuffer,
2492    };
2493    use settings::Settings;
2494    use util::test::sample_text;
2495
2496    #[gpui::test]
2497    fn test_layout_line_numbers(cx: &mut gpui::MutableAppContext) {
2498        cx.set_global(Settings::test(cx));
2499        let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
2500        let (window_id, editor) = cx.add_window(Default::default(), |cx| {
2501            Editor::new(EditorMode::Full, buffer, None, None, cx)
2502        });
2503        let element = EditorElement::new(editor.downgrade(), editor.read(cx).style(cx));
2504
2505        let layouts = editor.update(cx, |editor, cx| {
2506            let snapshot = editor.snapshot(cx);
2507            let mut presenter = cx.build_presenter(window_id, 30., Default::default());
2508            let layout_cx = presenter.build_layout_context(Vector2F::zero(), false, cx);
2509            element.layout_line_numbers(0..6, &Default::default(), &snapshot, &layout_cx)
2510        });
2511        assert_eq!(layouts.len(), 6);
2512    }
2513
2514    #[gpui::test]
2515    fn test_layout_with_placeholder_text_and_blocks(cx: &mut gpui::MutableAppContext) {
2516        cx.set_global(Settings::test(cx));
2517        let buffer = MultiBuffer::build_simple("", cx);
2518        let (window_id, editor) = cx.add_window(Default::default(), |cx| {
2519            Editor::new(EditorMode::Full, buffer, None, None, cx)
2520        });
2521
2522        editor.update(cx, |editor, cx| {
2523            editor.set_placeholder_text("hello", cx);
2524            editor.insert_blocks(
2525                [BlockProperties {
2526                    style: BlockStyle::Fixed,
2527                    disposition: BlockDisposition::Above,
2528                    height: 3,
2529                    position: Anchor::min(),
2530                    render: Arc::new(|_| Empty::new().boxed()),
2531                }],
2532                cx,
2533            );
2534
2535            // Blur the editor so that it displays placeholder text.
2536            cx.blur();
2537        });
2538
2539        let mut element = EditorElement::new(editor.downgrade(), editor.read(cx).style(cx));
2540
2541        let mut scene = SceneBuilder::new(1.0);
2542        let mut presenter = cx.build_presenter(window_id, 30., Default::default());
2543        let mut layout_cx = presenter.build_layout_context(Vector2F::zero(), false, cx);
2544        let (size, mut state) = element.layout(
2545            SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
2546            &mut layout_cx,
2547        );
2548
2549        assert_eq!(state.position_map.line_layouts.len(), 4);
2550        assert_eq!(
2551            state
2552                .line_number_layouts
2553                .iter()
2554                .map(Option::is_some)
2555                .collect::<Vec<_>>(),
2556            &[false, false, false, true]
2557        );
2558
2559        // Don't panic.
2560        let bounds = RectF::new(Default::default(), size);
2561        let mut paint_cx = presenter.build_paint_context(&mut scene, bounds.size(), cx);
2562        element.paint(bounds, bounds, &mut state, &mut paint_cx);
2563    }
2564}