element.rs

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