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