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