element.rs

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