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