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        CmdShiftChanged, 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, Event, EventContext,
  33    LayoutContext, ModifiersChangedEvent, MouseButton, MouseButtonEvent, MouseMovedEvent,
  34    MouseRegion, MutableAppContext, PaintContext, Quad, Scene, SizeConstraint, ViewContext,
  35    WeakViewHandle,
  36};
  37use json::json;
  38use language::{Bias, CursorShape, DiagnosticSeverity, OffsetUtf16, Point, Selection};
  39use project::ProjectPath;
  40use settings::{GitGutter, Settings};
  41use smallvec::SmallVec;
  42use std::{
  43    cmp::{self, Ordering},
  44    fmt::Write,
  45    iter,
  46    ops::{DerefMut, Range},
  47    sync::Arc,
  48};
  49
  50#[derive(Debug)]
  51struct DiffHunkLayout {
  52    visual_range: Range<u32>,
  53    status: DiffHunkStatus,
  54    is_folded: bool,
  55}
  56
  57struct SelectionLayout {
  58    head: DisplayPoint,
  59    cursor_shape: CursorShape,
  60    range: Range<DisplayPoint>,
  61}
  62
  63impl SelectionLayout {
  64    fn new<T: ToPoint + ToDisplayPoint + Clone>(
  65        selection: Selection<T>,
  66        line_mode: bool,
  67        cursor_shape: CursorShape,
  68        map: &DisplaySnapshot,
  69    ) -> Self {
  70        if line_mode {
  71            let selection = selection.map(|p| p.to_point(&map.buffer_snapshot));
  72            let point_range = map.expand_to_line(selection.range());
  73            Self {
  74                head: selection.head().to_display_point(map),
  75                cursor_shape,
  76                range: point_range.start.to_display_point(map)
  77                    ..point_range.end.to_display_point(map),
  78            }
  79        } else {
  80            let selection = selection.map(|p| p.to_display_point(map));
  81            Self {
  82                head: selection.head(),
  83                cursor_shape,
  84                range: selection.range(),
  85            }
  86        }
  87    }
  88}
  89
  90#[derive(Clone)]
  91pub struct EditorElement {
  92    view: WeakViewHandle<Editor>,
  93    style: Arc<EditorStyle>,
  94}
  95
  96impl EditorElement {
  97    pub fn new(view: WeakViewHandle<Editor>, style: EditorStyle) -> Self {
  98        Self {
  99            view,
 100            style: Arc::new(style),
 101        }
 102    }
 103
 104    fn view<'a>(&self, cx: &'a AppContext) -> &'a Editor {
 105        self.view.upgrade(cx).unwrap().read(cx)
 106    }
 107
 108    fn update_view<F, T>(&self, cx: &mut MutableAppContext, f: F) -> T
 109    where
 110        F: FnOnce(&mut Editor, &mut ViewContext<Editor>) -> T,
 111    {
 112        self.view.upgrade(cx).unwrap().update(cx, f)
 113    }
 114
 115    fn snapshot(&self, cx: &mut MutableAppContext) -> EditorSnapshot {
 116        self.update_view(cx, |view, cx| view.snapshot(cx))
 117    }
 118
 119    fn attach_mouse_handlers(
 120        view: &WeakViewHandle<Editor>,
 121        position_map: &Arc<PositionMap>,
 122        visible_bounds: RectF,
 123        text_bounds: RectF,
 124        gutter_bounds: RectF,
 125        bounds: RectF,
 126        cx: &mut PaintContext,
 127    ) {
 128        enum EditorElementMouseHandlers {}
 129        cx.scene.push_mouse_region(
 130            MouseRegion::new::<EditorElementMouseHandlers>(view.id(), view.id(), visible_bounds)
 131                .on_down(MouseButton::Left, {
 132                    let position_map = position_map.clone();
 133                    move |e, cx| {
 134                        if !Self::mouse_down(
 135                            e.platform_event,
 136                            position_map.as_ref(),
 137                            text_bounds,
 138                            gutter_bounds,
 139                            cx,
 140                        ) {
 141                            cx.propogate_event();
 142                        }
 143                    }
 144                })
 145                .on_down(MouseButton::Right, {
 146                    let position_map = position_map.clone();
 147                    move |e, cx| {
 148                        if !Self::mouse_right_down(
 149                            e.position,
 150                            position_map.as_ref(),
 151                            text_bounds,
 152                            cx,
 153                        ) {
 154                            cx.propogate_event();
 155                        }
 156                    }
 157                })
 158                .on_up(MouseButton::Left, {
 159                    let view = view.clone();
 160                    let position_map = position_map.clone();
 161                    move |e, cx| {
 162                        if !Self::mouse_up(
 163                            view.clone(),
 164                            e.position,
 165                            e.cmd,
 166                            e.shift,
 167                            position_map.as_ref(),
 168                            text_bounds,
 169                            cx,
 170                        ) {
 171                            cx.propogate_event()
 172                        }
 173                    }
 174                })
 175                .on_drag(MouseButton::Left, {
 176                    let view = view.clone();
 177                    let position_map = position_map.clone();
 178                    move |e, cx| {
 179                        if !Self::mouse_dragged(
 180                            view.clone(),
 181                            e.platform_event,
 182                            position_map.as_ref(),
 183                            text_bounds,
 184                            cx,
 185                        ) {
 186                            cx.propogate_event()
 187                        }
 188                    }
 189                })
 190                .on_move({
 191                    let position_map = position_map.clone();
 192                    move |e, cx| {
 193                        if !Self::mouse_moved(e.platform_event, &position_map, text_bounds, cx) {
 194                            cx.propogate_event()
 195                        }
 196                    }
 197                })
 198                .on_scroll({
 199                    let position_map = position_map.clone();
 200                    move |e, cx| {
 201                        if !Self::scroll(e.position, e.delta, e.precise, &position_map, bounds, cx)
 202                        {
 203                            cx.propogate_event()
 204                        }
 205                    }
 206                }),
 207        );
 208    }
 209
 210    fn mouse_down(
 211        MouseButtonEvent {
 212            position,
 213            ctrl,
 214            alt,
 215            shift,
 216            cmd,
 217            mut click_count,
 218            ..
 219        }: MouseButtonEvent,
 220        position_map: &PositionMap,
 221        text_bounds: RectF,
 222        gutter_bounds: RectF,
 223        cx: &mut EventContext,
 224    ) -> bool {
 225        if gutter_bounds.contains_point(position) {
 226            click_count = 3; // Simulate triple-click when clicking the gutter to select lines
 227        } else if !text_bounds.contains_point(position) {
 228            return false;
 229        }
 230
 231        let (position, target_position) = position_map.point_for_position(text_bounds, position);
 232
 233        if shift && alt {
 234            cx.dispatch_action(Select(SelectPhase::BeginColumnar {
 235                position,
 236                goal_column: target_position.column(),
 237            }));
 238        } else if shift && !ctrl && !alt && !cmd {
 239            cx.dispatch_action(Select(SelectPhase::Extend {
 240                position,
 241                click_count,
 242            }));
 243        } else {
 244            cx.dispatch_action(Select(SelectPhase::Begin {
 245                position,
 246                add: alt,
 247                click_count,
 248            }));
 249        }
 250
 251        true
 252    }
 253
 254    fn mouse_right_down(
 255        position: Vector2F,
 256        position_map: &PositionMap,
 257        text_bounds: RectF,
 258        cx: &mut EventContext,
 259    ) -> bool {
 260        if !text_bounds.contains_point(position) {
 261            return false;
 262        }
 263
 264        let (point, _) = position_map.point_for_position(text_bounds, position);
 265
 266        cx.dispatch_action(DeployMouseContextMenu { position, point });
 267        true
 268    }
 269
 270    fn mouse_up(
 271        view: WeakViewHandle<Editor>,
 272        position: Vector2F,
 273        cmd: bool,
 274        shift: bool,
 275        position_map: &PositionMap,
 276        text_bounds: RectF,
 277        cx: &mut EventContext,
 278    ) -> bool {
 279        let view = view.upgrade(cx.app).unwrap().read(cx.app);
 280        let end_selection = view.has_pending_selection();
 281        let pending_nonempty_selections = view.has_pending_nonempty_selection();
 282
 283        if end_selection {
 284            cx.dispatch_action(Select(SelectPhase::End));
 285        }
 286
 287        if !pending_nonempty_selections && cmd && text_bounds.contains_point(position) {
 288            let (point, target_point) = position_map.point_for_position(text_bounds, position);
 289
 290            if point == target_point {
 291                if shift {
 292                    cx.dispatch_action(GoToFetchedTypeDefinition { point });
 293                } else {
 294                    cx.dispatch_action(GoToFetchedDefinition { point });
 295                }
 296
 297                return true;
 298            }
 299        }
 300
 301        end_selection
 302    }
 303
 304    fn mouse_dragged(
 305        view: WeakViewHandle<Editor>,
 306        MouseMovedEvent {
 307            cmd,
 308            shift,
 309            position,
 310            ..
 311        }: MouseMovedEvent,
 312        position_map: &PositionMap,
 313        text_bounds: RectF,
 314        cx: &mut EventContext,
 315    ) -> bool {
 316        // This will be handled more correctly once https://github.com/zed-industries/zed/issues/1218 is completed
 317        // Don't trigger hover popover if mouse is hovering over context menu
 318        let point = if text_bounds.contains_point(position) {
 319            let (point, target_point) = position_map.point_for_position(text_bounds, position);
 320            if point == target_point {
 321                Some(point)
 322            } else {
 323                None
 324            }
 325        } else {
 326            None
 327        };
 328
 329        cx.dispatch_action(UpdateGoToDefinitionLink {
 330            point,
 331            cmd_held: cmd,
 332            shift_held: shift,
 333        });
 334
 335        let view = view.upgrade(cx.app).unwrap().read(cx.app);
 336        if view.has_pending_selection() {
 337            let mut scroll_delta = Vector2F::zero();
 338
 339            let vertical_margin = position_map.line_height.min(text_bounds.height() / 3.0);
 340            let top = text_bounds.origin_y() + vertical_margin;
 341            let bottom = text_bounds.lower_left().y() - vertical_margin;
 342            if position.y() < top {
 343                scroll_delta.set_y(-scale_vertical_mouse_autoscroll_delta(top - position.y()))
 344            }
 345            if position.y() > bottom {
 346                scroll_delta.set_y(scale_vertical_mouse_autoscroll_delta(position.y() - bottom))
 347            }
 348
 349            let horizontal_margin = position_map.line_height.min(text_bounds.width() / 3.0);
 350            let left = text_bounds.origin_x() + horizontal_margin;
 351            let right = text_bounds.upper_right().x() - horizontal_margin;
 352            if position.x() < left {
 353                scroll_delta.set_x(-scale_horizontal_mouse_autoscroll_delta(
 354                    left - position.x(),
 355                ))
 356            }
 357            if position.x() > right {
 358                scroll_delta.set_x(scale_horizontal_mouse_autoscroll_delta(
 359                    position.x() - right,
 360                ))
 361            }
 362
 363            let (position, target_position) =
 364                position_map.point_for_position(text_bounds, position);
 365
 366            cx.dispatch_action(Select(SelectPhase::Update {
 367                position,
 368                goal_column: target_position.column(),
 369                scroll_position: (position_map.snapshot.scroll_position() + scroll_delta)
 370                    .clamp(Vector2F::zero(), position_map.scroll_max),
 371            }));
 372
 373            cx.dispatch_action(HoverAt { point });
 374            true
 375        } else {
 376            cx.dispatch_action(HoverAt { point });
 377            false
 378        }
 379    }
 380
 381    fn mouse_moved(
 382        MouseMovedEvent {
 383            cmd,
 384            shift,
 385            position,
 386            ..
 387        }: MouseMovedEvent,
 388        position_map: &PositionMap,
 389        text_bounds: RectF,
 390        cx: &mut EventContext,
 391    ) -> bool {
 392        // This will be handled more correctly once https://github.com/zed-industries/zed/issues/1218 is completed
 393        // Don't trigger hover popover if mouse is hovering over context menu
 394        let point = if text_bounds.contains_point(position) {
 395            let (point, target_point) = position_map.point_for_position(text_bounds, position);
 396            if point == target_point {
 397                Some(point)
 398            } else {
 399                None
 400            }
 401        } else {
 402            None
 403        };
 404
 405        cx.dispatch_action(UpdateGoToDefinitionLink {
 406            point,
 407            cmd_held: cmd,
 408            shift_held: shift,
 409        });
 410
 411        cx.dispatch_action(HoverAt { point });
 412        true
 413    }
 414
 415    fn modifiers_changed(&self, event: ModifiersChangedEvent, cx: &mut EventContext) -> bool {
 416        cx.dispatch_action(CmdShiftChanged {
 417            cmd_down: event.cmd,
 418            shift_down: event.shift,
 419        });
 420        false
 421    }
 422
 423    fn scroll(
 424        position: Vector2F,
 425        mut delta: Vector2F,
 426        precise: bool,
 427        position_map: &PositionMap,
 428        bounds: RectF,
 429        cx: &mut EventContext,
 430    ) -> bool {
 431        if !bounds.contains_point(position) {
 432            return false;
 433        }
 434
 435        let max_glyph_width = position_map.em_width;
 436        if !precise {
 437            delta *= vec2f(max_glyph_width, position_map.line_height);
 438        }
 439
 440        let scroll_position = position_map.snapshot.scroll_position();
 441        let x = (scroll_position.x() * max_glyph_width - delta.x()) / max_glyph_width;
 442        let y =
 443            (scroll_position.y() * position_map.line_height - delta.y()) / position_map.line_height;
 444        let scroll_position = vec2f(x, y).clamp(Vector2F::zero(), position_map.scroll_max);
 445
 446        cx.dispatch_action(Scroll(scroll_position));
 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        cx: &mut LayoutContext,
1328    ) -> (f32, Vec<BlockLayout>) {
1329        let editor = if let Some(editor) = self.view.upgrade(cx) {
1330            editor
1331        } else {
1332            return Default::default();
1333        };
1334
1335        let tooltip_style = cx.global::<Settings>().theme.tooltip.clone();
1336        let scroll_x = snapshot.scroll_position.x();
1337        let (fixed_blocks, non_fixed_blocks) = snapshot
1338            .blocks_in_range(rows.clone())
1339            .partition::<Vec<_>, _>(|(_, block)| match block {
1340                TransformBlock::ExcerptHeader { .. } => false,
1341                TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
1342            });
1343        let mut render_block = |block: &TransformBlock, width: f32| {
1344            let mut element = match block {
1345                TransformBlock::Custom(block) => {
1346                    let align_to = block
1347                        .position()
1348                        .to_point(&snapshot.buffer_snapshot)
1349                        .to_display_point(snapshot);
1350                    let anchor_x = text_x
1351                        + if rows.contains(&align_to.row()) {
1352                            line_layouts[(align_to.row() - rows.start) as usize]
1353                                .x_for_index(align_to.column() as usize)
1354                        } else {
1355                            layout_line(align_to.row(), snapshot, style, cx.text_layout_cache)
1356                                .x_for_index(align_to.column() as usize)
1357                        };
1358
1359                    cx.render(&editor, |_, cx| {
1360                        block.render(&mut BlockContext {
1361                            cx,
1362                            anchor_x,
1363                            gutter_padding,
1364                            line_height,
1365                            scroll_x,
1366                            gutter_width,
1367                            em_width,
1368                        })
1369                    })
1370                }
1371                TransformBlock::ExcerptHeader {
1372                    key,
1373                    buffer,
1374                    range,
1375                    starts_new_buffer,
1376                    ..
1377                } => {
1378                    let jump_icon = project::File::from_dyn(buffer.file()).map(|file| {
1379                        let jump_position = range
1380                            .primary
1381                            .as_ref()
1382                            .map_or(range.context.start, |primary| primary.start);
1383                        let jump_action = crate::Jump {
1384                            path: ProjectPath {
1385                                worktree_id: file.worktree_id(cx),
1386                                path: file.path.clone(),
1387                            },
1388                            position: language::ToPoint::to_point(&jump_position, buffer),
1389                            anchor: jump_position,
1390                        };
1391
1392                        enum JumpIcon {}
1393                        cx.render(&editor, |_, cx| {
1394                            MouseEventHandler::<JumpIcon>::new(*key, cx, |state, _| {
1395                                let style = style.jump_icon.style_for(state, false);
1396                                Svg::new("icons/arrow_up_right_8.svg")
1397                                    .with_color(style.color)
1398                                    .constrained()
1399                                    .with_width(style.icon_width)
1400                                    .aligned()
1401                                    .contained()
1402                                    .with_style(style.container)
1403                                    .constrained()
1404                                    .with_width(style.button_width)
1405                                    .with_height(style.button_width)
1406                                    .boxed()
1407                            })
1408                            .with_cursor_style(CursorStyle::PointingHand)
1409                            .on_click(MouseButton::Left, move |_, cx| {
1410                                cx.dispatch_action(jump_action.clone())
1411                            })
1412                            .with_tooltip::<JumpIcon, _>(
1413                                *key,
1414                                "Jump to Buffer".to_string(),
1415                                Some(Box::new(crate::OpenExcerpts)),
1416                                tooltip_style.clone(),
1417                                cx,
1418                            )
1419                            .aligned()
1420                            .flex_float()
1421                            .boxed()
1422                        })
1423                    });
1424
1425                    if *starts_new_buffer {
1426                        let style = &self.style.diagnostic_path_header;
1427                        let font_size =
1428                            (style.text_scale_factor * self.style.text.font_size).round();
1429
1430                        let mut filename = None;
1431                        let mut parent_path = None;
1432                        if let Some(file) = buffer.file() {
1433                            let path = file.path();
1434                            filename = path.file_name().map(|f| f.to_string_lossy().to_string());
1435                            parent_path =
1436                                path.parent().map(|p| p.to_string_lossy().to_string() + "/");
1437                        }
1438
1439                        Flex::row()
1440                            .with_child(
1441                                Label::new(
1442                                    filename.unwrap_or_else(|| "untitled".to_string()),
1443                                    style.filename.text.clone().with_font_size(font_size),
1444                                )
1445                                .contained()
1446                                .with_style(style.filename.container)
1447                                .aligned()
1448                                .boxed(),
1449                            )
1450                            .with_children(parent_path.map(|path| {
1451                                Label::new(path, style.path.text.clone().with_font_size(font_size))
1452                                    .contained()
1453                                    .with_style(style.path.container)
1454                                    .aligned()
1455                                    .boxed()
1456                            }))
1457                            .with_children(jump_icon)
1458                            .contained()
1459                            .with_style(style.container)
1460                            .with_padding_left(gutter_padding)
1461                            .with_padding_right(gutter_padding)
1462                            .expanded()
1463                            .named("path header block")
1464                    } else {
1465                        let text_style = self.style.text.clone();
1466                        Flex::row()
1467                            .with_child(Label::new("".to_string(), text_style).boxed())
1468                            .with_children(jump_icon)
1469                            .contained()
1470                            .with_padding_left(gutter_padding)
1471                            .with_padding_right(gutter_padding)
1472                            .expanded()
1473                            .named("collapsed context")
1474                    }
1475                }
1476            };
1477
1478            element.layout(
1479                SizeConstraint {
1480                    min: Vector2F::zero(),
1481                    max: vec2f(width, block.height() as f32 * line_height),
1482                },
1483                cx,
1484            );
1485            element
1486        };
1487
1488        let mut fixed_block_max_width = 0f32;
1489        let mut blocks = Vec::new();
1490        for (row, block) in fixed_blocks {
1491            let element = render_block(block, f32::INFINITY);
1492            fixed_block_max_width = fixed_block_max_width.max(element.size().x() + em_width);
1493            blocks.push(BlockLayout {
1494                row,
1495                element,
1496                style: BlockStyle::Fixed,
1497            });
1498        }
1499        for (row, block) in non_fixed_blocks {
1500            let style = match block {
1501                TransformBlock::Custom(block) => block.style(),
1502                TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
1503            };
1504            let width = match style {
1505                BlockStyle::Sticky => editor_width,
1506                BlockStyle::Flex => editor_width
1507                    .max(fixed_block_max_width)
1508                    .max(gutter_width + scroll_width),
1509                BlockStyle::Fixed => unreachable!(),
1510            };
1511            let element = render_block(block, width);
1512            blocks.push(BlockLayout {
1513                row,
1514                element,
1515                style,
1516            });
1517        }
1518        (
1519            scroll_width.max(fixed_block_max_width - gutter_width),
1520            blocks,
1521        )
1522    }
1523}
1524
1525impl Element for EditorElement {
1526    type LayoutState = LayoutState;
1527    type PaintState = ();
1528
1529    fn layout(
1530        &mut self,
1531        constraint: SizeConstraint,
1532        cx: &mut LayoutContext,
1533    ) -> (Vector2F, Self::LayoutState) {
1534        let mut size = constraint.max;
1535        if size.x().is_infinite() {
1536            unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
1537        }
1538
1539        let snapshot = self.snapshot(cx.app);
1540        let style = self.style.clone();
1541        let line_height = style.text.line_height(cx.font_cache);
1542
1543        let gutter_padding;
1544        let gutter_width;
1545        let gutter_margin;
1546        if snapshot.mode == EditorMode::Full {
1547            gutter_padding = style.text.em_width(cx.font_cache) * style.gutter_padding_factor;
1548            gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
1549            gutter_margin = -style.text.descent(cx.font_cache);
1550        } else {
1551            gutter_padding = 0.0;
1552            gutter_width = 0.0;
1553            gutter_margin = 0.0;
1554        };
1555
1556        let text_width = size.x() - gutter_width;
1557        let em_width = style.text.em_width(cx.font_cache);
1558        let em_advance = style.text.em_advance(cx.font_cache);
1559        let overscroll = vec2f(em_width, 0.);
1560        let snapshot = self.update_view(cx.app, |view, cx| {
1561            view.set_visible_line_count(size.y() / line_height);
1562
1563            let wrap_width = match view.soft_wrap_mode(cx) {
1564                SoftWrap::None => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
1565                SoftWrap::EditorWidth => {
1566                    Some(text_width - gutter_margin - overscroll.x() - em_width)
1567                }
1568                SoftWrap::Column(column) => Some(column as f32 * em_advance),
1569            };
1570
1571            if view.set_wrap_width(wrap_width, cx) {
1572                view.snapshot(cx)
1573            } else {
1574                snapshot
1575            }
1576        });
1577
1578        let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
1579        if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
1580            size.set_y(
1581                scroll_height
1582                    .min(constraint.max_along(Axis::Vertical))
1583                    .max(constraint.min_along(Axis::Vertical))
1584                    .min(line_height * max_lines as f32),
1585            )
1586        } else if let EditorMode::SingleLine = snapshot.mode {
1587            size.set_y(
1588                line_height
1589                    .min(constraint.max_along(Axis::Vertical))
1590                    .max(constraint.min_along(Axis::Vertical)),
1591            )
1592        } else if size.y().is_infinite() {
1593            size.set_y(scroll_height);
1594        }
1595        let gutter_size = vec2f(gutter_width, size.y());
1596        let text_size = vec2f(text_width, size.y());
1597
1598        let (autoscroll_horizontally, mut snapshot) = self.update_view(cx.app, |view, cx| {
1599            let autoscroll_horizontally = view.autoscroll_vertically(size.y(), line_height, cx);
1600            let snapshot = view.snapshot(cx);
1601            (autoscroll_horizontally, snapshot)
1602        });
1603
1604        let scroll_position = snapshot.scroll_position();
1605        // The scroll position is a fractional point, the whole number of which represents
1606        // the top of the window in terms of display rows.
1607        let start_row = scroll_position.y() as u32;
1608        let height_in_lines = size.y() / line_height;
1609        let max_row = snapshot.max_point().row();
1610
1611        // Add 1 to ensure selections bleed off screen
1612        let end_row = 1 + cmp::min(
1613            (scroll_position.y() + height_in_lines).ceil() as u32,
1614            max_row,
1615        );
1616
1617        let start_anchor = if start_row == 0 {
1618            Anchor::min()
1619        } else {
1620            snapshot
1621                .buffer_snapshot
1622                .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
1623        };
1624        let end_anchor = if end_row > max_row {
1625            Anchor::max()
1626        } else {
1627            snapshot
1628                .buffer_snapshot
1629                .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
1630        };
1631
1632        let mut selections: Vec<(ReplicaId, Vec<SelectionLayout>)> = Vec::new();
1633        let mut active_rows = BTreeMap::new();
1634        let mut highlighted_rows = None;
1635        let mut highlighted_ranges = Vec::new();
1636        let mut show_scrollbars = false;
1637        self.update_view(cx.app, |view, cx| {
1638            let display_map = view.display_map.update(cx, |map, cx| map.snapshot(cx));
1639
1640            highlighted_rows = view.highlighted_rows();
1641            let theme = cx.global::<Settings>().theme.as_ref();
1642            highlighted_ranges = view.background_highlights_in_range(
1643                start_anchor.clone()..end_anchor.clone(),
1644                &display_map,
1645                theme,
1646            );
1647
1648            let mut remote_selections = HashMap::default();
1649            for (replica_id, line_mode, cursor_shape, selection) in display_map
1650                .buffer_snapshot
1651                .remote_selections_in_range(&(start_anchor.clone()..end_anchor.clone()))
1652            {
1653                // The local selections match the leader's selections.
1654                if Some(replica_id) == view.leader_replica_id {
1655                    continue;
1656                }
1657                remote_selections
1658                    .entry(replica_id)
1659                    .or_insert(Vec::new())
1660                    .push(SelectionLayout::new(
1661                        selection,
1662                        line_mode,
1663                        cursor_shape,
1664                        &display_map,
1665                    ));
1666            }
1667            selections.extend(remote_selections);
1668
1669            if view.show_local_selections {
1670                let mut local_selections = view
1671                    .selections
1672                    .disjoint_in_range(start_anchor..end_anchor, cx);
1673                local_selections.extend(view.selections.pending(cx));
1674                for selection in &local_selections {
1675                    let is_empty = selection.start == selection.end;
1676                    let selection_start = snapshot.prev_line_boundary(selection.start).1;
1677                    let selection_end = snapshot.next_line_boundary(selection.end).1;
1678                    for row in cmp::max(selection_start.row(), start_row)
1679                        ..=cmp::min(selection_end.row(), end_row)
1680                    {
1681                        let contains_non_empty_selection =
1682                            active_rows.entry(row).or_insert(!is_empty);
1683                        *contains_non_empty_selection |= !is_empty;
1684                    }
1685                }
1686
1687                // Render the local selections in the leader's color when following.
1688                let local_replica_id = view
1689                    .leader_replica_id
1690                    .unwrap_or_else(|| view.replica_id(cx));
1691
1692                selections.push((
1693                    local_replica_id,
1694                    local_selections
1695                        .into_iter()
1696                        .map(|selection| {
1697                            SelectionLayout::new(
1698                                selection,
1699                                view.selections.line_mode,
1700                                view.cursor_shape,
1701                                &display_map,
1702                            )
1703                        })
1704                        .collect(),
1705                ));
1706            }
1707
1708            show_scrollbars = view.show_scrollbars();
1709        });
1710
1711        let line_number_layouts =
1712            self.layout_line_numbers(start_row..end_row, &active_rows, &snapshot, cx);
1713
1714        let hunk_layouts = self.layout_git_gutters(start_row..end_row, &snapshot);
1715
1716        let scrollbar_row_range = scroll_position.y()..(scroll_position.y() + height_in_lines);
1717
1718        let mut max_visible_line_width = 0.0;
1719        let line_layouts = self.layout_lines(start_row..end_row, &snapshot, cx);
1720        for line in &line_layouts {
1721            if line.width() > max_visible_line_width {
1722                max_visible_line_width = line.width();
1723            }
1724        }
1725
1726        let style = self.style.clone();
1727        let longest_line_width = layout_line(
1728            snapshot.longest_row(),
1729            &snapshot,
1730            &style,
1731            cx.text_layout_cache,
1732        )
1733        .width();
1734        let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
1735        let em_width = style.text.em_width(cx.font_cache);
1736        let (scroll_width, blocks) = self.layout_blocks(
1737            start_row..end_row,
1738            &snapshot,
1739            size.x(),
1740            scroll_width,
1741            gutter_padding,
1742            gutter_width,
1743            em_width,
1744            gutter_width + gutter_margin,
1745            line_height,
1746            &style,
1747            &line_layouts,
1748            cx,
1749        );
1750
1751        let scroll_max = vec2f(
1752            ((scroll_width - text_size.x()) / em_width).max(0.0),
1753            max_row as f32,
1754        );
1755
1756        self.update_view(cx.app, |view, cx| {
1757            let clamped = view.clamp_scroll_left(scroll_max.x());
1758
1759            let autoscrolled = if autoscroll_horizontally {
1760                view.autoscroll_horizontally(
1761                    start_row,
1762                    text_size.x(),
1763                    scroll_width,
1764                    em_width,
1765                    &line_layouts,
1766                    cx,
1767                )
1768            } else {
1769                false
1770            };
1771
1772            if clamped || autoscrolled {
1773                snapshot = view.snapshot(cx);
1774            }
1775        });
1776
1777        let mut context_menu = None;
1778        let mut code_actions_indicator = None;
1779        let mut hover = None;
1780        let mut mode = EditorMode::Full;
1781        cx.render(&self.view.upgrade(cx).unwrap(), |view, cx| {
1782            let newest_selection_head = view
1783                .selections
1784                .newest::<usize>(cx)
1785                .head()
1786                .to_display_point(&snapshot);
1787
1788            let style = view.style(cx);
1789            if (start_row..end_row).contains(&newest_selection_head.row()) {
1790                if view.context_menu_visible() {
1791                    context_menu =
1792                        view.render_context_menu(newest_selection_head, style.clone(), cx);
1793                }
1794
1795                code_actions_indicator = view
1796                    .render_code_actions_indicator(&style, cx)
1797                    .map(|indicator| (newest_selection_head.row(), indicator));
1798            }
1799
1800            let visible_rows = start_row..start_row + line_layouts.len() as u32;
1801            hover = view.hover_state.render(&snapshot, &style, visible_rows, cx);
1802            mode = view.mode;
1803        });
1804
1805        if let Some((_, context_menu)) = context_menu.as_mut() {
1806            context_menu.layout(
1807                SizeConstraint {
1808                    min: Vector2F::zero(),
1809                    max: vec2f(
1810                        cx.window_size.x() * 0.7,
1811                        (12. * line_height).min((size.y() - line_height) / 2.),
1812                    ),
1813                },
1814                cx,
1815            );
1816        }
1817
1818        if let Some((_, indicator)) = code_actions_indicator.as_mut() {
1819            indicator.layout(
1820                SizeConstraint::strict_along(
1821                    Axis::Vertical,
1822                    line_height * style.code_actions.vertical_scale,
1823                ),
1824                cx,
1825            );
1826        }
1827
1828        if let Some((_, hover_popovers)) = hover.as_mut() {
1829            for hover_popover in hover_popovers.iter_mut() {
1830                hover_popover.layout(
1831                    SizeConstraint {
1832                        min: Vector2F::zero(),
1833                        max: vec2f(
1834                            (120. * em_width) // Default size
1835                                .min(size.x() / 2.) // Shrink to half of the editor width
1836                                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
1837                            (16. * line_height) // Default size
1838                                .min(size.y() / 2.) // Shrink to half of the editor height
1839                                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
1840                        ),
1841                    },
1842                    cx,
1843                );
1844            }
1845        }
1846
1847        (
1848            size,
1849            LayoutState {
1850                mode,
1851                position_map: Arc::new(PositionMap {
1852                    size,
1853                    scroll_max,
1854                    line_layouts,
1855                    line_height,
1856                    em_width,
1857                    em_advance,
1858                    snapshot,
1859                }),
1860                visible_display_row_range: start_row..end_row,
1861                gutter_size,
1862                gutter_padding,
1863                text_size,
1864                scrollbar_row_range,
1865                show_scrollbars,
1866                max_row,
1867                gutter_margin,
1868                active_rows,
1869                highlighted_rows,
1870                highlighted_ranges,
1871                line_number_layouts,
1872                hunk_layouts,
1873                blocks,
1874                selections,
1875                context_menu,
1876                code_actions_indicator,
1877                hover_popovers: hover,
1878            },
1879        )
1880    }
1881
1882    fn paint(
1883        &mut self,
1884        bounds: RectF,
1885        visible_bounds: RectF,
1886        layout: &mut Self::LayoutState,
1887        cx: &mut PaintContext,
1888    ) -> Self::PaintState {
1889        let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
1890        cx.scene.push_layer(Some(visible_bounds));
1891
1892        let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
1893        let text_bounds = RectF::new(
1894            bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
1895            layout.text_size,
1896        );
1897
1898        Self::attach_mouse_handlers(
1899            &self.view,
1900            &layout.position_map,
1901            visible_bounds,
1902            text_bounds,
1903            gutter_bounds,
1904            bounds,
1905            cx,
1906        );
1907
1908        self.paint_background(gutter_bounds, text_bounds, layout, cx);
1909        if layout.gutter_size.x() > 0. {
1910            self.paint_gutter(gutter_bounds, visible_bounds, layout, cx);
1911        }
1912        self.paint_text(text_bounds, visible_bounds, layout, cx);
1913
1914        cx.scene.push_layer(Some(bounds));
1915        if !layout.blocks.is_empty() {
1916            self.paint_blocks(bounds, visible_bounds, layout, cx);
1917        }
1918        self.paint_scrollbar(bounds, layout, cx);
1919        cx.scene.pop_layer();
1920
1921        cx.scene.pop_layer();
1922    }
1923
1924    fn dispatch_event(
1925        &mut self,
1926        event: &Event,
1927        _: RectF,
1928        _: RectF,
1929        _: &mut LayoutState,
1930        _: &mut (),
1931        cx: &mut EventContext,
1932    ) -> bool {
1933        if let Event::ModifiersChanged(event) = event {
1934            self.modifiers_changed(*event, cx);
1935        }
1936
1937        false
1938    }
1939
1940    fn rect_for_text_range(
1941        &self,
1942        range_utf16: Range<usize>,
1943        bounds: RectF,
1944        _: RectF,
1945        layout: &Self::LayoutState,
1946        _: &Self::PaintState,
1947        _: &gpui::MeasurementContext,
1948    ) -> Option<RectF> {
1949        let text_bounds = RectF::new(
1950            bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
1951            layout.text_size,
1952        );
1953        let content_origin = text_bounds.origin() + vec2f(layout.gutter_margin, 0.);
1954        let scroll_position = layout.position_map.snapshot.scroll_position();
1955        let start_row = scroll_position.y() as u32;
1956        let scroll_top = scroll_position.y() * layout.position_map.line_height;
1957        let scroll_left = scroll_position.x() * layout.position_map.em_width;
1958
1959        let range_start = OffsetUtf16(range_utf16.start)
1960            .to_display_point(&layout.position_map.snapshot.display_snapshot);
1961        if range_start.row() < start_row {
1962            return None;
1963        }
1964
1965        let line = layout
1966            .position_map
1967            .line_layouts
1968            .get((range_start.row() - start_row) as usize)?;
1969        let range_start_x = line.x_for_index(range_start.column() as usize);
1970        let range_start_y = range_start.row() as f32 * layout.position_map.line_height;
1971        Some(RectF::new(
1972            content_origin
1973                + vec2f(
1974                    range_start_x,
1975                    range_start_y + layout.position_map.line_height,
1976                )
1977                - vec2f(scroll_left, scroll_top),
1978            vec2f(
1979                layout.position_map.em_width,
1980                layout.position_map.line_height,
1981            ),
1982        ))
1983    }
1984
1985    fn debug(
1986        &self,
1987        bounds: RectF,
1988        _: &Self::LayoutState,
1989        _: &Self::PaintState,
1990        _: &gpui::DebugContext,
1991    ) -> json::Value {
1992        json!({
1993            "type": "BufferElement",
1994            "bounds": bounds.to_json()
1995        })
1996    }
1997}
1998
1999pub struct LayoutState {
2000    position_map: Arc<PositionMap>,
2001    gutter_size: Vector2F,
2002    gutter_padding: f32,
2003    gutter_margin: f32,
2004    text_size: Vector2F,
2005    mode: EditorMode,
2006    visible_display_row_range: Range<u32>,
2007    active_rows: BTreeMap<u32, bool>,
2008    highlighted_rows: Option<Range<u32>>,
2009    line_number_layouts: Vec<Option<text_layout::Line>>,
2010    hunk_layouts: Vec<DiffHunkLayout>,
2011    blocks: Vec<BlockLayout>,
2012    highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
2013    selections: Vec<(ReplicaId, Vec<SelectionLayout>)>,
2014    scrollbar_row_range: Range<f32>,
2015    show_scrollbars: bool,
2016    max_row: u32,
2017    context_menu: Option<(DisplayPoint, ElementBox)>,
2018    code_actions_indicator: Option<(u32, ElementBox)>,
2019    hover_popovers: Option<(DisplayPoint, Vec<ElementBox>)>,
2020}
2021
2022pub struct PositionMap {
2023    size: Vector2F,
2024    line_height: f32,
2025    scroll_max: Vector2F,
2026    em_width: f32,
2027    em_advance: f32,
2028    line_layouts: Vec<text_layout::Line>,
2029    snapshot: EditorSnapshot,
2030}
2031
2032impl PositionMap {
2033    /// Returns two display points:
2034    /// 1. The nearest *valid* position in the editor
2035    /// 2. An unclipped, potentially *invalid* position that maps directly to
2036    ///    the given pixel position.
2037    fn point_for_position(
2038        &self,
2039        text_bounds: RectF,
2040        position: Vector2F,
2041    ) -> (DisplayPoint, DisplayPoint) {
2042        let scroll_position = self.snapshot.scroll_position();
2043        let position = position - text_bounds.origin();
2044        let y = position.y().max(0.0).min(self.size.y());
2045        let x = position.x() + (scroll_position.x() * self.em_width);
2046        let row = (y / self.line_height + scroll_position.y()) as u32;
2047        let (column, x_overshoot) = if let Some(line) = self
2048            .line_layouts
2049            .get(row as usize - scroll_position.y() as usize)
2050        {
2051            if let Some(ix) = line.index_for_x(x) {
2052                (ix as u32, 0.0)
2053            } else {
2054                (line.len() as u32, 0f32.max(x - line.width()))
2055            }
2056        } else {
2057            (0, x)
2058        };
2059
2060        let mut target_point = DisplayPoint::new(row, column);
2061        let point = self.snapshot.clip_point(target_point, Bias::Left);
2062        *target_point.column_mut() += (x_overshoot / self.em_advance) as u32;
2063
2064        (point, target_point)
2065    }
2066}
2067
2068struct BlockLayout {
2069    row: u32,
2070    element: ElementBox,
2071    style: BlockStyle,
2072}
2073
2074fn layout_line(
2075    row: u32,
2076    snapshot: &EditorSnapshot,
2077    style: &EditorStyle,
2078    layout_cache: &TextLayoutCache,
2079) -> text_layout::Line {
2080    let mut line = snapshot.line(row);
2081
2082    if line.len() > MAX_LINE_LEN {
2083        let mut len = MAX_LINE_LEN;
2084        while !line.is_char_boundary(len) {
2085            len -= 1;
2086        }
2087
2088        line.truncate(len);
2089    }
2090
2091    layout_cache.layout_str(
2092        &line,
2093        style.text.font_size,
2094        &[(
2095            snapshot.line_len(row) as usize,
2096            RunStyle {
2097                font_id: style.text.font_id,
2098                color: Color::black(),
2099                underline: Default::default(),
2100            },
2101        )],
2102    )
2103}
2104
2105#[derive(Debug)]
2106pub struct Cursor {
2107    origin: Vector2F,
2108    block_width: f32,
2109    line_height: f32,
2110    color: Color,
2111    shape: CursorShape,
2112    block_text: Option<Line>,
2113}
2114
2115impl Cursor {
2116    pub fn new(
2117        origin: Vector2F,
2118        block_width: f32,
2119        line_height: f32,
2120        color: Color,
2121        shape: CursorShape,
2122        block_text: Option<Line>,
2123    ) -> Cursor {
2124        Cursor {
2125            origin,
2126            block_width,
2127            line_height,
2128            color,
2129            shape,
2130            block_text,
2131        }
2132    }
2133
2134    pub fn bounding_rect(&self, origin: Vector2F) -> RectF {
2135        RectF::new(
2136            self.origin + origin,
2137            vec2f(self.block_width, self.line_height),
2138        )
2139    }
2140
2141    pub fn paint(&self, origin: Vector2F, cx: &mut PaintContext) {
2142        let bounds = match self.shape {
2143            CursorShape::Bar => RectF::new(self.origin + origin, vec2f(2.0, self.line_height)),
2144            CursorShape::Block | CursorShape::Hollow => RectF::new(
2145                self.origin + origin,
2146                vec2f(self.block_width, self.line_height),
2147            ),
2148            CursorShape::Underscore => RectF::new(
2149                self.origin + origin + Vector2F::new(0.0, self.line_height - 2.0),
2150                vec2f(self.block_width, 2.0),
2151            ),
2152        };
2153
2154        //Draw background or border quad
2155        if matches!(self.shape, CursorShape::Hollow) {
2156            cx.scene.push_quad(Quad {
2157                bounds,
2158                background: None,
2159                border: Border::all(1., self.color),
2160                corner_radius: 0.,
2161            });
2162        } else {
2163            cx.scene.push_quad(Quad {
2164                bounds,
2165                background: Some(self.color),
2166                border: Default::default(),
2167                corner_radius: 0.,
2168            });
2169        }
2170
2171        if let Some(block_text) = &self.block_text {
2172            block_text.paint(self.origin + origin, bounds, self.line_height, cx);
2173        }
2174    }
2175
2176    pub fn shape(&self) -> CursorShape {
2177        self.shape
2178    }
2179}
2180
2181#[derive(Debug)]
2182pub struct HighlightedRange {
2183    pub start_y: f32,
2184    pub line_height: f32,
2185    pub lines: Vec<HighlightedRangeLine>,
2186    pub color: Color,
2187    pub corner_radius: f32,
2188}
2189
2190#[derive(Debug)]
2191pub struct HighlightedRangeLine {
2192    pub start_x: f32,
2193    pub end_x: f32,
2194}
2195
2196impl HighlightedRange {
2197    pub fn paint(&self, bounds: RectF, scene: &mut Scene) {
2198        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
2199            self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
2200            self.paint_lines(
2201                self.start_y + self.line_height,
2202                &self.lines[1..],
2203                bounds,
2204                scene,
2205            );
2206        } else {
2207            self.paint_lines(self.start_y, &self.lines, bounds, scene);
2208        }
2209    }
2210
2211    fn paint_lines(
2212        &self,
2213        start_y: f32,
2214        lines: &[HighlightedRangeLine],
2215        bounds: RectF,
2216        scene: &mut Scene,
2217    ) {
2218        if lines.is_empty() {
2219            return;
2220        }
2221
2222        let mut path = PathBuilder::new();
2223        let first_line = lines.first().unwrap();
2224        let last_line = lines.last().unwrap();
2225
2226        let first_top_left = vec2f(first_line.start_x, start_y);
2227        let first_top_right = vec2f(first_line.end_x, start_y);
2228
2229        let curve_height = vec2f(0., self.corner_radius);
2230        let curve_width = |start_x: f32, end_x: f32| {
2231            let max = (end_x - start_x) / 2.;
2232            let width = if max < self.corner_radius {
2233                max
2234            } else {
2235                self.corner_radius
2236            };
2237
2238            vec2f(width, 0.)
2239        };
2240
2241        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
2242        path.reset(first_top_right - top_curve_width);
2243        path.curve_to(first_top_right + curve_height, first_top_right);
2244
2245        let mut iter = lines.iter().enumerate().peekable();
2246        while let Some((ix, line)) = iter.next() {
2247            let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
2248
2249            if let Some((_, next_line)) = iter.peek() {
2250                let next_top_right = vec2f(next_line.end_x, bottom_right.y());
2251
2252                match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
2253                    Ordering::Equal => {
2254                        path.line_to(bottom_right);
2255                    }
2256                    Ordering::Less => {
2257                        let curve_width = curve_width(next_top_right.x(), bottom_right.x());
2258                        path.line_to(bottom_right - curve_height);
2259                        if self.corner_radius > 0. {
2260                            path.curve_to(bottom_right - curve_width, bottom_right);
2261                        }
2262                        path.line_to(next_top_right + curve_width);
2263                        if self.corner_radius > 0. {
2264                            path.curve_to(next_top_right + curve_height, next_top_right);
2265                        }
2266                    }
2267                    Ordering::Greater => {
2268                        let curve_width = curve_width(bottom_right.x(), next_top_right.x());
2269                        path.line_to(bottom_right - curve_height);
2270                        if self.corner_radius > 0. {
2271                            path.curve_to(bottom_right + curve_width, bottom_right);
2272                        }
2273                        path.line_to(next_top_right - curve_width);
2274                        if self.corner_radius > 0. {
2275                            path.curve_to(next_top_right + curve_height, next_top_right);
2276                        }
2277                    }
2278                }
2279            } else {
2280                let curve_width = curve_width(line.start_x, line.end_x);
2281                path.line_to(bottom_right - curve_height);
2282                if self.corner_radius > 0. {
2283                    path.curve_to(bottom_right - curve_width, bottom_right);
2284                }
2285
2286                let bottom_left = vec2f(line.start_x, bottom_right.y());
2287                path.line_to(bottom_left + curve_width);
2288                if self.corner_radius > 0. {
2289                    path.curve_to(bottom_left - curve_height, bottom_left);
2290                }
2291            }
2292        }
2293
2294        if first_line.start_x > last_line.start_x {
2295            let curve_width = curve_width(last_line.start_x, first_line.start_x);
2296            let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
2297            path.line_to(second_top_left + curve_height);
2298            if self.corner_radius > 0. {
2299                path.curve_to(second_top_left + curve_width, second_top_left);
2300            }
2301            let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
2302            path.line_to(first_bottom_left - curve_width);
2303            if self.corner_radius > 0. {
2304                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
2305            }
2306        }
2307
2308        path.line_to(first_top_left + curve_height);
2309        if self.corner_radius > 0. {
2310            path.curve_to(first_top_left + top_curve_width, first_top_left);
2311        }
2312        path.line_to(first_top_right - top_curve_width);
2313
2314        scene.push_path(path.build(self.color, Some(bounds)));
2315    }
2316}
2317
2318pub fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
2319    delta.powf(1.5) / 100.0
2320}
2321
2322fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
2323    delta.powf(1.2) / 300.0
2324}
2325
2326#[cfg(test)]
2327mod tests {
2328    use std::sync::Arc;
2329
2330    use super::*;
2331    use crate::{
2332        display_map::{BlockDisposition, BlockProperties},
2333        Editor, MultiBuffer,
2334    };
2335    use settings::Settings;
2336    use util::test::sample_text;
2337
2338    #[gpui::test]
2339    fn test_layout_line_numbers(cx: &mut gpui::MutableAppContext) {
2340        cx.set_global(Settings::test(cx));
2341        let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
2342        let (window_id, editor) = cx.add_window(Default::default(), |cx| {
2343            Editor::new(EditorMode::Full, buffer, None, None, cx)
2344        });
2345        let element = EditorElement::new(editor.downgrade(), editor.read(cx).style(cx));
2346
2347        let layouts = editor.update(cx, |editor, cx| {
2348            let snapshot = editor.snapshot(cx);
2349            let mut presenter = cx.build_presenter(window_id, 30., Default::default());
2350            let layout_cx = presenter.build_layout_context(Vector2F::zero(), false, cx);
2351            element.layout_line_numbers(0..6, &Default::default(), &snapshot, &layout_cx)
2352        });
2353        assert_eq!(layouts.len(), 6);
2354    }
2355
2356    #[gpui::test]
2357    fn test_layout_with_placeholder_text_and_blocks(cx: &mut gpui::MutableAppContext) {
2358        cx.set_global(Settings::test(cx));
2359        let buffer = MultiBuffer::build_simple("", cx);
2360        let (window_id, editor) = cx.add_window(Default::default(), |cx| {
2361            Editor::new(EditorMode::Full, buffer, None, None, cx)
2362        });
2363
2364        editor.update(cx, |editor, cx| {
2365            editor.set_placeholder_text("hello", cx);
2366            editor.insert_blocks(
2367                [BlockProperties {
2368                    style: BlockStyle::Fixed,
2369                    disposition: BlockDisposition::Above,
2370                    height: 3,
2371                    position: Anchor::min(),
2372                    render: Arc::new(|_| Empty::new().boxed()),
2373                }],
2374                cx,
2375            );
2376
2377            // Blur the editor so that it displays placeholder text.
2378            cx.blur();
2379        });
2380
2381        let mut element = EditorElement::new(editor.downgrade(), editor.read(cx).style(cx));
2382
2383        let mut scene = Scene::new(1.0);
2384        let mut presenter = cx.build_presenter(window_id, 30., Default::default());
2385        let mut layout_cx = presenter.build_layout_context(Vector2F::zero(), false, cx);
2386        let (size, mut state) = element.layout(
2387            SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
2388            &mut layout_cx,
2389        );
2390
2391        assert_eq!(state.position_map.line_layouts.len(), 4);
2392        assert_eq!(
2393            state
2394                .line_number_layouts
2395                .iter()
2396                .map(Option::is_some)
2397                .collect::<Vec<_>>(),
2398            &[false, false, false, true]
2399        );
2400
2401        // Don't panic.
2402        let bounds = RectF::new(Default::default(), size);
2403        let mut paint_cx = presenter.build_paint_context(&mut scene, bounds.size(), cx);
2404        element.paint(bounds, bounds, &mut state, &mut paint_cx);
2405    }
2406}