diff --git a/Cargo.lock b/Cargo.lock index 9cbee49675..896a7f44e2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2873,6 +2873,20 @@ dependencies = [ "tree-sitter-navi", ] +[[package]] +name = "example-editor-gutter-menu" +version = "0.10.0" +dependencies = [ + "gpui-kit", +] + +[[package]] +name = "example-editor-spacers" +version = "0.10.0" +dependencies = [ + "gpui-kit", +] + [[package]] name = "example-html" version = "0.10.0" diff --git a/Cargo.toml b/Cargo.toml index 23d46cdb07..f87bab7c5a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,6 +17,8 @@ members = [ "examples/hello_world", "examples/input", "examples/editor", + "examples/editor_gutter_menu", + "examples/editor_spacers", "examples/syntect", "examples/tig", "examples/brush", diff --git a/crates/base/examples/showcase/mod.rs b/crates/base/examples/showcase/mod.rs index 06f20a9fea..6d5f6e4ccb 100644 --- a/crates/base/examples/showcase/mod.rs +++ b/crates/base/examples/showcase/mod.rs @@ -179,6 +179,16 @@ pub struct BaseShowcase { text_selection_footer_bounds: Rc>>>, } +/// The showcase's editor colors, assigned over the defaults. +fn editor_style() -> InputEditorStyle { + let mut style = InputEditorStyle::default(); + style.foreground = example_rgb(0x171717).into(); + style.muted_foreground = example_rgb(0x737373).into(); + style.selection = gpui::hsla(0.6, 0.8, 0.7, 0.45); + style.caret = example_rgb(0x171717).into(); + style +} + impl BaseShowcase { pub fn new(component: impl Into, window: &mut Window, cx: &mut Context) -> Self { activate_palette(window, cx); @@ -191,24 +201,12 @@ impl BaseShowcase { } else { "Hello GPUI" }); - state.set_editor_style(InputEditorStyle { - foreground: example_rgb(0x171717).into(), - muted_foreground: example_rgb(0x737373).into(), - selection: gpui::hsla(0.6, 0.8, 0.7, 0.45), - caret: example_rgb(0x171717).into(), - ..InputEditorStyle::default() - }); + state.set_editor_style(editor_style()); state }); let toolbar_search = cx.new(|cx| { let mut state = InputState::new(window, cx).placeholder("Search"); - state.set_editor_style(InputEditorStyle { - foreground: example_rgb(0x171717).into(), - muted_foreground: example_rgb(0x737373).into(), - selection: gpui::hsla(0.6, 0.8, 0.7, 0.45), - caret: example_rgb(0x171717).into(), - ..InputEditorStyle::default() - }); + state.set_editor_style(editor_style()); state }); let otp = cx.new(|cx| OtpState::new(6, window, cx).default_value("12")); @@ -225,13 +223,7 @@ impl BaseShowcase { }); let textarea_base = textarea.clone(); textarea_base.update(cx, |state, _| { - state.set_editor_style(InputEditorStyle { - foreground: example_rgb(0x171717).into(), - muted_foreground: example_rgb(0x737373).into(), - selection: gpui::hsla(0.6, 0.8, 0.7, 0.45), - caret: example_rgb(0x171717).into(), - ..InputEditorStyle::default() - }); + state.set_editor_style(editor_style()); }); let editor = cx.new(|cx| { EditorState::new(window, cx) @@ -250,24 +242,13 @@ impl BaseShowcase { }), cx, ); - state.set_editor_style(InputEditorStyle { - foreground: example_rgb(0x171717).into(), - muted_foreground: example_rgb(0x737373).into(), - selection: gpui::hsla(0.6, 0.8, 0.7, 0.45), - caret: example_rgb(0x171717).into(), - highlight_styles: Arc::new(ShowcaseHighlightStyles), - ..InputEditorStyle::default() - }); + let mut style = editor_style(); + style.highlight_styles = Arc::new(ShowcaseHighlightStyles); + state.set_editor_style(style); }); let combobox_query = cx.new(|cx| { let mut state = InputState::new(window, cx).placeholder("Search frameworks…"); - state.set_editor_style(InputEditorStyle { - foreground: example_rgb(0x171717).into(), - muted_foreground: example_rgb(0x737373).into(), - selection: gpui::hsla(0.6, 0.8, 0.7, 0.45), - caret: example_rgb(0x171717).into(), - ..InputEditorStyle::default() - }); + state.set_editor_style(editor_style()); state }); cx.subscribe( @@ -434,26 +415,18 @@ impl BaseShowcase { } fn refresh_editor_styles(&self, cx: &mut Context) { - let style = || InputEditorStyle { - foreground: example_rgb(0x171717).into(), - muted_foreground: example_rgb(0x737373).into(), - selection: gpui::hsla(0.6, 0.8, 0.7, 0.45), - caret: example_rgb(0x171717).into(), - ..InputEditorStyle::default() - }; self.input - .update(cx, |state, _| state.set_editor_style(style())); + .update(cx, |state, _| state.set_editor_style(editor_style())); self.textarea - .update(cx, |state, _| state.set_editor_style(style())); + .update(cx, |state, _| state.set_editor_style(editor_style())); self.combobox_query - .update(cx, |state, _| state.set_editor_style(style())); + .update(cx, |state, _| state.set_editor_style(editor_style())); self.toolbar_search - .update(cx, |state, _| state.set_editor_style(style())); + .update(cx, |state, _| state.set_editor_style(editor_style())); self.editor.update(cx, |state, _| { - state.set_editor_style(InputEditorStyle { - highlight_styles: Arc::new(ShowcaseHighlightStyles), - ..style() - }); + let mut style = editor_style(); + style.highlight_styles = Arc::new(ShowcaseHighlightStyles); + state.set_editor_style(style); }); } diff --git a/crates/base/src/input/base/element.rs b/crates/base/src/input/base/element.rs index 698bd7b31d..69f5f7fd83 100644 --- a/crates/base/src/input/base/element.rs +++ b/crates/base/src/input/base/element.rs @@ -4,8 +4,9 @@ use crate::input::{ }; use gpui::Corners; use gpui::Half; +use gpui::prelude::FluentBuilder as _; use gpui::{ - AnyElement, App, Bounds, Edges, Element, ElementId, ElementInputHandler, Entity, + AnyElement, App, Bounds, ContentMask, Edges, Element, ElementId, ElementInputHandler, Entity, GlobalElementId, }; use gpui::{ @@ -20,12 +21,12 @@ use smallvec::SmallVec; use std::{collections::BTreeSet, ops::Range, rc::Rc}; use crate::{ - Scrollbar, + Scrollbar, ScrollbarPlacement, Side, input::{RopeExt as _, blink_cursor::CURSOR_WIDTH, display_map::LineLayout}, }; use super::{ - InputBaseState, PrepaintCaretGeometry, RangeDecorationStyle, TextDecoration, + GutterColumn, InputBaseState, PrepaintCaretGeometry, RangeDecorationStyle, TextDecoration, layout::{LastLayout, WhitespaceIndicators}, mode::LayoutMode, tab_stops::{expand_tabs, expanded_width, tab_stop_width}, @@ -229,6 +230,8 @@ pub(super) struct EditorScrollbarSnapshot { line_height: Pixels, padding_top: Pixels, wrap_width: Option, + placement: ScrollbarPlacement, + horizontal_bounds: Option>, } impl EditorScrollbarSnapshot { @@ -241,13 +244,39 @@ impl EditorScrollbarSnapshot { scroll_y_f64: f64, state: &InputBaseState, ) -> Self { + let mut layout = EditorScrollbarLayout::new( + input_bounds, + last_layout.text_origin_x, + scroll_size, + state.editor_paddings, + state.scrollbar_placement, + ); + if state.gutter_side.is_left() + && !state.scrollbar_placement.is_left() + && last_layout.line_number_width > px(0.) + { + layout.set_gutter_gap(last_layout.gutter_gap); + } + let horizontal_bounds = (state.gutter_side.is_right() + && state.scrollbar_placement.is_left() + && last_layout.line_number_width > px(0.)) + .then(|| { + // Mirror the left gutter's track inset, including its outer + // padding. The full viewport still anchors the vertical bar. + let inset = (state.editor_paddings.right * 2. + last_layout.line_number_width + - last_layout.gutter_gap) + .max(px(0.)); + Bounds::new( + layout.bounds.origin, + size( + (layout.bounds.size.width - inset).max(px(0.)), + layout.bounds.size.height, + ), + ) + }); Self { - layout: EditorScrollbarLayout::new( - input_bounds, - last_layout.line_number_width, - scroll_size, - state.editor_paddings, - ), + layout, + horizontal_bounds, cursor_scroll_offset, scroll_height_f64, scroll_y_f64, @@ -255,12 +284,9 @@ impl EditorScrollbarSnapshot { line_height: last_layout.line_height, padding_top: state.editor_paddings.top, wrap_width: last_layout.wrap_width, + placement: state.scrollbar_placement, } } - fn with_gutter_gap(mut self, gap: Pixels) -> Self { - self.layout.set_gutter_gap(gap); - self - } } impl EditorScrollbarLayout { @@ -278,14 +304,17 @@ impl EditorScrollbarLayout { fn new( input_bounds: Bounds, - line_number_width: Pixels, + text_origin_x: Pixels, scroll_size: Size, paddings: Edges, + placement: ScrollbarPlacement, ) -> Self { - let left = if line_number_width == px(0.) { + let left = if placement.is_left() { + -paddings.left + } else if text_origin_x == px(0.) { px(0.) } else { - paddings.left + line_number_width - LINE_NUMBER_RIGHT_MARGIN + paddings.left + text_origin_x - LINE_NUMBER_RIGHT_MARGIN }; let bounds = Bounds::new( @@ -395,6 +424,7 @@ impl Element for EditorScrollbar { } else { crate::ScrollbarAxis::Both }, + placement: snapshot.placement, }; renderer(presentation, window, cx) } else { @@ -403,7 +433,11 @@ impl Element for EditorScrollbar { } else { Scrollbar::vertical(&scroll_handle) } + .placement(snapshot.placement) .viewport_bounds(snapshot.layout.bounds) + .when_some(snapshot.horizontal_bounds, |this, bounds| { + this.horizontal_viewport_bounds(bounds) + }) .scroll_viewport_size(snapshot.layout.scroll_viewport_size) .scroll_size(snapshot.layout.scroll_size) .into_any_element() @@ -476,19 +510,42 @@ fn clamp_vertical_scroll_offset( ) as f32) } +/// Where the spacer rows that have a background are painted: their top +/// relative to the content origin, their height and their color. Rows from +/// `ghost_end` on are below the ghost lines and move down by their height. +fn place_spacer_backgrounds( + layout: &LastLayout, + rows: Vec<(Range, Hsla)>, + ghost_end: Option, +) -> Vec<(Pixels, Pixels, Hsla)> { + let ghost_height = layout.ghost_lines.map_or(px(0.), |(_, height)| height); + rows.into_iter() + .map(|(rows, color)| { + let mut top = layout.display_row_y(rows.start); + if ghost_end.is_some_and(|end| rows.start >= end) { + top += ghost_height; + } + (top, layout.line_height * rows.len(), color) + }) + .collect() +} + fn editor_gutter_bounds( input_bounds: Bounds, line_number_width: Pixels, ghost_lines_height: Pixels, paddings: Edges, + side: Side, ) -> Bounds { + let (x, outer_padding) = if side.is_left() { + (input_bounds.origin.x - paddings.left, paddings.left) + } else { + (input_bounds.right() - line_number_width, paddings.right) + }; Bounds { - origin: point( - input_bounds.origin.x - paddings.left, - input_bounds.origin.y - paddings.top, - ), + origin: point(x, input_bounds.origin.y - paddings.top), size: size( - line_number_width + paddings.left, + line_number_width + outer_padding, input_bounds.size.height + ghost_lines_height + paddings.top + paddings.bottom, ), } @@ -654,8 +711,14 @@ fn layout_overview_ruler( return Vec::new(); } + // The marks sit on the vertical track, on whichever side it is placed. + let track_left = if snapshot.placement.is_left() { + layout.bounds.left() + } else { + layout.bounds.right() - track_width + }; let track = Bounds::new( - point(layout.bounds.right() - track_width, layout.bounds.top()), + point(track_left, layout.bounds.top()), size(track_width, layout.bounds.size.height), ); let track_height_f64 = f64::from(f32::from(track.size.height)); @@ -701,6 +764,133 @@ fn layout_overview_ruler( .collect() } +/// Return the part of `bounds` on the text's side of the gutter. +fn editor_text_bounds( + bounds: Bounds, + gutter_bounds: Bounds, + side: Side, +) -> Bounds { + let (left, right) = if side.is_left() { + (gutter_bounds.right().max(bounds.left()), bounds.right()) + } else { + (bounds.left(), gutter_bounds.left().min(bounds.right())) + }; + Bounds::from_corners( + point(left.min(right), bounds.top()), + point(right, bounds.bottom()), + ) +} + +/// Return the x and the width of a gutter column, relative to the input bounds. +/// +/// From the text outward, a gutter holds a margin, then its columns in the +/// order of `gutter_order`. A gutter on the right is the mirror of one on the +/// left. +pub(super) fn gutter_column( + last_layout: &LastLayout, + folding: bool, + column: GutterColumn, +) -> (Pixels, Pixels) { + let width = |column| match column { + GutterColumn::FoldIcons => fold_column_width(folding), + GutterColumn::LineNumbers => line_number_column_width(last_layout, folding), + GutterColumn::Markers => last_layout.gutter_marker_width, + GutterColumn::Decorations => last_layout.gutter_decorations_width, + }; + let inset = last_layout + .gutter_order + .iter() + .take_while(|&&other| other != column) + .fold(last_layout.gutter_gap, |inset, &other| inset + width(other)); + ( + gutter_column_x(last_layout, inset, width(column)), + width(column), + ) +} + +fn fold_column_width(folding: bool) -> Pixels { + if folding { + FOLD_ICON_HITBOX_WIDTH + } else { + px(0.) + } +} + +fn line_number_column_width(last_layout: &LastLayout, folding: bool) -> Pixels { + last_layout.line_number_width + - last_layout.gutter_marker_width + - last_layout.gutter_decorations_width + - last_layout.gutter_gap + - fold_column_width(folding) +} + +/// Return the x of a gutter column `inset` from the text, relative to the input bounds. +fn gutter_column_x(last_layout: &LastLayout, inset: Pixels, width: Pixels) -> Pixels { + if last_layout.gutter_side.is_left() { + last_layout.gutter_origin_x + last_layout.line_number_width - inset - width + } else { + last_layout.gutter_origin_x + inset + } +} + +/// Return the x of a line number `width` wide, aligned toward the text, +/// relative to the input bounds. +fn line_number_x(last_layout: &LastLayout, folding: bool, width: Pixels) -> Pixels { + let (numbers_x, numbers_width) = gutter_column(last_layout, folding, GutterColumn::LineNumbers); + if last_layout.gutter_side.is_left() { + numbers_x + numbers_width - width + } else { + numbers_x + } +} + +/// Return the x of a gutter marker `size` wide, relative to the input bounds. +/// +/// The rest of the markers' column is the gap toward the line numbers. +fn gutter_marker_x(last_layout: &LastLayout, folding: bool, size: Pixels) -> Pixels { + let (slot_x, slot_width) = gutter_column(last_layout, folding, GutterColumn::Markers); + let position = |column| { + last_layout + .gutter_order + .iter() + .position(|&other| other == column) + }; + let inset = if position(GutterColumn::LineNumbers) < position(GutterColumn::Markers) { + slot_width - size + } else { + px(0.) + }; + if last_layout.gutter_side.is_left() { + slot_x + slot_width - inset - size + } else { + slot_x + inset + } +} + +/// Return the x of the gutter decoration strip, `width` wide, relative to the +/// input bounds. +/// +/// As for the markers, the rest of the column is the gap toward the line numbers. +fn gutter_decorations_x(last_layout: &LastLayout, folding: bool, width: Pixels) -> Pixels { + let (column_x, column_width) = gutter_column(last_layout, folding, GutterColumn::Decorations); + let position = |column| { + last_layout + .gutter_order + .iter() + .position(|&other| other == column) + }; + let inset = if position(GutterColumn::LineNumbers) < position(GutterColumn::Decorations) { + column_width - width + } else { + px(0.) + }; + if last_layout.gutter_side.is_left() { + column_x + column_width - inset - width + } else { + column_x + inset + } +} + use super::MASK_CHAR; /// Convert a byte offset in the original text to a byte offset in the masked display string. @@ -874,6 +1064,15 @@ struct FoldIconLayout { icons: Vec<(usize, bool, gpui::AnyElement)>, } +/// Layout information for line decorations. +#[derive(Default)] +struct LineDecorationLayout { + /// List of (top, height, color) background bands, top relative to the content origin + backgrounds: Vec<(Pixels, Pixels, Hsla)>, + /// Prepainted gutter marker elements + markers: Vec, +} + pub(super) struct TextElement { pub(crate) state: Entity>, placeholder: SharedString, @@ -1044,7 +1243,8 @@ impl TextElement { } let line_height_f64 = f64::from(f32::from(line_height)); - let total_wrapped_lines = state.display_map.wrap_row_count(); + let total_wrapped_lines = + state.display_map.wrap_row_count() + state.display_map.spacer_row_count(); let empty_bottom = empty_bottom_height( state.is_code_editor(), state.scroll_beyond_last_line, @@ -1151,7 +1351,6 @@ impl TextElement { let line_height = last_layout.line_height; let visible_range = &last_layout.visible_range; let lines = &last_layout.lines; - let line_number_width = last_layout.line_number_width; let active_id = state.active_selection().id; let mut scroll_offset = state.scroll_handle.offset(); @@ -1237,9 +1436,9 @@ impl TextElement { TextAlign::Center => CURSOR_WIDTH, }; scroll_offset.x = if scroll_offset.x + cursor_pos.x - > (bounds.size.width - line_number_width - safety_margin) + > (last_layout.text_width - safety_margin) { - bounds.size.width - line_number_width - safety_margin - cursor_pos.x + last_layout.text_width - safety_margin - cursor_pos.x } else if scroll_offset.x + cursor_pos.x < px(0.) { -cursor_pos.x } else { @@ -1266,7 +1465,7 @@ impl TextElement { // Apply the final horizontal offset to every caret after cursor-follow and // deferred scrolling have been resolved, regardless of selection order. - let cursor_x = bounds.left() + cursor_pos.x + line_number_width; + let cursor_x = bounds.left() + cursor_pos.x + last_layout.text_origin_x; cursor_infos.push(CursorRenderInfo { bounds: Bounds::new( point( @@ -1313,7 +1512,7 @@ impl TextElement { ) -> Option> { let corners = Self::layout_range_corners(&range, last_layout)?; let points = frame_outline_points(&corners); - let origin = bounds.origin + point(last_layout.line_number_width, px(0.)); + let origin = bounds.origin + point(last_layout.text_origin_x, px(0.)); let mut builder = gpui::PathBuilder::fill(); builder.move_to(origin + *points.first()?); for point in points.iter().skip(1) { @@ -1336,16 +1535,18 @@ impl TextElement { return None; } - let mut row_offset: isize = 0; + let mut y = last_layout.visible_top; let mut corners = Vec::new(); - for (&line_offset, line) in last_layout + for (ix, (&line_offset, line)) in last_layout .visible_line_byte_offsets .iter() .zip(last_layout.lines.iter()) + .enumerate() { + let (spacer_above, spacer_below) = last_layout.spacers(ix); + y += spacer_above; let mut offset = line_offset; for (row, shaped) in line.wrapped_lines.iter().enumerate() { - let y = last_layout.local_row_y(row_offset); let end = offset + shaped.len; let start_ix = range.start.max(offset); let end_ix = range.end.min(end); @@ -1370,8 +1571,9 @@ impl TextElement { }); } offset = end; - row_offset += 1; + y += last_layout.line_height; } + y += spacer_below; } (!corners.is_empty()).then_some(corners) } @@ -1420,7 +1622,7 @@ impl TextElement { else { continue; }; - let origin = bounds.origin + point(last_layout.line_number_width, px(0.)); + let origin = bounds.origin + point(last_layout.text_origin_x, px(0.)); let corners = pad_frame_corners(&corners, px(1.)); let points = frame_outline_points(&corners) .into_iter() @@ -1632,12 +1834,16 @@ impl TextElement { let start_line = state.display_map.display_row_to_buffer_line(first_display); let end_line = state.display_map.display_row_to_buffer_line(last_display); - // Viewport-local y of the top of the first visible buffer line. + // Viewport-local y of the top of the first visible buffer line, above + // the spacers standing above it. let anchor_display_row = match state .display_map .buffer_line_to_display_row_range(start_line) { - Some(range) => range.start, + Some(range) => { + let (above, _) = state.display_map.spacer_rows_beside(start_line); + range.start - above + } None => first_display, }; let visible_top = @@ -1682,7 +1888,7 @@ impl TextElement { .measure_line_numbers(line_number_len, style, window); let mut line_number_width = if state.mode.line_number() { - number_width + gap + Self::gutter_marker_width(state, window) + number_width + gap } else if state.is_code_editor() { gap } else { @@ -1694,11 +1900,47 @@ impl TextElement { line_number_width += FOLD_ICON_HITBOX_WIDTH } - if let Some(width) = state.extras.gutter_decorations_width() { - line_number_width += width + GUTTER_DECORATION_GAP; + ( + line_number_width + Self::gutter_decorations_width(state), + gap, + ) + } + + /// Return the width reserved for the gutter markers' column. + /// + /// The slot is reserved while line numbers are shown, a marker renderer is set + /// and a line decoration collection has a provider, so the gutter keeps its + /// width as marked rows scroll in and out of view. + fn gutter_marker_width(state: &InputBaseState, window: &Window) -> Pixels { + if state.mode.line_number() + && state.editor_style.gutter_marker_renderer().is_some() + && state.extras.has_line_decorations() + { + let size = state + .editor_style + .gutter_marker_size() + .to_pixels(window.rem_size()); + if size > Pixels::ZERO { + size + state + .editor_style + .gutter_marker_gap() + .to_pixels(window.rem_size()) + .max(px(0.)) + } else { + px(0.) + } + } else { + px(0.) } + } - (line_number_width, gap) + /// Return the width reserved for the gutter decoration strip's column: the + /// strip and its gap, while a gutter decoration collection exists. + fn gutter_decorations_width(state: &InputBaseState) -> Pixels { + state + .extras + .gutter_decorations_width() + .map_or(px(0.), |width| width + GUTTER_DECORATION_GAP) } /// Layout shaped lines for whitespace indicators (space and tab). @@ -1844,7 +2086,7 @@ impl TextElement { /// Return (line_number_width, line_number_len) /// Layout fold icon hitboxes during prepaint phase. /// - /// This creates hitboxes for the fold icon area, positioned to the right of line numbers. + /// This creates hitboxes for the fold icon area, positioned between the line numbers and the text. /// Icons are created and prepainted here to avoid panics. /// Bars and boundary pills for gutter decorations, in the strip at `origin_x` /// before the line numbers. Rows below `ghost_rows.0` move down by the @@ -1931,7 +2173,6 @@ impl TextElement { origin_x: Pixels, bounds: &Bounds, last_layout: &LastLayout, - line_number_right_edge_offset: Pixels, window: &mut Window, cx: &mut App, ) -> FoldIconLayout { @@ -1945,7 +2186,10 @@ impl TextElement { let line_number_hitbox = window.insert_hitbox( Bounds::new( - point(origin_x, bounds.origin.y + last_layout.visible_top), + point( + origin_x + last_layout.gutter_origin_x, + bounds.origin.y + last_layout.visible_top, + ), size(last_layout.line_number_width, bounds.size.height), ), HitboxBehavior::Normal, @@ -1963,24 +2207,27 @@ impl TextElement { } let mut infos = Vec::with_capacity(last_layout.visible_buffer_lines.len()); - let mut row_offset: isize = 0; + let mut offset_y = last_layout.visible_top; - for (line, &buffer_line) in last_layout + for (ix, (line, &buffer_line)) in last_layout .lines .iter() .zip(last_layout.visible_buffer_lines.iter()) + .enumerate() { + let (spacer_above, spacer_below) = last_layout.spacers(ix); + offset_y += spacer_above; if state.display_map.is_fold_candidate(buffer_line) { let is_folded = state.display_map.is_folded_at(buffer_line); infos.push(FoldInfo { buffer_line, is_folded, display_row: buffer_line, - offset_y: last_layout.local_row_y(row_offset), + offset_y, }); } - row_offset += line.wrapped_lines.len() as isize; + offset_y += line.wrapped_lines.len() * last_layout.line_height + spacer_below; } infos @@ -1988,17 +2235,18 @@ impl TextElement { // Second pass: create and prepaint icons let line_height = last_layout.line_height; + let (fold_icon_x, _) = gutter_column(last_layout, true, GutterColumn::FoldIcons); let icon_relative_pos = point( (FOLD_ICON_HITBOX_WIDTH - FOLD_ICON_WIDTH).half(), (line_height - FOLD_ICON_WIDTH).half(), ); for (ix, info) in fold_infos.iter().enumerate() { - // Position fold icon to the right of line numbers. + // Position fold icon between the line numbers and the text. // Use origin_x (unscrolled) so icons stay fixed in the gutter during horizontal scroll. let fold_icon_bounds = Bounds::new( point( - origin_x + icon_relative_pos.x + line_number_right_edge_offset, + origin_x + icon_relative_pos.x + fold_icon_x, bounds.origin.y + icon_relative_pos.y + info.offset_y, ), size(FOLD_ICON_HITBOX_WIDTH, line_height), @@ -2094,27 +2342,29 @@ impl TextElement { // Each folded line on screen, the top of its first row, how many // rows it wraps to, and where its text ends. let mut folded = Vec::new(); - let mut row_offset: isize = 0; - let mut ghost_offset = px(0.); - for (line, &buffer_line) in last_layout + let mut offset_y = last_layout.visible_top; + for (ix, (line, &buffer_line)) in last_layout .lines .iter() .zip(last_layout.visible_buffer_lines.iter()) + .enumerate() { + let (spacer_above, spacer_below) = last_layout.spacers(ix); + offset_y += spacer_above; let rows = line.wrapped_lines.len(); - let top = last_layout.local_row_y(row_offset) + ghost_offset; if state.display_map.is_folded_at(buffer_line) && let Some(last) = line.wrapped_lines.last() { let end = line.row_x(rows - 1, last_layout.content_width) + last.width; - folded.push((buffer_line, top, rows, end)); + folded.push((buffer_line, offset_y, rows, end)); } - row_offset += rows as isize; + offset_y += rows * line_height; if let Some((row, height)) = ghost_rows && row == buffer_line { - ghost_offset += height; + offset_y += height; } + offset_y += spacer_below; } ( state.fold_background, @@ -2123,7 +2373,7 @@ impl TextElement { ) }; - let origin = bounds.origin + point(last_layout.line_number_width, px(0.)); + let origin = bounds.origin + point(last_layout.text_origin_x, px(0.)); for (buffer_line, top, rows, end) in folded { if let Some(color) = background { let bounds = Bounds::new( @@ -2168,6 +2418,105 @@ impl TextElement { folded_lines } + /// Ask the spacer provider for the spacers of every line, when the rows have + /// moved since it was last asked or it was told to be asked again. + /// + /// The provider is asked outside of any update of the state, so it may read + /// this editor as well as others. + fn ask_for_spacers(&self, cx: &mut App) { + let (provider, lines, version) = { + let state = self.state.read(cx); + let version = state.display_map.rows_version(); + if state.spacers_asked == Some(version) { + return; + } + ( + state.extras.spacer_provider(), + 0..state.display_map.buffer_line_count(), + version, + ) + }; + let spacers = provider + .map(|provider| provider.spacers(lines, cx)) + .unwrap_or_default(); + self.state.update(cx, |state, _| { + state.display_map.set_spacers(spacers); + state.spacers_asked = Some(version); + }); + } + + /// Layout line decoration backgrounds and gutter markers for the visible rows. + /// + /// Markers are only laid out while line numbers are shown, in their column + /// of the gutter. + fn layout_line_decorations( + &self, + origin_x: Pixels, + bounds: &Bounds, + last_layout: &LastLayout, + window: &mut Window, + cx: &mut App, + ) -> LineDecorationLayout { + let (Some(&first), Some(&last)) = ( + last_layout.visible_buffer_lines.first(), + last_layout.visible_buffer_lines.last(), + ) else { + return LineDecorationLayout::default(); + }; + let (decorations, renderer, marker_size, folding) = { + let state = self.state.read(cx); + let renderer = state + .mode + .line_number() + .then(|| state.editor_style.gutter_marker_renderer().cloned()) + .flatten(); + ( + state.extras.line_decorations(first..last + 1, cx), + renderer, + state + .editor_style + .gutter_marker_size() + .to_pixels(window.rem_size()), + state.mode.is_folding(), + ) + }; + if decorations.is_empty() { + return LineDecorationLayout::default(); + } + + let line_height = last_layout.line_height; + let rows: Vec<_> = last_layout.row_extents().collect(); + let marker_x = origin_x + gutter_marker_x(last_layout, folding, marker_size); + + let mut layout = LineDecorationLayout::default(); + for decoration in &decorations { + let Ok(ix) = last_layout + .visible_buffer_lines + .binary_search(&decoration.row()) + else { + continue; + }; + let Some(&(top, height)) = rows.get(ix) else { + continue; + }; + if let Some(color) = decoration.background() { + layout.backgrounds.push((top, height, color)); + } + if let (Some(marker), Some(render)) = (decoration.marker(), renderer.as_ref()) + && marker_size > Pixels::ZERO + { + let origin = point( + marker_x, + bounds.origin.y + top + (line_height - marker_size).half(), + ); + let mut element = render(marker); + element.prepaint_as_root(origin, size(marker_size, marker_size).into(), window, cx); + layout.markers.push(element); + } + } + layout + } + /// Paint fold icons using prepaint hitboxes. /// /// This handles: @@ -2759,9 +3108,10 @@ impl TextElement { .and_then(|c| c.key.as_ref()) .map_or(bounds.size.width, |k| k.2); let mut placements = Vec::new(); - let mut row_offset: isize = 0; + let mut y = layout.visible_top; for (ix, &row) in layout.visible_buffer_lines.iter().enumerate() { - let y = layout.local_row_y(row_offset); + let (spacer_above, spacer_below) = layout.spacers(ix); + y += spacer_above; let start = state.text.line_start_offset(row); let end = state.text.line_end_offset(row); let spans = state.token_spans(); @@ -2772,11 +3122,11 @@ impl TextElement { { placements.push(( state.token_context(span, layout.line_height, width), - bounds.origin + position + point(layout.line_number_width, y), + bounds.origin + position + point(layout.text_origin_x, y), )); } } - row_offset += layout.lines[ix].wrapped_lines.len() as isize; + y += layout.lines[ix].size(layout.line_height).height + spacer_below; } let mut out = Vec::new(); let mut token_bounds = std::collections::HashMap::new(); @@ -3131,7 +3481,6 @@ pub(super) struct PrepaintState { /// /// Each is the shaped number and the count of soft wrapped rows it spans. line_numbers: Option>, - line_number_right_edge_offset: Pixels, line_number_baseline_offset: Pixels, /// Size of the scrollable area by entire lines. scroll_size: Size, @@ -3156,6 +3505,11 @@ pub(super) struct PrepaintState { /// Fold icon layout data fold_icon_layout: FoldIconLayout, folded_lines: FoldedLines, + /// Line decoration layout data + line_decoration_layout: LineDecorationLayout, + /// (top, height, color) of the spacer rows that have a background, top + /// relative to the content origin. + spacer_backgrounds: Vec<(Pixels, Pixels, Hsla)>, // Inline completion rendering data /// Shaped ghost lines to paint after cursor row (completion lines 2+) ghost_lines: Vec, @@ -3431,17 +3785,30 @@ impl Element for TextElement Element for TextElement Element for TextElement 0 { + visible_buffer_lines + .iter() + .map(|&line| state.display_map.spacer_rows_beside(line)) + .collect() + } else { + Vec::new() + }; + // The display rows of the spacers that have a background; placed once + // the layout knows where its rows are. + let spacer_background_rows: Vec<(Range, Hsla)> = + match (visible_buffer_lines.first(), visible_buffer_lines.last()) { + (Some(&first), Some(&last)) => state + .display_map + .spacer_backgrounds(first..last + 1) + .collect(), + _ => Vec::new(), + }; let visible_start_offset = state.text.line_start_offset(visible_range.start); let visible_end_offset = state .text @@ -3537,6 +3925,16 @@ impl Element for TextElement Element for TextElement Element for TextElement bounds.size.width { - longest_line_width + line_number_width + RIGHT_MARGIN + if longest_line_width + reserved_width + RIGHT_MARGIN > bounds.size.width { + longest_line_width + reserved_width + RIGHT_MARGIN } else { longest_line_width }, @@ -3753,7 +4152,7 @@ impl Element for TextElement Element for TextElement 0) + .map(|row| (row, ghost_lines_height)); + // Ghost lines follow the cursor row's text, so they push down the + // spacers below it as well as every row after it. + let ghost_end = last_layout.ghost_lines.and_then(|(row, _)| { + let rows = self + .state + .read(cx) + .display_map + .buffer_line_to_display_row_range(row)?; + Some(rows.end) + }); + let spacer_backgrounds = + place_spacer_backgrounds(&last_layout, spacer_background_rows, ghost_end); // Completion/code-action menus position at the active caret. last_layout.cursor_bounds = cursor_infos .iter() @@ -3892,8 +4307,9 @@ impl Element for TextElement Element for TextElement Element for TextElement Element for TextElement px(0.)).then(|| { + editor_gutter_bounds( + input_bounds, + last_layout.line_number_width, + ghost_lines_height, + state.editor_paddings, + last_layout.gutter_side, + ) + }); state.last_layout = Some(last_layout.clone()); state.last_bounds = Some(bounds); state.last_cursor = Some(state.cursor()); @@ -4021,7 +4448,6 @@ impl Element for TextElement Element for TextElement Element for TextElement>(); + + // Paint line decoration backgrounds under everything else on the row. + for &(y, height, color) in &line_backgrounds { + window.paint_quad(fill( + Bounds::new( + point(input_bounds.origin.x, y), + size(bounds.size.width, height), + ), + color, + )); + } for background in std::mem::take(&mut prepaint.folded_lines.backgrounds) { window.paint_quad(background); @@ -4105,18 +4557,14 @@ impl Element for TextElement Element for TextElement Element for TextElement px(0.)).then(|| ContentMask { + bounds: editor_text_bounds( + window.content_mask().bounds, + gutter_bounds, + prepaint.last_layout.gutter_side, + ), + }); - line.paint_background( - p, - line_height, - prepaint.last_layout.content_width, - window, - cx, - ); + let cursor_row_y = window.with_content_mask(text_mask, |window| { + // Paint glyph backgrounds + // + // gpui's `paint` only draws glyphs, underlines, and strikethroughs, so decoration + // backgrounds need their own pass. It runs ahead of the indent guides, selections, + // and text so a highlighted range sits under them instead of covering them. + // + // Every row is painted where it is laid out: past the ghost lines + // and the spacers above it. + for (line, (top, _)) in prepaint + .last_layout + .lines + .iter() + .zip(prepaint.last_layout.row_extents()) + { + let p = point( + origin.x + prepaint.last_layout.text_origin_x + scroll_offset, + origin.y + top, + ); - row_offset += line.wrapped_lines.len() as isize; + line.paint_background( + p, + line_height, + prepaint.last_layout.content_width, + window, + cx, + ); + } - // Ghost lines shift every later line down. - if Some(buffer_line) == prepaint.current_row { - ghost_offset += prepaint.ghost_lines_height; + // Paint indent guides + if let Some(path) = prepaint.indent_guides_path.take() { + window.paint_path(path, editor_style.border.opacity(0.85)); } - } - // Paint indent guides - if let Some(path) = prepaint.indent_guides_path.take() { - window.paint_path(path, editor_style.border.opacity(0.85)); - } + // Application decorations sit below the user's selection. + for (path, color) in &prepaint.range_decoration_fills { + window.paint_path(path.clone(), *color); + } + for (path, color) in &prepaint.range_decoration_frames { + window.paint_path(path.clone(), *color); + } - // Application decorations sit below the user's selection. - for (path, color) in &prepaint.range_decoration_fills { - window.paint_path(path.clone(), *color); - } - for (path, color) in &prepaint.range_decoration_frames { - window.paint_path(path.clone(), *color); - } + // Paint selections + if window.is_window_active() { + let secondary_selection = Hsla { + s: 0.1, + ..editor_style.selection + }; + for (path, is_active) in prepaint.search_match_paths.iter() { + window.paint_path(path.clone(), secondary_selection); - // Paint selections - if window.is_window_active() { - let secondary_selection = Hsla { - s: 0.1, - ..editor_style.selection - }; - for (path, is_active) in prepaint.search_match_paths.iter() { - window.paint_path(path.clone(), secondary_selection); + if *is_active { + window.paint_path(path.clone(), editor_style.selection); + } + } - if *is_active { - window.paint_path(path.clone(), editor_style.selection); + for path in prepaint.selection_paths.drain(..) { + window.paint_path(path, editor_style.selection); } - } - for path in prepaint.selection_paths.drain(..) { - window.paint_path(path, editor_style.selection); + // Paint hover highlight + if let Some(path) = prepaint.hover_highlight_path.take() { + window.paint_path(path, secondary_selection); + } } - // Paint hover highlight - if let Some(path) = prepaint.hover_highlight_path.take() { - window.paint_path(path, secondary_selection); + // Paint document colors + for (path, color) in prepaint.document_color_paths.iter() { + let color = if disabled { color.opacity(0.5) } else { *color }; + window.paint_path(path.clone(), color); } - } - - // Paint document colors - for (path, color) in prepaint.document_color_paths.iter() { - let color = if disabled { color.opacity(0.5) } else { *color }; - window.paint_path(path.clone(), color); - } - // Paint text with inline completion ghost line support - let mut row_offset: isize = 0; - let mut ghost_offset = px(0.); - let ghost_lines = &prepaint.ghost_lines; - let has_ghost_lines = !ghost_lines.is_empty(); + // Paint text with inline completion ghost line support + let ghost_lines = &prepaint.ghost_lines; + let has_ghost_lines = !ghost_lines.is_empty(); - // Track the y-position of the cursor row for positioning the first line suffix - let mut cursor_row_y = None; + // Track the y-position of the cursor row for positioning the first line suffix + let mut cursor_row_y = None; - for (line, &buffer_line) in prepaint - .last_layout - .lines - .iter() - .zip(prepaint.last_layout.visible_buffer_lines.iter()) - { - let row = buffer_line; - let line_y = origin.y + prepaint.last_layout.local_row_y(row_offset) + ghost_offset; - let p = point( - origin.x + prepaint.last_layout.line_number_width + (scroll_offset), - line_y, - ); + for ((line, &buffer_line), (top, height)) in prepaint + .last_layout + .lines + .iter() + .zip(prepaint.last_layout.visible_buffer_lines.iter()) + .zip(prepaint.last_layout.row_extents()) + { + let row = buffer_line; + let line_y = origin.y + top; + let p = point( + origin.x + prepaint.last_layout.text_origin_x + (scroll_offset), + line_y, + ); - // Paint the actual line - line.paint( - p, - line_height, - prepaint.last_layout.content_width, - window, - cx, - ); - row_offset += line.wrapped_lines.len() as isize; + // Paint the actual line + line.paint( + p, + line_height, + prepaint.last_layout.content_width, + window, + cx, + ); + if Some(row) == prepaint.current_row { + cursor_row_y = Some(line_y); + } - if Some(row) == prepaint.current_row { - cursor_row_y = Some(line_y); - } + // After the cursor row, paint ghost lines (which shifts subsequent content down) + if has_ghost_lines && Some(row) == prepaint.current_row { + let ghost_x = origin.x + prepaint.last_layout.text_origin_x; + let mut ghost_y = line_y + height; - // After the cursor row, paint ghost lines (which shifts subsequent content down) - if has_ghost_lines && Some(row) == prepaint.current_row { - let ghost_x = origin.x + prepaint.last_layout.line_number_width; - let ghost_base_y = - origin.y + prepaint.last_layout.local_row_y(row_offset) + ghost_offset; + for ghost_line in ghost_lines { + let ghost_p = point(ghost_x, ghost_y); - for (ghost_ix, ghost_line) in ghost_lines.iter().enumerate() { - let ghost_p = point(ghost_x, ghost_base_y + line_height * (ghost_ix as f32)); + // Paint semi-transparent background for ghost line + let ghost_bounds = Bounds::new( + ghost_p, + size(prepaint.last_layout.text_width, line_height), + ); + window.paint_quad(fill(ghost_bounds, editor_background)); - // Paint semi-transparent background for ghost line - let ghost_bounds = Bounds::new( - ghost_p, - size( - bounds.size.width - prepaint.last_layout.line_number_width, + // Paint ghost line text + _ = ghost_line.paint( + ghost_p, line_height, - ), - ); - window.paint_quad(fill(ghost_bounds, editor_background)); + text_align, + Some(prepaint.last_layout.content_width), + window, + cx, + ); + ghost_y += line_height; + } + } + } - // Paint ghost line text - _ = ghost_line.paint( - ghost_p, - line_height, - text_align, - Some(prepaint.last_layout.content_width), - window, - cx, - ); - } - ghost_offset += line_height * (ghost_lines.len() as f32); + for element in &mut prepaint.token_elements { + element.paint(window, cx); + } + for placeholder in &mut prepaint.folded_lines.placeholders { + placeholder.paint(window, cx); } - } - - for element in &mut prepaint.token_elements { - element.paint(window, cx); - } - for placeholder in &mut prepaint.folded_lines.placeholders { - placeholder.paint(window, cx); - } - // Paint blinking cursors (shared blink state for all carets) - if focused && show_cursor { - for cursor_info in prepaint.cursor_infos_with_scroll() { - window.paint_quad(fill( - snap_caret_to_device_pixels(cursor_info.bounds, window.scale_factor()), - editor_style.caret, - )); + // Paint blinking cursors (shared blink state for all carets) + if focused && show_cursor { + for cursor_info in prepaint.cursor_infos_with_scroll() { + window.paint_quad(fill( + snap_caret_to_device_pixels(cursor_info.bounds, window.scale_factor()), + editor_style.caret, + )); + } } - } + + cursor_row_y + }); // Paint line numbers if let Some(line_numbers) = prepaint.line_numbers.as_ref() { - let mut row_offset: isize = 0; - let mut ghost_offset = px(0.); - - // The gutter is a fixed overlay above horizontally scrolling text. - // Always give it an opaque editor background when the theme does not - // provide a dedicated gutter color, and cover the complete gutter so - // text cannot show through its right-side spacing/fold-icon area. + // Give the gutter the editor background when the theme does not + // provide a dedicated gutter color, and cover the complete gutter. let gutter_bg = editor_style .editor_gutter_background .unwrap_or(editor_background); - let gutter_bounds = editor_gutter_bounds( - input_bounds, - prepaint.last_layout.line_number_width, - prepaint.ghost_lines_height, - editor_paddings, - ); window.paint_quad(fill(gutter_bounds, gutter_bg)); + // Repaint line decoration backgrounds over the gutter background. + for &(y, height, color) in &line_backgrounds { + window.paint_quad(fill( + Bounds::new( + point(gutter_bounds.origin.x, y), + size(gutter_bounds.size.width, height), + ), + color, + )); + } + let folding = self.state.read(cx).mode.is_folding(); - // Each item is the normal lines. - for ((line_no, rows), &buffer_line) in line_numbers + // Each item is the normal lines, numbered where its row is laid + // out, so a spacer row has no number. + for (((line_no, rows), &buffer_line), (top, _)) in line_numbers .iter() .zip(prepaint.last_layout.visible_buffer_lines.iter()) + .zip(prepaint.last_layout.row_extents()) { - let p = point( - input_bounds.origin.x, - origin.y + prepaint.last_layout.local_row_y(row_offset) + ghost_offset, - ); + let y = origin.y + top; let is_active = prepaint.current_row == Some(buffer_line); let height = line_height * *rows as f32; @@ -4342,7 +4797,7 @@ impl Element for TextElement Element for TextElement Element for TextElement Element for TextElement>>, + } + + impl Bands { + fn new(marker: bool) -> Rc { + Rc::new(Self { + marker, + asked: Default::default(), + }) + } + } + + impl crate::input::LineDecorationProvider for Bands { + fn line_decorations( + &self, + rows: Range, + _: &App, + ) -> Vec { + self.asked.borrow_mut().push(rows.clone()); + rows.map(|row| { + let decoration = + crate::input::LineDecoration::new(row).with_background(gpui::red()); + if self.marker { + decoration.with_marker(crate::input::GutterMarker::DiffAdded) + } else { + decoration + } + }) + .collect() + } + } + + /// Projects a gutter-marker renderer that counts the markers it builds. + fn count_markers(editor: &Entity, cx: &mut App) -> Rc> { + let built = Rc::new(std::cell::Cell::new(0)); + let counter = built.clone(); + editor.update(cx, |state, _| { + state.set_editor_style( + crate::input::InputEditorStyle::default() + .with_gutter_marker_renderer(Some(Rc::new(move |_| { + counter.set(counter.get() + 1); + div().into_any_element() + }))) + .with_gutter_marker_size(gpui::rems(0.75)) + .with_gutter_marker_gap(gpui::rems(0.25)), + ); + }); + built + } + + /// Projects a gutter-marker renderer whose markers record where they are laid out. + fn record_markers( + editor: &Entity, + cx: &mut App, + ) -> Rc>>> { + let laid_out = Rc::new(std::cell::RefCell::new(Vec::new())); + let record = laid_out.clone(); + editor.update(cx, |state, _| { + state.set_editor_style( + crate::input::InputEditorStyle::default() + .with_gutter_marker_renderer(Some(Rc::new(move |_| { + let record = record.clone(); + gpui::canvas( + move |bounds, _, _| record.borrow_mut().push(bounds), + |_, _, _, _| {}, + ) + .size(gpui::rems(0.75)) + .into_any_element() + }))) + .with_gutter_marker_size(gpui::rems(0.75)) + .with_gutter_marker_gap(gpui::rems(0.25)), + ); + }); + laid_out + } + + #[gpui::test] + fn line_decorations_are_asked_for_the_visible_rows_on_every_frame(cx: &mut TestAppContext) { + let (editor, window) = decoration_editor(cx, &"x\n".repeat(100), false); + let mut cx = VisualTestContext::from_window(window.into(), cx); + let bands = Bands::new(true); + cx.update(|window, cx| { + let built = count_markers(&editor, cx); + // Nothing attached: nothing to ask, nothing built. + window.draw(cx).clear(cx); + assert_eq!(built.get(), 0); + + editor.update(cx, |state, cx| { + state.create_line_decorations_collection(bands.clone(), cx); + }); + window.draw(cx).clear(cx); + let visible = editor.read(cx).visible_row_range().unwrap(); + assert_eq!(visible.start, 0); + assert!(visible.end < 100); + assert_eq!(*bands.asked.borrow(), vec![visible.clone()]); + assert_eq!(built.get(), visible.len()); + + // Every frame asks again, about the rows that frame shows. + editor.update(cx, |state, cx| { + let height = state.last_layout.as_ref().unwrap().line_height; + state.set_scroll_offset(point(px(0.), -height * 40.), cx); + }); + window.draw(cx).clear(cx); + window.draw(cx).clear(cx); + let scrolled = editor.read(cx).visible_row_range().unwrap(); + assert!(scrolled.start >= 39, "{scrolled:?}"); + assert_eq!(bands.asked.borrow().len(), 3); + assert_eq!(bands.asked.borrow().last(), Some(&scrolled)); + }); + } + + #[gpui::test] + fn gutter_markers_need_a_renderer_and_the_line_numbers(cx: &mut TestAppContext) { + let (editor, window) = decoration_editor(cx, "a\nb\nc", false); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.update(|window, cx| { + editor.update(cx, |state, cx| { + state.create_line_decorations_collection(Bands::new(true), cx); + }); + window.draw(cx).clear(cx); + + let built = count_markers(&editor, cx); + window.draw(cx).clear(cx); + assert_eq!(built.get(), 3); + + editor.update(cx, |state, cx| state.set_line_number(false, window, cx)); + window.draw(cx).clear(cx); + assert_eq!(built.get(), 3, "no gutter, no markers"); + }); + } + + #[gpui::test] + fn line_backgrounds_cover_the_bounds_of_their_rows(cx: &mut TestAppContext) { + // A soft-wrapped first row and a folded one: bands follow both. + let text = format!("{}\nshort\ntop\nhidden\nend\nlast", "word ".repeat(8)); + let (editor, window) = decoration_editor(cx, &text, true); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.update(|window, cx| { + editor.update(cx, |state, cx| { + state.apply_highlighter_fold_candidates(vec![FoldRange::new(2, 4)], cx); + state.display_map.set_folded(2, true); + state.create_line_decorations_collection(Bands::new(false), cx); + }); + window.draw(cx).clear(cx); + + let (layout, bounds, input_bounds) = { + let state = editor.read(cx); + ( + state.last_layout.clone().unwrap(), + state.last_bounds.unwrap(), + state.input_bounds, + ) + }; + assert!(layout.visible_buffer_lines.starts_with(&[0, 1, 2, 4])); + let decorations = TextElement::new(editor.clone()).layout_line_decorations( + input_bounds.origin.x, + &bounds, + &layout, + window, + cx, + ); + assert!(decorations.markers.is_empty(), "no renderer projected"); + // One band per laid-out row; none for the folded one. + assert_eq!( + decorations.backgrounds.len(), + layout.visible_buffer_lines.len() + ); + + let state = editor.read(cx); + for (&(top, height, _), &row) in decorations + .backgrounds + .iter() + .zip(&layout.visible_buffer_lines) + { + let row_bounds = state.row_bounds(row).unwrap(); + assert_eq!( + row_bounds.origin, + point(input_bounds.origin.x, bounds.origin.y + top) + ); + assert_eq!(row_bounds.size, size(input_bounds.size.width, height)); + } + assert!(decorations.backgrounds[0].1 > layout.line_height, "wrapped"); + }); + } + + #[gpui::test] + fn gutter_markers_have_a_slot_left_of_the_line_numbers(cx: &mut TestAppContext) { + // Three-digit numbers fill the narrowest column; longer ones widen it. + for rem_size in [16., 24., 32.] { + for (lines, widest) in [(150, 99), (1_200, 999)] { + let text = format!("{}\n{}", "wide ".repeat(80), "x\n".repeat(lines)); + let (editor, window) = decoration_editor(cx, &text, false); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.update(|window, cx| { + window.set_rem_size(px(rem_size)); + let laid_out = record_markers(&editor, cx); + let padding = px(6.); + editor.update(cx, |state, _| { + state.set_editor_paddings(Edges { + left: padding, + ..Default::default() + }); + }); + window.draw(cx).clear(cx); + let line_number_width = |cx: &App| { + editor + .read(cx) + .last_layout + .as_ref() + .unwrap() + .line_number_width + }; + let plain = line_number_width(cx); + + let collection = editor.update(cx, |state, cx| { + let height = state.last_layout.as_ref().unwrap().line_height; + state.set_scroll_offset(point(px(0.), -height * (lines - 4) as f32), cx); + state.create_line_decorations_collection(Bands::new(true), cx) + }); + window.draw(cx).clear(cx); + laid_out.borrow_mut().clear(); + window.draw(cx).clear(cx); + assert!(editor.read(cx).visible_row_range().unwrap().start > widest); + + // The numbers keep their right edge, so the growth is the slot. + let slot = line_number_width(cx) - plain; + let input_bounds = editor.read(cx).input_bounds; + let state = editor.read(cx); + let layout = state.last_layout.as_ref().unwrap(); + let row_centers = layout + .visible_buffer_lines + .iter() + .map(|&row| { + state.row_bounds(row).unwrap().top() + layout.line_height.half() + }) + .collect::>(); + let markers_x = || { + let markers = laid_out.borrow(); + assert!(!markers.is_empty()); + for marker in markers.iter() { + assert!( + marker.left() >= input_bounds.left() - padding + && marker.right() <= input_bounds.left() + slot, + "{marker:?} is not in the slot left of {lines} line numbers" + ); + assert!( + row_centers + .iter() + .any(|¢er| (marker.center().y - center).abs() < px(0.01)), + "{marker:?} is not centered on a row at rem {rem_size}" + ); + } + markers + .iter() + .map(|marker| marker.left()) + .collect::>() + }; + let unscrolled = markers_x(); + + // Scrolling horizontally moves the text, not the gutter. + laid_out.borrow_mut().clear(); + editor.update(cx, |state, cx| { + let offset = state.scroll_handle.offset(); + state.set_scroll_offset(point(px(-200.), offset.y), cx); + }); + window.draw(cx).clear(cx); + laid_out.borrow_mut().clear(); + window.draw(cx).clear(cx); + assert!(editor.read(cx).scroll_handle.offset().x < px(0.)); + assert_eq!(markers_x()[..unscrolled.len()], unscrolled[..]); + + // Without a provider there is no slot. + collection.clear(cx); + window.draw(cx).clear(cx); + assert_eq!(line_number_width(cx), plain); + }); + } + } + } + + #[gpui::test] + fn gutter_markers_keep_to_the_outer_edge_of_a_right_gutter(cx: &mut TestAppContext) { + let (editor, window) = decoration_editor(cx, &"x\n".repeat(20), false); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.update(|window, cx| { + let laid_out = record_markers(&editor, cx); + editor.update(cx, |state, cx| { + state.set_gutter_side(Side::Right, cx); + state.create_line_decorations_collection(Bands::new(true), cx); + }); + window.draw(cx).clear(cx); + laid_out.borrow_mut().clear(); + window.draw(cx).clear(cx); + + let state = editor.read(cx); + let layout = state.last_layout.as_ref().unwrap(); + let input_bounds = state.input_bounds; + let slot = layout.gutter_marker_width; + assert!(slot > px(0.)); + let (numbers_x, _) = gutter_column(layout, true, GutterColumn::LineNumbers); + assert_eq!( + numbers_x, + layout.gutter_origin_x + LINE_NUMBER_RIGHT_MARGIN + FOLD_ICON_HITBOX_WIDTH + ); + let markers = laid_out.borrow(); + assert!(!markers.is_empty()); + for marker in markers.iter() { + assert!( + marker.left() >= input_bounds.right() - slot, + "{marker:?} is not in the slot right of the line numbers" + ); + assert!( + (marker.right() - input_bounds.right()).abs() < px(0.01), + "{marker:?} is not at the outer edge" + ); + } + drop(markers); + + // On the left, the line numbers follow the slot. + editor.update(cx, |state, cx| state.set_gutter_side(Side::Left, cx)); + window.draw(cx).clear(cx); + let layout = editor.read(cx).last_layout.clone().unwrap(); + assert_eq!( + gutter_column(&layout, true, GutterColumn::LineNumbers).0, + layout.gutter_marker_width + ); + }); + } + + #[gpui::test] + fn rows_below_a_multiline_inline_completion_are_bounded_where_painted(cx: &mut TestAppContext) { + let (editor, window) = decoration_editor(cx, "one\ntwo\nthree\nfour", false); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.update(|window, cx| { + editor.update(cx, |state, cx| { + state.create_line_decorations_collection(Bands::new(false), cx); + state.set_cursor_position(lsp_types::Position::new(0, 3), window, cx); + }); + window.draw(cx).clear(cx); + let before: Vec<_> = (0..4) + .map(|row| editor.read(cx).row_bounds(row).unwrap()) + .collect(); + let version = editor.read(cx).display_map().version(); + + // Two ghost lines follow the cursor row. + editor.update(cx, |state, cx| { + state.extras.inline_completion.item = Some(lsp_types::InlineCompletionItem { + insert_text: "\nghost\nghost".into(), + filter_text: None, + range: None, + command: None, + insert_text_format: None, + }); + cx.notify(); + }); + window.draw(cx).clear(cx); + + let (layout, bounds, input_bounds) = { + let state = editor.read(cx); + let map = state.display_map(); + assert_eq!(map.version(), version); + assert_eq!(map.display_row_count(), 4); + assert_eq!(map.buffer_line_to_display_row_range(2), Some(2..3)); + ( + state.last_layout.clone().unwrap(), + state.last_bounds.unwrap(), + state.input_bounds, + ) + }; + let ghost = layout.line_height * 2.; + assert_eq!(editor.read(cx).row_bounds(0), Some(before[0])); + for row in 1..4 { + let bounds = editor.read(cx).row_bounds(row).unwrap(); + assert_eq!(bounds.origin.y, before[row].origin.y + ghost, "row {row}"); + assert_eq!(bounds.size, before[row].size); + } + + // Backgrounds are laid out over the same rows. + let decorations = TextElement::new(editor.clone()).layout_line_decorations( + input_bounds.origin.x, + &bounds, + &layout, + window, + cx, + ); + for (&(top, height, _), row) in decorations.backgrounds.iter().zip(0..4) { + let row_bounds = editor.read(cx).row_bounds(row).unwrap(); + assert_eq!(row_bounds.origin.y, bounds.origin.y + top); + assert_eq!(row_bounds.size.height, height); + } + }); + } + #[gpui::test] fn a_tab_indicator_is_clipped_to_its_tab(cx: &mut TestAppContext) { cx.update(crate::init); @@ -5863,40 +6714,721 @@ mod tests { } #[gpui::test] - fn gutter_typography_updates_wrapping_scrollbars_and_pointer_coordinates( - cx: &mut TestAppContext, - ) { - let assert_widths_match = |actual: Pixels, expected: Pixels| { - // Bounds widths subtract absolute f32 coordinates, so moving the - // gutter can change rounding even when glyph metrics are unchanged. - // A 0.001px floor covers that cancellation while still rejecting - // changes large enough to affect the editor's visible geometry. - let tolerance = - (actual.abs().max(expected.abs()).max(px(1.)) * (4. * f32::EPSILON)).max(px(0.001)); + fn row_bounds_cover_soft_wrapped_rows_that_are_laid_out(cx: &mut TestAppContext) { + let text = format!( + "{}\nshort\ntop\nhidden\nend\n{}", + "word ".repeat(8), + "x\n".repeat(60) + ); + let (editor, window) = decoration_editor(cx, &text, true); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.update(|window, cx| { + let unpainted = cx.new(|cx| EditorState::new(window, cx).default_value("a")); assert!( - (actual - expected).abs() <= tolerance, - "{actual:?} != {expected:?} (roundoff tolerance: {tolerance:?})", + unpainted.read(cx).row_bounds(0).is_none(), + "nothing laid out" ); - }; - let (editor, window) = decoration_editor(cx, &"hello world ".repeat(40), true); - let mut cx = VisualTestContext::from_window(window.into(), cx); - let (baseline_width, baseline_wrap, body_height, body_glyph_width) = - cx.update(|window, cx| { - editor.update(cx, |state, cx| state.set_selected_range(0..0, cx)); - window.draw(cx).clear(cx); + editor.update(cx, |state, cx| { + state.apply_highlighter_fold_candidates(vec![FoldRange::new(2, 4)], cx); + state.display_map.set_folded(2, true); + cx.notify(); + }); + window.draw(cx).clear(cx); + { let state = editor.read(cx); let layout = state.last_layout.as_ref().unwrap(); - ( - layout.line_number_width, - layout.wrap_width.unwrap(), - layout.line_height, - state.range_to_bounds(&(0..1)).unwrap().size.width, - ) - }); - - let mut previous: Option<(Pixels, Pixels, Pixels, Bounds)> = None; - for gap in [px(0.), px(12.), px(24.), px(0.)] { + let wrapped = state.row_bounds(0).unwrap(); + assert_eq!( + wrapped.origin, + point( + state.input_bounds.origin.x, + state.last_bounds.unwrap().origin.y + layout.visible_top + ) + ); + assert_eq!(wrapped.size.width, state.input_bounds.size.width); + assert!(wrapped.size.height > layout.line_height, "{wrapped:?}"); + + let next = state.row_bounds(1).unwrap(); + assert_eq!(next.origin.y, wrapped.bottom()); + assert_eq!(next.size.height, layout.line_height); + assert!(state.row_bounds(3).is_none(), "folded away"); + assert_eq!( + state.row_bounds(4).unwrap().origin.y, + state.row_bounds(2).unwrap().bottom() + ); + } + + editor.update(cx, |state, cx| { + let height = state.last_layout.as_ref().unwrap().line_height; + state.set_scroll_offset(point(px(0.), -height * 30.), cx); + }); + // Deferred scroll is committed by prepaint and reflected next frame. + window.draw(cx).clear(cx); + window.draw(cx).clear(cx); + let state = editor.read(cx); + let visible = state.visible_row_range().unwrap(); + assert!(state.row_bounds(0).is_none(), "scrolled out of view"); + assert!(state.row_bounds(visible.start + 1).is_some()); + }); + } + + #[gpui::test] + fn the_display_row_map_is_what_the_layout_draws(cx: &mut TestAppContext) { + // A soft-wrapped first line, a folded one, and a last line that wraps + // as the first does but is never laid out. + let text = format!( + "{}\nshort\ntop\nhidden\nend\n{}{}", + "word ".repeat(8), + "x\n".repeat(40), + "word ".repeat(8) + ); + let last = 45; + let (editor, window) = decoration_editor(cx, &text, true); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.update(|window, cx| { + let unpainted = cx.new(|cx| EditorState::new(window, cx).default_value("a\nb")); + assert_eq!( + unpainted.read(cx).display_map().display_row_count(), + 0, + "nothing laid out" + ); + + editor.update(cx, |state, cx| { + state.apply_highlighter_fold_candidates(vec![FoldRange::new(2, 4)], cx); + state.display_map.set_folded(2, true); + cx.notify(); + }); + window.draw(cx).clear(cx); + { + let state = editor.read(cx); + let line_height = state.line_height().unwrap(); + let map: &crate::input::DisplayMap = state.display_map(); + assert!(map.buffer_line_to_display_row_range(3).is_none()); + for line in [0, 1, 2, 4, last] { + let point = crate::input::BufferPoint::new(line, 0); + let display = map.buffer_pos_to_display_pos(point); + assert_eq!(map.display_pos_to_buffer_pos(display), point); + } + let wrapped = state + .display_map() + .buffer_line_to_display_row_range(0) + .unwrap(); + assert_eq!(wrapped.start, 0); + assert!(wrapped.len() > 1, "{wrapped:?}"); + assert_eq!( + state.row_bounds(0).unwrap().size.height, + line_height * wrapped.len() as f32 + ); + assert_eq!( + state + .display_map() + .buffer_line_to_display_row_range(1) + .unwrap(), + wrapped.end..wrapped.end + 1 + ); + let top = state + .display_map() + .buffer_line_to_display_row_range(2) + .unwrap(); + assert_eq!( + state + .display_map() + .buffer_line_to_display_row_range(4) + .unwrap() + .start, + top.end + ); + + let below = state + .display_map() + .buffer_line_to_display_row_range(last) + .unwrap(); + assert_eq!(below.len(), wrapped.len()); + assert_eq!(below.end, map.display_row_count()); + assert!(state.row_bounds(last).is_none(), "not laid out"); + + for line in [0, 1, 2, 4, 5, last] { + for row in map.buffer_line_to_display_row_range(line).unwrap() { + assert_eq!(map.display_row_to_buffer_line(row), line); + } + } + assert!(map.buffer_line_to_display_row_range(last + 1).is_none()); + } + + // Laid out at last, the line takes the rows the map gave it. A + // scroll moves no row, so the version stays. + let version = editor.read(cx).display_map().version(); + editor.update(cx, |state, cx| { + state.set_scroll_offset(point(px(0.), px(-10_000.)), cx); + }); + window.draw(cx).clear(cx); + window.draw(cx).clear(cx); + { + let state = editor.read(cx); + assert_eq!(state.display_map().version(), version); + let line_height = state.line_height().unwrap(); + let below = state + .display_map() + .buffer_line_to_display_row_range(last) + .unwrap(); + let bounds = state.row_bounds(last).unwrap(); + assert_eq!(bounds.size.height, line_height * below.len() as f32); + assert_eq!( + bounds.origin.y - state.last_bounds.unwrap().origin.y - state.scroll_offset().y, + line_height * below.start as f32 + ); + } + + // Without soft wrap every line is one row, and the version moved. + editor.update(cx, |state, cx| state.set_soft_wrap(false, window, cx)); + window.draw(cx).clear(cx); + { + let state = editor.read(cx); + assert_ne!(state.display_map().version(), version); + assert_eq!( + state + .display_map() + .buffer_line_to_display_row_range(0) + .unwrap(), + 0..1 + ); + assert_eq!(state.display_map().display_row_to_buffer_line(5), 6); + } + + // So does opening a fold, and an edit. + let version = editor.read(cx).display_map().version(); + editor.update(cx, |state, cx| { + state.display_map.set_folded(2, false); + cx.notify(); + }); + assert_ne!(editor.read(cx).display_map().version(), version); + let version = editor.read(cx).display_map().version(); + editor.update(cx, |state, cx| state.insert("x", window, cx)); + assert_ne!(editor.read(cx).display_map().version(), version); + }); + } + + /// Hands out the spacers it holds, and counts how often it was asked. + #[derive(Default)] + struct HeldSpacers { + spacers: std::cell::RefCell>, + asked: std::cell::Cell, + } + + impl crate::input::SpacerProvider for HeldSpacers { + fn spacers(&self, lines: Range, _: &App) -> Vec { + self.asked.set(self.asked.get() + 1); + self.spacers + .borrow() + .iter() + .filter(|spacer| lines.contains(&spacer.line())) + .cloned() + .collect() + } + } + + /// Five short lines, the second long enough to wrap when `wrap` is on, then + /// twenty more and an empty one; padded by `spacers`. + fn spaced_editor( + cx: &mut TestAppContext, + wrap: bool, + spacers: Vec, + ) -> ( + Entity, + gpui::WindowHandle, + Rc, + ) { + let text = format!( + "one\n{}\nthree\nfour\nfive\n{}", + "word ".repeat(8), + "x\n".repeat(20) + ); + let (editor, window) = decoration_editor(cx, &text, wrap); + let held = Rc::new(HeldSpacers::default()); + *held.spacers.borrow_mut() = spacers; + cx.update(|cx| { + editor.update(cx, |state, cx| { + state.set_spacer_provider(Some(held.clone()), cx); + }); + }); + (editor, window, held) + } + + /// The display row a laid-out caret or element stands on. + fn row_at(state: &EditorState, y: Pixels) -> usize { + let layout = state.last_layout.as_ref().unwrap(); + let top = state.last_bounds.unwrap().origin.y + state.scroll_offset().y; + ((y - top) / layout.line_height).floor() as usize + } + + /// The display rows of a visible line's text. + fn text_rows(state: &EditorState, line: usize) -> Range { + state + .display_map() + .buffer_line_to_display_row_range(line) + .unwrap() + } + + #[gpui::test] + fn spacer_rows_are_display_rows_that_push_every_row_below_them(cx: &mut TestAppContext) { + use crate::input::{BufferPoint, DisplayPoint, Spacer}; + for wrap in [false, true] { + let (editor, window, _) = spaced_editor( + cx, + wrap, + vec![ + Spacer::above(0, 1), + Spacer::below(0, 2), + Spacer::below(1, 3), + Spacer::below(25, 4), + ], + ); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.update(|window, cx| { + window.draw(cx).clear(cx); + let (line_height, wrapped, starts, scroll_height) = { + let state = editor.read(cx); + let line_height = state.line_height().unwrap(); + let wrapped = text_rows(state, 1).len(); + assert_eq!(wrapped > 1, wrap); + assert_eq!(state.display_map().display_row_count(), 25 + wrapped + 10); + let starts: Vec = + (0..5).map(|line| text_rows(state, line).start).collect(); + assert_eq!(starts, [1, 4, 7 + wrapped, 8 + wrapped, 9 + wrapped]); + for row in 0..state.display_map().display_row_count() + 2 { + let spacer = [0, 2, 3].contains(&row) + || (4 + wrapped..7 + wrapped).contains(&row) + || (31 + wrapped..35 + wrapped).contains(&row); + assert_eq!( + state.display_map().is_spacer_row(row), + spacer, + "row {row}, wrap {wrap}" + ); + } + let map = state.display_map(); + assert_eq!(map.display_row_to_buffer_line(0), 0); + assert_eq!(map.display_row_to_buffer_line(3), 0); + assert_eq!(map.display_row_to_buffer_line(6 + wrapped), 1); + let last_row = map.display_pos_to_buffer_pos(DisplayPoint::new(3 + wrapped, 0)); + assert_eq!( + map.display_pos_to_buffer_pos(DisplayPoint::new(6 + wrapped, 0)), + last_row + ); + assert_eq!( + map.display_pos_to_buffer_pos(DisplayPoint::new(0, 0)), + BufferPoint::new(0, 0) + ); + + // Every laid-out row is drawn at its display row, its height its own. + let top = state.last_bounds.unwrap().origin.y; + let laid_out = &state.last_layout.as_ref().unwrap().visible_buffer_lines; + assert!(laid_out.contains(&1)); + for &line in laid_out { + let start = text_rows(state, line).start; + let bounds = state.row_bounds(line).unwrap(); + assert_eq!(bounds.origin.y - top, line_height * start); + assert_eq!( + bounds.size.height, + line_height * text_rows(state, line).len() + ); + } + (line_height, wrapped, starts, state.scroll_size.height) + }; + + // The caret on the last line is scrolled into view past every spacer. + editor.update(cx, |state, cx| { + state.set_cursor_position(Position::new(25, 0), window, cx); + }); + window.draw(cx).clear(cx); + window.draw(cx).clear(cx); + { + // The caret is laid out where it is painted. + let state = editor.read(cx); + let caret = state.last_layout.as_ref().unwrap().cursor_bounds.unwrap(); + let shown = caret.center(); + assert!(state.input_bounds.contains(&shown), "{caret:?}"); + assert_eq!(row_at(state, shown.y), 30 + wrapped); + } + + // Without the provider the rows close up, and the scroll height + // is ten rows shorter. + editor.update(cx, |state, cx| state.set_spacer_provider(None, cx)); + window.draw(cx).clear(cx); + let state = editor.read(cx); + assert_eq!(state.display_map().display_row_count(), 25 + wrapped); + assert_eq!(text_rows(state, 1).start, starts[1] - 3); + assert_eq!(scroll_height - state.scroll_size.height, line_height * 10); + }); + } + } + + #[gpui::test] + fn a_spacer_background_stays_on_its_rows_when_scrolled(cx: &mut TestAppContext) { + use crate::input::Spacer; + let color = gpui::hsla(0., 1., 0.5, 1.); + let (editor, window, _) = + spaced_editor(cx, false, vec![Spacer::below(1, 2).with_background(color)]); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.update(|window, cx| { + for scroll in [px(0.), px(-30.)] { + editor.update(cx, |state, cx| { + state.set_scroll_offset(point(px(0.), scroll), cx) + }); + window.draw(cx).clear(cx); + let state = editor.read(cx); + assert_eq!(state.scroll_offset().y, scroll); + let layout = state.last_layout.as_ref().unwrap(); + let rows = state + .display_map + .spacer_backgrounds(0..state.display_map.buffer_line_count()) + .collect(); + let placed = place_spacer_backgrounds(layout, rows, None); + let top = state.row_bounds(1).unwrap().bottom() - state.last_bounds.unwrap().top(); + assert_eq!(placed, [(top, layout.line_height * 2, color)], "{scroll:?}"); + } + }); + } + + #[gpui::test] + fn the_caret_and_a_click_never_stand_on_a_spacer_row(cx: &mut TestAppContext) { + use crate::input::{MoveDown, MoveUp, Spacer}; + for wrap in [false, true] { + let (editor, window, _) = spaced_editor( + cx, + wrap, + vec![ + Spacer::below(0, 2), + Spacer::above(1, 1), + Spacer::below(25, 3), + ], + ); + let mut cx = VisualTestContext::from_window(window.into(), cx); + let (above_one, below_zero) = cx.update(|window, cx| { + window.draw(cx).clear(cx); + let wrapped = text_rows(editor.read(cx), 1).len(); + let line = |editor: &Entity, cx: &App| { + editor.read(cx).cursor_position().line as usize + }; + + editor.update(cx, |state, cx| { + state.set_cursor_position(Position::new(0, 1), window, cx); + state.down(&MoveDown, window, cx); + }); + assert_eq!(line(&editor, cx), 1, "past the rows between lines 0 and 1"); + window.draw(cx).clear(cx); + { + let state = editor.read(cx); + let caret = state.last_layout.as_ref().unwrap().cursor_bounds.unwrap(); + assert_eq!(row_at(state, caret.center().y), 4); + } + for _ in 0..wrapped { + editor.update(cx, |state, cx| state.down(&MoveDown, window, cx)); + } + assert_eq!(line(&editor, cx), 2); + editor.update(cx, |state, cx| state.up(&MoveUp, window, cx)); + assert_eq!(line(&editor, cx), 1); + for _ in 0..wrapped { + editor.update(cx, |state, cx| state.up(&MoveUp, window, cx)); + } + assert_eq!(line(&editor, cx), 0); + + // Down from the last line, with spacers below it, stays on it. + editor.update(cx, |state, cx| { + state.set_cursor_position(Position::new(25, 0), window, cx); + state.down(&MoveDown, window, cx); + }); + assert_eq!(line(&editor, cx), 25); + + // A block selection takes the rows of text and none of the spacers. + if !wrap { + editor.update(cx, |state, cx| { + state.build_columnar_selection( + crate::input::state::ColumnarPoint::new(1, 0), + crate::input::state::ColumnarPoint::new(6, 0), + cx, + ); + let ranges: Vec<_> = + state.selections.iter().map(|s| (s.start, s.end)).collect(); + assert_eq!(ranges, vec![(1, 2), (5, 6)]); + }); + } + + editor.update(cx, |state, cx| { + state.set_cursor_position(Position::new(0, 0), window, cx); + }); + window.draw(cx).clear(cx); + let state = editor.read(cx); + let layout = state.last_layout.as_ref().unwrap(); + let origin = state.last_bounds.unwrap().origin; + // The x of the third character of a line, on the row `row`. + let at = |line: usize, row: f32| { + let x = layout.text_origin_x + + layout + .line(line) + .unwrap() + .position_for_index(2, layout, false) + .unwrap() + .x; + origin + point(x, layout.line_height * row) + }; + (at(1, 3.5), at(0, 1.5)) + }); + + // A click on a spacer row is a click on the row of text beside it. + cx.simulate_click(below_zero, gpui::Modifiers::default()); + editor.read_with(&cx, |state, _| { + assert_eq!(state.selected_range(), 2..2, "wrap {wrap}"); + }); + cx.simulate_click(above_one, gpui::Modifiers::default()); + editor.read_with(&cx, |state, _| { + assert_eq!(state.selected_range(), 6..6, "wrap {wrap}"); + }); + } + } + + #[gpui::test] + fn bands_markers_and_fold_icons_stand_on_text_rows_only(cx: &mut TestAppContext) { + use crate::input::Spacer; + for wrap in [false, true] { + let (editor, window, _) = spaced_editor( + cx, + wrap, + vec![ + Spacer::below(0, 2).with_background(gpui::blue()), + Spacer::above(2, 1), + Spacer::below(2, 1), + ], + ); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.update(|window, cx| { + let markers = record_markers(&editor, cx); + let icons = record_fold_icons(&editor, cx); + editor.update(cx, |state, cx| { + state.apply_highlighter_fold_candidates(vec![FoldRange::new(2, 4)], cx); + state.create_line_decorations_collection(Bands::new(true), cx); + }); + window.draw(cx).clear(cx); + let state = editor.read(cx); + let layout = state.last_layout.as_ref().unwrap(); + let line_height = layout.line_height; + let top = state.last_bounds.unwrap().origin.y; + let start = |line| text_rows(state, line).start; + + // A band and a marker for every laid-out line, on its first text row. + let tops: Vec = markers + .borrow() + .iter() + .map(|marker| { + ((marker.center().y - top - line_height.half()) / line_height).round() + as usize + }) + .collect(); + let expected: Vec = layout + .visible_buffer_lines + .iter() + .map(|&line| start(line)) + .collect(); + assert_eq!(tops, expected, "wrap {wrap}"); + for (ix, (band_top, height)) in layout.row_extents().enumerate() { + let line = layout.visible_buffer_lines[ix]; + assert_eq!(band_top, line_height * start(line)); + assert_eq!(height, line_height * text_rows(state, line).len()); + } + + // The fold icon of line 2 is on its row, not on the spacer above it. + let icon = *icons.borrow().first().expect("a fold icon is laid out"); + assert_eq!(row_at(state, icon.center().y), start(2)); + + // A spacer's background covers its rows and nothing else. + let backgrounds: Vec<_> = state.display_map.spacer_backgrounds(0..26).collect(); + assert_eq!(backgrounds, vec![(1..3, gpui::blue())]); + assert_eq!(start(1), 3); + }); + } + } + + #[gpui::test] + fn ranges_are_laid_out_on_text_rows_only(cx: &mut TestAppContext) { + use crate::input::Spacer; + for wrap in [false, true] { + let (editor, window, _) = spaced_editor( + cx, + wrap, + vec![ + Spacer::above(0, 1), + Spacer::below(1, 2), + Spacer::above(2, 1), + ], + ); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.update(|window, cx| { + window.draw(cx).clear(cx); + let state = editor.read(cx); + let layout = state.last_layout.as_ref().unwrap(); + // From the middle of line 0 to the middle of line 2: a selection, a + // search match and a colour box are all laid out this way. + let end = state.text.line_start_offset(2) + 3; + let corners = + TextElement::::layout_range_corners(&(1..end), layout).unwrap(); + let rows: Vec = corners + .iter() + .map(|corners| (corners.top_left.y / layout.line_height).round() as usize) + .collect(); + let expected: Vec = [0, 1, 2] + .into_iter() + .flat_map(|line| text_rows(state, line)) + .collect(); + assert_eq!(rows, expected, "wrap {wrap}"); + assert!( + rows.iter() + .all(|&row| !state.display_map().is_spacer_row(row)) + ); + assert_eq!(rows[0], 1); + }); + } + } + + #[gpui::test] + fn spacers_beside_a_right_gutter_and_a_left_scroll_bar(cx: &mut TestAppContext) { + use crate::input::Spacer; + let (editor, window, _) = spaced_editor(cx, true, vec![Spacer::below(0, 3)]); + let mut cx = VisualTestContext::from_window(window.into(), cx); + let in_text = cx.update(|window, cx| { + let markers = record_markers(&editor, cx); + editor.update(cx, |state, cx| { + state.set_gutter_side(Side::Right, cx); + state.set_scrollbar_placement(ScrollbarPlacement::BottomLeft, cx); + state.create_line_decorations_collection(Bands::new(true), cx); + }); + window.draw(cx).clear(cx); + let state = editor.read(cx); + let layout = state.last_layout.as_ref().unwrap(); + let marker = markers.borrow()[1]; + assert!(marker.left() > state.input_bounds.left() + layout.text_width); + assert_eq!(row_at(state, marker.center().y), 4); + let x = layout.text_origin_x + + layout.lines[1] + .position_for_index(2, layout, false) + .unwrap() + .x; + state.last_bounds.unwrap().origin + point(x, layout.line_height * 4.5) + }); + cx.simulate_click(in_text, gpui::Modifiers::default()); + editor.read_with(&cx, |state, _| { + assert_eq!(state.selected_range(), 6..6); + }); + } + + #[gpui::test] + fn spacers_are_asked_for_when_the_rows_move(cx: &mut TestAppContext) { + use crate::input::Spacer; + let (editor, window, held) = spaced_editor( + cx, + true, + vec![ + Spacer::below(1, 2), + Spacer::below(3, 5), + Spacer::below(40, 9), + ], + ); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.update(|window, cx| { + window.draw(cx).clear(cx); + assert_eq!(held.asked.get(), 1); + // Line 40 does not exist. + assert_eq!(editor.read(cx).display_map.spacer_row_count(), 7); + + // A frame, or a scroll, moves no row. + window.draw(cx).clear(cx); + editor.update(cx, |state, cx| { + state.set_scroll_offset(point(px(0.), px(-40.)), cx); + }); + window.draw(cx).clear(cx); + assert_eq!(held.asked.get(), 1); + + // An edit, a rewrap, a fold and a refresh do. The spacers are placed + // again at once, before the provider is asked: a line that now wraps + // to more rows has no spacer inside it. + editor.update(cx, |state, cx| { + state.set_cursor_position(Position::new(1, 0), window, cx); + state.insert("more ".repeat(8), window, cx); + }); + { + let state = editor.read(cx); + assert_eq!( + text_rows(state, 1).len(), + state.display_map.visible_wrap_row_count_for_buffer_line(1) + ); + assert!(text_rows(state, 1).len() > 2); + } + window.draw(cx).clear(cx); + assert_eq!(held.asked.get(), 2); + editor.update(cx, |state, cx| state.set_soft_wrap(false, window, cx)); + window.draw(cx).clear(cx); + assert_eq!(held.asked.get(), 3); + editor.update(cx, |state, cx| { + state.apply_highlighter_fold_candidates(vec![FoldRange::new(2, 4)], cx); + state.display_map.set_folded(2, true); + cx.notify(); + }); + window.draw(cx).clear(cx); + assert_eq!(held.asked.get(), 4); + // Line 3 is folded away, and its spacers with it. + assert_eq!(editor.read(cx).display_map.spacer_row_count(), 2); + // The same answer leaves the version; cached rows stay valid. + let version = editor.read(cx).display_map().version(); + editor.update(cx, |state, cx| state.refresh_spacers(cx)); + window.draw(cx).clear(cx); + assert_eq!(held.asked.get(), 5); + assert_eq!(editor.read(cx).display_map().version(), version); + + // A different one moves it, without asking the provider anew. + *held.spacers.borrow_mut() = vec![Spacer::below(1, 4)]; + editor.update(cx, |state, cx| state.refresh_spacers(cx)); + window.draw(cx).clear(cx); + window.draw(cx).clear(cx); + assert_eq!(held.asked.get(), 6); + assert_ne!(editor.read(cx).display_map().version(), version); + assert_eq!(editor.read(cx).display_map.spacer_row_count(), 4); + }); + } + + #[gpui::test] + fn gutter_typography_updates_wrapping_scrollbars_and_pointer_coordinates( + cx: &mut TestAppContext, + ) { + let assert_widths_match = |actual: Pixels, expected: Pixels| { + // Bounds widths subtract absolute f32 coordinates, so moving the + // gutter can change rounding even when glyph metrics are unchanged. + // A 0.001px floor covers that cancellation while still rejecting + // changes large enough to affect the editor's visible geometry. + let tolerance = + (actual.abs().max(expected.abs()).max(px(1.)) * (4. * f32::EPSILON)).max(px(0.001)); + assert!( + (actual - expected).abs() <= tolerance, + "{actual:?} != {expected:?} (roundoff tolerance: {tolerance:?})", + ); + }; + + let (editor, window) = decoration_editor(cx, &"hello world ".repeat(40), true); + let mut cx = VisualTestContext::from_window(window.into(), cx); + let (baseline_width, baseline_wrap, body_height, body_glyph_width) = + cx.update(|window, cx| { + editor.update(cx, |state, cx| state.set_selected_range(0..0, cx)); + window.draw(cx).clear(cx); + let state = editor.read(cx); + let layout = state.last_layout.as_ref().unwrap(); + ( + layout.line_number_width, + layout.wrap_width.unwrap(), + layout.line_height, + state.range_to_bounds(&(0..1)).unwrap().size.width, + ) + }); + + let mut previous: Option<(Pixels, Pixels, Pixels, Bounds)> = None; + for gap in [px(0.), px(12.), px(24.), px(0.)] { window .update(&mut cx, |view, _, cx| { view.1 = Some(gap); @@ -5908,131 +7440,941 @@ mod tests { window.draw(cx).clear(cx); let state = editor.read(cx); let layout = state.last_layout.as_ref().unwrap(); - assert_eq!(layout.line_height, body_height); - assert_widths_match( - state.range_to_bounds(&(0..1)).unwrap().size.width, - body_glyph_width, + assert_eq!(layout.line_height, body_height); + assert_widths_match( + state.range_to_bounds(&(0..1)).unwrap().size.width, + body_glyph_width, + ); + assert!(layout.line_number_width > baseline_width); + assert!(layout.wrap_width.unwrap() < baseline_wrap); + + let column_width = layout.line_number_width - gap - FOLD_ICON_HITBOX_WIDTH; + let mut number_style = TextStyle::default(); + number_style.font_family = ".SystemUIFont".into(); + // Assert actual painted labels fit, rather than assuming a + // punctuation glyph represents this font's digit advances. + for number in ["1", "10", "123", "444", "888", "999"] { + let number = window.text_system().shape_line( + number.into(), + px(32.), + &[number_style.to_run(number.len())], + None, + ); + assert_widths_match(column_width.max(number.width), column_width); + } + + let caret = state.prepaint_caret_geometry().unwrap().cursor_bounds(); + ( + column_width, + layout.wrap_width.unwrap(), + state.editor_scrollbar_snapshot.get().unwrap().layout.bounds, + point(caret.left() + px(1.), caret.center().y), + ) + }); + + if let Some((previous_gap, previous_column, previous_wrap, previous_scrollbar)) = + previous + { + // A new gap changes wrapping, but the number/folding lane and + // scrollbar origin must not drift along with the blank space. + assert_widths_match(column_width, previous_column); + assert_widths_match(wrap_width + gap, previous_wrap + previous_gap); + assert_widths_match(scrollbar_bounds.origin.x, previous_scrollbar.origin.x); + assert_widths_match(scrollbar_bounds.size.width, previous_scrollbar.size.width); + assert_eq!(scrollbar_bounds.origin.y, previous_scrollbar.origin.y); + assert_eq!(scrollbar_bounds.size.height, previous_scrollbar.size.height); + } + previous = Some((gap, column_width, wrap_width, scrollbar_bounds)); + + cx.simulate_click(click_position, gpui::Modifiers::default()); + editor.read_with(&cx, |state, _| assert_eq!(state.selected_range(), 0..0)); + } + + window + .update(&mut cx, |view, _, cx| { + view.1 = Some(px(12.)); + cx.notify(); + }) + .unwrap(); + cx.update(|window, cx| { + editor.update(cx, |state, cx| { + state.set_line_number(false, window, cx); + }); + window.draw(cx).clear(cx); + assert_eq!( + editor + .read(cx) + .last_layout + .as_ref() + .unwrap() + .line_number_width, + px(12.) + FOLD_ICON_HITBOX_WIDTH, + ); + editor.update(cx, |state, cx| state.set_folding(false, window, cx)); + window.draw(cx).clear(cx); + assert_eq!( + editor + .read(cx) + .last_layout + .as_ref() + .unwrap() + .line_number_width, + px(12.) + ); + }); + } + + #[gpui::test] + fn custom_gutter_gaps_keep_reordered_columns_and_hit_testing_aligned(cx: &mut TestAppContext) { + let (editor, window) = decoration_editor(cx, "a\n b\nc", false); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.update(|_, cx| { + count_markers(&editor, cx); + editor.update(cx, |state, cx| { + state.apply_highlighter_fold_candidates(vec![FoldRange::new(0, 1)], cx); + state.create_line_decorations_collection(Bands::new(true), cx); + }); + }); + for gap in [px(0.), px(12.), px(24.)] { + window + .update(&mut cx, |view, _, cx| { + view.1 = Some(gap); + cx.notify(); + }) + .unwrap(); + cx.update(|window, cx| { + for side in [Side::Left, Side::Right] { + for order in GUTTER_ORDERS { + editor.update(cx, |state, cx| { + state.set_gutter_side(side, cx); + state.set_gutter_order(order, cx); + }); + window.draw(cx).clear(cx); + let state = editor.read(cx); + let layout = state.last_layout.as_ref().unwrap(); + assert_eq!(layout.gutter_gap, gap); + let y = state.row_bounds(1).unwrap().center().y; + let mut inset = gap; + for column in order { + let (x, width) = gutter_column(layout, true, column); + if width == px(0.) { + continue; + } + let from_text = if side.is_left() { + layout.text_origin_x - (x + width) + } else { + x - layout.text_origin_x - layout.text_width + }; + assert!( + (from_text - inset).abs() < px(0.001), + "{gap:?} {side:?} {column:?}" + ); + let hit = state + .hit_test(point(state.input_bounds.left() + x + width.half(), y)) + .unwrap(); + assert_eq!(hit.gutter_column(), Some(column)); + assert_eq!(hit.row(), Some(1)); + inset += width; + } + } + } + }); + } + } + + #[gpui::test] + fn editor_line_number_gutter_resizes_with_document_lines(cx: &mut TestAppContext) { + let (editor, window) = decoration_editor(cx, &"x\n".repeat(8), false); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.update(|window, cx| { + window.draw(cx).clear(cx); + let narrow = editor + .read(cx) + .last_layout + .as_ref() + .unwrap() + .line_number_width; + + let longer_text = "x\n".repeat(99); + editor.update(cx, |state, cx| { + state.set_value(longer_text.as_str(), window, cx) + }); + window.draw(cx).clear(cx); + let middle = editor + .read(cx) + .last_layout + .as_ref() + .unwrap() + .line_number_width; + assert_eq!(middle, narrow, "one to three digits must share a width"); + + let longest_text = "x\n".repeat(999); + editor.update(cx, |state, cx| { + state.set_value(longest_text.as_str(), window, cx) + }); + window.draw(cx).clear(cx); + let wide = editor + .read(cx) + .last_layout + .as_ref() + .unwrap() + .line_number_width; + + assert!( + wide > narrow, + "more line-number digits must widen the gutter" + ); + }); + } + + #[gpui::test] + fn a_gutter_on_the_right_leaves_the_text_at_the_left_edge(cx: &mut TestAppContext) { + let (editor, window) = decoration_editor(cx, &"word ".repeat(40), true); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.update(|window, cx| { + window.draw(cx).clear(cx); + let left = editor.read(cx).last_layout.clone().unwrap(); + editor.update(cx, |state, cx| state.set_gutter_side(Side::Right, cx)); + window.draw(cx).clear(cx); + let state = editor.read(cx); + let right = state.last_layout.clone().unwrap(); + let width = state.input_bounds.size.width; + + assert!(left.line_number_width > px(0.)); + assert_eq!(right.line_number_width, left.line_number_width); + assert_eq!(left.text_origin_x, left.line_number_width); + assert_eq!(left.gutter_origin_x, px(0.)); + assert_eq!(right.text_origin_x, px(0.)); + assert_eq!(right.gutter_origin_x, width - right.line_number_width); + // The text keeps its width, so it wraps where it did. + assert!(right.wrap_width.is_some()); + assert_eq!(right.wrap_width, left.wrap_width); + assert!(right.lines[0].wrapped_lines.len() > 1); + assert_eq!( + right.lines[0].wrapped_lines.len(), + left.lines[0].wrapped_lines.len() + ); + }); + } + + /// Every order the gutter's columns can take, from the text outward. + const GUTTER_ORDERS: [[GutterColumn; 4]; 6] = { + use GutterColumn::*; + [ + [FoldIcons, LineNumbers, Markers, Decorations], + [FoldIcons, Markers, LineNumbers, Decorations], + [LineNumbers, FoldIcons, Markers, Decorations], + [LineNumbers, Markers, FoldIcons, Decorations], + [Markers, FoldIcons, LineNumbers, Decorations], + [Markers, LineNumbers, FoldIcons, Decorations], + ] + }; + + /// How far `column` is from the text in `order`, given each column's width. + fn inset_from_text( + order: &[GutterColumn], + column: GutterColumn, + width: impl Fn(GutterColumn) -> Pixels, + ) -> Pixels { + order + .iter() + .take_while(|&&other| other != column) + .fold(LINE_NUMBER_RIGHT_MARGIN, |inset, &other| { + inset + width(other) + }) + } + + #[test] + fn a_gutter_order_lists_every_column_once() { + use GutterColumn::*; + assert_eq!( + GutterColumn::order([]), + [FoldIcons, LineNumbers, Markers, Decorations] + ); + assert_eq!( + GutterColumn::order([Markers]), + [Markers, FoldIcons, LineNumbers, Decorations] + ); + assert_eq!( + GutterColumn::order([LineNumbers, LineNumbers, Markers, LineNumbers]), + [LineNumbers, Markers, FoldIcons, Decorations] + ); + assert_eq!( + GutterColumn::order([Decorations, FoldIcons]), + [Decorations, FoldIcons, LineNumbers, Markers] + ); + for order in GUTTER_ORDERS { + assert_eq!(GutterColumn::order(order), order); + } + } + + /// The gutter decoration strip is a gutter column: outermost by default, + /// mirrored with the gutter, and next to the text when listed first. + #[gpui::test] + fn the_gutter_decoration_strip_is_a_gutter_column(cx: &mut TestAppContext) { + let (editor, window) = decoration_editor(cx, "one\ntwo\nthree", false); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.update(|window, cx| { + let _strip = editor.update(cx, |state, cx| { + state.create_gutter_decorations_collection(vec![GutterDecoration::new(0..3)], cx) + }); + let strip = px(3.); + for side in [Side::Left, Side::Right] { + for (order, outermost) in [(vec![], true), (vec![GutterColumn::Decorations], false)] + { + editor.update(cx, |state, cx| { + state.set_gutter_side(side, cx); + state.set_gutter_order(order, cx); + }); + window.draw(cx).clear(cx); + let state = editor.read(cx); + let layout = state.last_layout.as_ref().unwrap(); + assert_eq!( + layout.gutter_decorations_width, + strip + GUTTER_DECORATION_GAP ); - assert!(layout.line_number_width > baseline_width); - assert!(layout.wrap_width.unwrap() < baseline_wrap); + let x = gutter_decorations_x(layout, true, strip); + let gutter = + layout.gutter_origin_x..layout.gutter_origin_x + layout.line_number_width; + // How far the strip is from the gutter's edge at the text. + let from_text = if side.is_left() { + gutter.end - (x + strip) + } else { + x - gutter.start + }; + if outermost { + assert_eq!(from_text, layout.line_number_width - strip, "{side:?}"); + } else { + assert_eq!(from_text, LINE_NUMBER_RIGHT_MARGIN, "{side:?}"); + } + } + } + }); + } - let column_width = layout.line_number_width - gap - FOLD_ICON_HITBOX_WIDTH; - let mut number_style = TextStyle::default(); - number_style.font_family = ".SystemUIFont".into(); - // Assert actual painted labels fit, rather than assuming a - // punctuation glyph represents this font's digit advances. - for number in ["1", "10", "123", "444", "888", "999"] { - let number = window.text_system().shape_line( - number.into(), - px(32.), - &[number_style.to_run(number.len())], - None, - ); - assert_widths_match(column_width.max(number.width), column_width); + /// Projects a fold icon renderer whose icons record where they are laid out. + fn record_fold_icons( + editor: &Entity, + cx: &mut App, + ) -> Rc>>> { + let icons = Rc::new(std::cell::RefCell::new(Vec::new())); + let record = icons.clone(); + editor.update(cx, |state, _| { + let mut style = state.editor_style.clone(); + style.fold_icon_renderer = Some(Rc::new(move |_, _| { + let record = record.clone(); + gpui::canvas( + move |bounds, _, _| record.borrow_mut().push(bounds), + |_, _, _, _| {}, + ) + .size_full() + .into_any_element() + })); + state.set_editor_style(style); + }); + icons + } + + #[gpui::test] + fn a_right_gutter_is_mirrored(cx: &mut TestAppContext) { + let (editor, window) = decoration_editor(cx, "a\n b\nc\n".repeat(40).as_str(), false); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.update(|window, cx| { + let markers = record_markers(&editor, cx); + let icons = record_fold_icons(&editor, cx); + let paddings = Edges { + top: px(2.), + right: px(7.), + bottom: px(5.), + left: px(7.), + }; + editor.update(cx, |state, cx| { + state.set_editor_paddings(paddings); + state.apply_highlighter_fold_candidates(vec![FoldRange::new(0, 1)], cx); + state.create_line_decorations_collection(Bands::new(true), cx); + }); + + // Every span the gutter paints, measured from the gutter's outer edge to + // the span's near side, then the text's distance from the gutter. + let measure = |side: Side, + order: [GutterColumn; 4], + folding: bool, + window: &mut Window, + cx: &mut App| { + editor.update(cx, |state, cx| { + state.set_gutter_side(side, cx); + state.set_gutter_order(order, cx); + state.set_folding(folding, window, cx); + state.set_selected_range(0..0, cx); + }); + icons.borrow_mut().clear(); + markers.borrow_mut().clear(); + window.draw(cx).clear(cx); + let state = editor.read(cx); + let layout = state.last_layout.clone().unwrap(); + let input_bounds = state.input_bounds; + let from_outer = |x: Pixels, width: Pixels| { + if side.is_left() { + x - (input_bounds.left() - paddings.left) + } else { + input_bounds.right() + paddings.right - (x + width) } + }; + let at = |x: Pixels, width: Pixels| from_outer(input_bounds.left() + x, width); + + let gutter = editor_gutter_bounds(input_bounds, layout.line_number_width, px(0.), paddings, side); + let (numbers_x, numbers_width) = + gutter_column(&layout, folding, GutterColumn::LineNumbers); + let (fold_x, _) = gutter_column(&layout, folding, GutterColumn::FoldIcons); + assert!(layout.gutter_marker_width > px(0.)); + let marker = *markers.borrow().first().expect("a gutter marker is laid out"); + let mut spans = vec![ + from_outer(marker.left(), marker.size.width), + layout.gutter_marker_width, + from_outer(gutter.left(), gutter.size.width), + gutter.size.width, + at(numbers_x, numbers_width), + numbers_width, + ]; + // Numbers of any width, as a proportional font shapes them. + for width in [px(5.5), px(11.), numbers_width] { + spans.push(at(line_number_x(&layout, folding, width), width)); + } + if folding { + spans.push(at(fold_x, FOLD_ICON_HITBOX_WIDTH)); + let icon = *icons.borrow().first().expect("a fold icon is laid out"); + spans.push(from_outer(icon.left(), icon.size.width)); + } + let text_gap = if side.is_left() { + layout.text_origin_x - (layout.gutter_origin_x + layout.line_number_width) + } else { + layout.gutter_origin_x - (layout.text_origin_x + layout.text_width) + }; + (spans, text_gap, layout.text_width) + }; - let caret = state.prepaint_caret_geometry().unwrap().cursor_bounds(); + for (order, folding) in GUTTER_ORDERS + .into_iter() + .flat_map(|order| [(order, true), (order, false)]) + { + let (left, left_gap, left_width) = measure(Side::Left, order, folding, window, cx); + let (right, right_gap, right_width) = + measure(Side::Right, order, folding, window, cx); + assert_eq!(left.len(), right.len()); + for (ix, (left, right)) in left.iter().zip(&right).enumerate() { + assert!( + (*left - *right).abs() < px(0.01), + "span {ix}, {order:?} with folding {folding}: {left:?} on the left, {right:?} on the right" + ); + } + assert_eq!(left_gap, px(0.)); + assert_eq!(right_gap, px(0.)); + assert_eq!(left_width, right_width); + } + }); + } + + #[gpui::test] + fn the_gutter_order_counts_from_the_text(cx: &mut TestAppContext) { + let (editor, window) = decoration_editor(cx, "a\n b\nc", false); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.update(|window, cx| { + let markers = record_markers(&editor, cx); + let icons = record_fold_icons(&editor, cx); + editor.update(cx, |state, cx| { + state.apply_highlighter_fold_candidates(vec![FoldRange::new(0, 1)], cx); + state.create_line_decorations_collection(Bands::new(true), cx); + }); + for side in [Side::Left, Side::Right] { + for order in GUTTER_ORDERS { + editor.update(cx, |state, cx| { + state.set_gutter_side(side, cx); + state.set_gutter_order(order, cx); + state.set_selected_range(0..0, cx); + }); + icons.borrow_mut().clear(); + markers.borrow_mut().clear(); + window.draw(cx).clear(cx); + let state = editor.read(cx); + let layout = state.last_layout.clone().unwrap(); + let input_bounds = state.input_bounds; + // How far a span's near side is from the text. + let from_text = |x: Pixels, width: Pixels| { + if side.is_left() { + input_bounds.left() + layout.text_origin_x - (x + width) + } else { + x - (input_bounds.left() + layout.text_origin_x + layout.text_width) + } + }; + let numbers_width = line_number_column_width(&layout, true); + let digit = numbers_width / 3.; + let number = from_text( + input_bounds.left() + line_number_x(&layout, true, digit), + digit, + ); + let icon = *icons.borrow().first().expect("a fold icon is laid out"); + let icon = from_text(icon.left(), icon.size.width); + let icon_inset = (FOLD_ICON_HITBOX_WIDTH - FOLD_ICON_WIDTH).half(); + + let marker = *markers + .borrow() + .first() + .expect("a gutter marker is laid out"); + let marker_width = marker.size.width; + let marker = from_text(marker.left(), marker_width); + let slot = layout.gutter_marker_width; + assert!(slot > marker_width); + + let width = |column| match column { + GutterColumn::FoldIcons => FOLD_ICON_HITBOX_WIDTH, + GutterColumn::LineNumbers => numbers_width, + GutterColumn::Markers => slot, + GutterColumn::Decorations => px(0.), + }; + let number_from_text = + inset_from_text(&order, GutterColumn::LineNumbers, width); + let icon_from_text = + inset_from_text(&order, GutterColumn::FoldIcons, width) + icon_inset; + // The marker keeps its gap toward the line numbers. + let numbers_inside = + number_from_text < inset_from_text(&order, GutterColumn::Markers, width); + let marker_from_text = inset_from_text(&order, GutterColumn::Markers, width) + + if numbers_inside { + slot - marker_width + } else { + px(0.) + }; + // The marker is laid out on whole pixels. + assert!( + (marker - marker_from_text).abs() <= px(0.5), + "{side:?} gutter, {order:?}: the marker is {marker:?} from the text" + ); + assert!( + (number - number_from_text).abs() < px(0.01), + "{side:?} gutter, {order:?}: the line number is {number:?} from the text" + ); + // The icon is laid out on whole pixels. + assert!( + (icon - icon_from_text).abs() <= px(0.5), + "{side:?} gutter, {order:?}: the fold icon is {icon:?} from the text" + ); + } + } + }); + } + + #[gpui::test] + fn a_click_lands_on_the_fold_icon_or_the_line_number_in_every_gutter(cx: &mut TestAppContext) { + let (editor, window) = decoration_editor(cx, "abc\n b\nc", false); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.update(|_, cx| { + record_markers(&editor, cx); + editor.update(cx, |state, cx| { + state.create_line_decorations_collection(Bands::new(true), cx); + }); + }); + for side in [Side::Left, Side::Right] { + for order in GUTTER_ORDERS { + let (on_number, on_icon) = cx.update(|window, cx| { + editor.update(cx, |state, cx| { + state.display_map.clear_folds(); + state.apply_highlighter_fold_candidates(vec![FoldRange::new(0, 1)], cx); + state.set_gutter_side(side, cx); + state.set_gutter_order(order, cx); + state.set_selected_range(2..2, cx); + }); + window.draw(cx).clear(cx); + let state = editor.read(cx); + let layout = state.last_layout.as_ref().unwrap(); + let input_bounds = state.input_bounds; + let numbers_width = line_number_column_width(layout, true); + assert!(layout.gutter_marker_width > px(0.)); + let width = |column| match column { + GutterColumn::FoldIcons => FOLD_ICON_HITBOX_WIDTH, + GutterColumn::LineNumbers => numbers_width, + GutterColumn::Markers => layout.gutter_marker_width, + GutterColumn::Decorations => layout.gutter_decorations_width, + }; + let numbers_inset = inset_from_text(&order, GutterColumn::LineNumbers, width); + let fold_inset = inset_from_text(&order, GutterColumn::FoldIcons, width); + // The center of a column `inset` from the text. + let center = |inset: Pixels, width: Pixels| { + let inset = inset + width.half(); + if side.is_left() { + input_bounds.left() + layout.text_origin_x - inset + } else { + input_bounds.left() + layout.text_origin_x + layout.text_width + inset + } + }; + let y = input_bounds.top() + layout.line_height.half(); ( - column_width, - layout.wrap_width.unwrap(), - state.editor_scrollbar_snapshot.get().unwrap().layout.bounds, - point(caret.left() + px(1.), caret.center().y), + point(center(numbers_inset, numbers_width), y), + point(center(fold_inset, FOLD_ICON_HITBOX_WIDTH), y), ) }); - if let Some((previous_gap, previous_column, previous_wrap, previous_scrollbar)) = - previous - { - // A new gap changes wrapping, but the number/folding lane and - // scrollbar origin must not drift along with the blank space. - assert_widths_match(column_width, previous_column); - assert_widths_match(wrap_width + gap, previous_wrap + previous_gap); - assert_widths_match(scrollbar_bounds.origin.x, previous_scrollbar.origin.x); - assert_widths_match(scrollbar_bounds.size.width, previous_scrollbar.size.width); - assert_eq!(scrollbar_bounds.origin.y, previous_scrollbar.origin.y); - assert_eq!(scrollbar_bounds.size.height, previous_scrollbar.size.height); - } - previous = Some((gap, column_width, wrap_width, scrollbar_bounds)); + // The line number goes to the line, at the gutter's side of it. + cx.simulate_click(on_number, gpui::Modifiers::default()); + editor.read_with(&cx, |state, _| { + let at = if side.is_left() { 0 } else { 3 }; + assert_eq!(state.selected_range(), at..at, "{side:?} gutter, {order:?}"); + assert!( + !state.display_map.is_folded_at(0), + "{side:?} gutter, {order:?}" + ); + }); + + cx.update(|window, cx| window.draw(cx).clear(cx)); + cx.simulate_click(on_icon, gpui::Modifiers::default()); + editor.read_with(&cx, |state, _| { + assert!( + state.display_map.is_folded_at(0), + "{side:?} gutter, {order:?}" + ); + }); + } + } + } + + #[gpui::test] + fn horizontal_scrollbar_does_not_claim_clicks_in_the_right_gutter(cx: &mut TestAppContext) { + let text = format!("{}\n", "long line ".repeat(30)).repeat(40); + let (editor, window) = decoration_editor(cx, &text, false); + let mut cx = VisualTestContext::from_window(window.into(), cx); + let click = cx.update(|window, cx| { + Theme::global_mut(cx).scrollbar = + ScrollbarTheme::new().with_mode(ScrollbarMode::Always); + editor.update(cx, |state, cx| { + state.set_gutter_side(Side::Right, cx); + state.set_scrollbar_placement(ScrollbarPlacement::BottomLeft, cx); + }); + window.draw(cx).clear(cx); + let state = editor.read(cx); + let layout = state.last_layout.as_ref().unwrap(); + let (numbers_x, numbers_width) = gutter_column(layout, true, GutterColumn::LineNumbers); + point( + state.input_bounds.left() + numbers_x + numbers_width.half(), + state.input_bounds.bottom() - px(2.), + ) + }); + cx.simulate_click(click, gpui::Modifiers::default()); + editor.read_with(&cx, |state, _| { + assert_ne!( + state.selected_range(), + 0..0, + "the click must reach the editor" + ); + }); + } + + #[gpui::test] + fn a_scrollbar_beside_the_gutter_stays_at_the_outer_edge(cx: &mut TestAppContext) { + let (editor, window) = decoration_editor(cx, &"x\n".repeat(50), false); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.update(|window, cx| { + let paddings = Edges { + top: px(2.), + right: px(3.), + bottom: px(5.), + left: px(7.), + }; + editor.update(cx, |state, _| state.set_editor_paddings(paddings)); + for (gutter, scrollbar) in [ + (Side::Left, ScrollbarPlacement::BottomLeft), + (Side::Right, ScrollbarPlacement::BottomLeft), + (Side::Right, ScrollbarPlacement::BottomRight), + ] { + editor.update(cx, |state, cx| { + state.set_gutter_side(gutter, cx); + state.set_scrollbar_placement(scrollbar, cx); + }); + window.draw(cx).clear(cx); + let state = editor.read(cx); + let input_bounds = state.input_bounds; + let viewport = state.editor_scrollbar_snapshot.get().unwrap().layout.bounds; + assert_eq!( + viewport.right(), + input_bounds.right() + paddings.right, + "{gutter:?} gutter, {scrollbar:?} scrollbar" + ); + let left = if scrollbar.is_left() { + input_bounds.left() - paddings.left + } else { + input_bounds.left() + }; + assert_eq!( + viewport.left(), + left, + "{gutter:?} gutter, {scrollbar:?} scrollbar" + ); + } + }); + } + + #[gpui::test] + fn the_text_keeps_clear_of_a_scrollbar_on_the_left(cx: &mut TestAppContext) { + let (editor, window) = decoration_editor(cx, &"word ".repeat(40), true); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.update(|window, cx| { + editor.update(cx, |state, cx| { + state.set_editor_paddings(Edges { + top: px(4.), + right: px(10.), + bottom: px(4.), + left: px(6.), + }); + state.set_gutter_side(Side::Right, cx); + state.set_scrollbar_placement(ScrollbarPlacement::BottomLeft, cx); + }); + window.draw(cx).clear(cx); + let state = editor.read(cx); + let layout = state.last_layout.as_ref().unwrap(); + let input_bounds = state.input_bounds; + let scrollbar = state.editor_scrollbar_snapshot.get().unwrap().layout.bounds; + + assert!( + input_bounds.left() + layout.text_origin_x >= scrollbar.left() + Scrollbar::width(), + "the text starts under the scrollbar" + ); + // The text gives the room up, the gutter does not move. + assert_eq!( + layout.gutter_origin_x, + input_bounds.size.width - layout.line_number_width + ); + assert_eq!( + layout.text_origin_x + layout.text_width, + layout.gutter_origin_x + ); + assert_eq!(layout.wrap_width, Some(layout.text_width - RIGHT_MARGIN)); + }); + } + + #[gpui::test] + fn the_text_is_clipped_to_its_side_of_the_gutter(cx: &mut TestAppContext) { + let text = format!("{}\n", "word ".repeat(40)).repeat(3); + let (editor, window) = decoration_editor(cx, &text, false); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.update(|window, cx| { + editor.update(cx, |state, cx| { + state.create_decorations_collection( + vec![TextDecoration::new( + 0..text.len(), + HighlightStyle { + background_color: Some(gpui::red()), + underline: Some(UnderlineStyle { + color: Some(gpui::red()), + thickness: px(1.), + wavy: false, + }), + ..Default::default() + }, + )], + cx, + ); + }); + + for (line_number, side, placement) in [ + (true, Side::Left, ScrollbarPlacement::BottomRight), + (true, Side::Right, ScrollbarPlacement::BottomRight), + (true, Side::Left, ScrollbarPlacement::BottomLeft), + (true, Side::Right, ScrollbarPlacement::BottomLeft), + // Without line numbers the gutter holds only the fold icons. + (false, Side::Left, ScrollbarPlacement::BottomRight), + (false, Side::Right, ScrollbarPlacement::BottomRight), + ] { + editor.update(cx, |state, cx| { + state.set_line_number(line_number, window, cx); + state.set_gutter_side(side, cx); + state.set_scrollbar_placement(placement, cx); + state.set_scroll_offset(point(px(-100.), px(0.)), cx); + }); + // Deferred scroll is committed by prepaint and reflected next frame. + window.draw(cx).clear(cx); + window.draw(cx).clear(cx); + let state = editor.read(cx); + let layout = state.last_layout.as_ref().unwrap(); + let gutter = editor_gutter_bounds( + state.input_bounds, + layout.line_number_width, + px(0.), + state.editor_paddings, + side, + ) + .scale(window.scale_factor()); + + // Glyph backgrounds, then the text's own underlines. + let red = gpui::Background::from(gpui::red()); + let backgrounds = window + .painted_quads() + .into_iter() + .filter(|quad| quad.background == red) + .map(|quad| (quad.bounds, quad.content_mask.bounds)) + .collect::>(); + let underlines = window + .painted_underlines() + .into_iter() + .filter(|underline| underline.color == gpui::red()) + .map(|underline| (underline.bounds, underline.content_mask.bounds)) + .collect::>(); + for painted in [backgrounds, underlines] { + assert!( + painted.iter().any(|(bounds, _)| bounds.intersects(&gutter)), + "{side:?} gutter, line numbers {line_number}, {placement:?}: the text runs under the gutter" + ); + for (bounds, mask) in painted { + // A content mask is snapped to whole device pixels. + let shown = bounds.intersect(&mask).intersect(&gutter); + assert!( + shown.size.width < gpui::ScaledPixels::from(1.), + "{side:?} gutter, line numbers {line_number}, {placement:?}: {bounds:?} under {mask:?} shows through the gutter {gutter:?}" + ); + } + } + } + }); + } + + #[gpui::test] + fn the_text_keeps_clear_of_the_whole_track_of_a_scrollbar_on_the_left(cx: &mut TestAppContext) { + let (editor, window) = decoration_editor(cx, &"word\n".repeat(40), true); + let mut cx = VisualTestContext::from_window(window.into(), cx); + for track_width in [None, Some(px(24.))] { + let in_text = cx.update(|window, cx| { + Theme::global_mut(cx).scrollbar = ScrollbarTheme::new() + .with_mode(ScrollbarMode::Always) + .with_styles( + ScrollbarStyles::default().when_some(track_width, |styles, width| { + styles.track(|track| track.width(width)) + }), + ); + editor.update(cx, |state, cx| { + state.set_gutter_side(Side::Right, cx); + state.set_scrollbar_placement(ScrollbarPlacement::BottomLeft, cx); + state.set_selected_range(4..4, cx); + }); + window.draw(cx).clear(cx); + let state = editor.read(cx); + let layout = state.last_layout.as_ref().unwrap(); + let input_bounds = state.input_bounds; + let scrollbar = state.editor_scrollbar_snapshot.get().unwrap().layout.bounds; + + assert_eq!(scrollbar.left(), input_bounds.left()); + assert!( + layout.text_origin_x >= track_width.unwrap_or(Scrollbar::width()), + "{track_width:?} track: the text starts under the scrollbar" + ); + input_bounds.origin + point(layout.text_origin_x + px(1.), layout.line_height * 0.5) + }); - cx.simulate_click(click_position, gpui::Modifiers::default()); - editor.read_with(&cx, |state, _| assert_eq!(state.selected_range(), 0..0)); + cx.simulate_click(in_text, gpui::Modifiers::default()); + editor.read_with(&cx, |state, _| { + assert_eq!(state.selected_range(), 0..0, "{track_width:?} track"); + }); } + } - window - .update(&mut cx, |view, _, cx| { - view.1 = Some(px(12.)); - cx.notify(); - }) - .unwrap(); - cx.update(|window, cx| { - editor.update(cx, |state, cx| { - state.set_line_number(false, window, cx); - }); - window.draw(cx).clear(cx); - assert_eq!( - editor - .read(cx) - .last_layout - .as_ref() - .unwrap() - .line_number_width, - px(12.) + FOLD_ICON_HITBOX_WIDTH, - ); - editor.update(cx, |state, cx| state.set_folding(false, window, cx)); - window.draw(cx).clear(cx); - assert_eq!( - editor - .read(cx) - .last_layout - .as_ref() + #[gpui::test] + fn a_click_lands_in_the_text_beside_a_gutter_on_either_side(cx: &mut TestAppContext) { + let (editor, window) = decoration_editor(cx, "abcdef\nab", false); + let mut cx = VisualTestContext::from_window(window.into(), cx); + for (side, gutter_click) in [(Side::Left, 7), (Side::Right, 9)] { + let (in_text, in_gutter) = cx.update(|window, cx| { + editor.update(cx, |state, cx| { + state.set_gutter_side(side, cx); + state.set_selected_range(0..0, cx); + }); + window.draw(cx).clear(cx); + let state = editor.read(cx); + let layout = state.last_layout.as_ref().unwrap(); + let input_bounds = state.input_bounds; + let x = layout.lines[0] + .position_for_index(3, layout, false) .unwrap() - .line_number_width, - px(12.) - ); - }); + .x; + ( + input_bounds.origin + point(layout.text_origin_x + x, layout.line_height * 0.5), + input_bounds.origin + + point( + layout.gutter_origin_x + layout.line_number_width.half(), + layout.line_height * 1.5, + ), + ) + }); + + cx.simulate_click(in_text, gpui::Modifiers::default()); + editor.read_with(&cx, |state, _| { + assert_eq!(state.selected_range(), 3..3, "{side:?} gutter"); + }); + + // A click in the gutter goes to the line, at the gutter's side of it. + cx.simulate_click(in_gutter, gpui::Modifiers::default()); + editor.read_with(&cx, |state, _| { + assert_eq!( + state.selected_range(), + gutter_click..gutter_click, + "{side:?} gutter" + ); + }); + } } #[gpui::test] - fn editor_line_number_gutter_resizes_with_document_lines(cx: &mut TestAppContext) { - let (editor, window) = decoration_editor(cx, &"x\n".repeat(8), false); + fn the_caret_and_the_ime_bounds_follow_the_text_beside_a_right_gutter(cx: &mut TestAppContext) { + let text = "wide ".repeat(80); + let (editor, window) = decoration_editor(cx, &format!("abcdef\n{text}"), false); let mut cx = VisualTestContext::from_window(window.into(), cx); cx.update(|window, cx| { - window.draw(cx).clear(cx); - let narrow = editor - .read(cx) - .last_layout - .as_ref() - .unwrap() - .line_number_width; - - let longer_text = "x\n".repeat(99); editor.update(cx, |state, cx| { - state.set_value(longer_text.as_str(), window, cx) + state.set_gutter_side(Side::Right, cx); + state.focus(window, cx); + state.set_selected_range(3..3, cx); }); window.draw(cx).clear(cx); - let middle = editor - .read(cx) - .last_layout - .as_ref() + let (layout, bounds, input_bounds) = { + let state = editor.read(cx); + ( + state.last_layout.clone().unwrap(), + state.last_bounds.unwrap(), + state.input_bounds, + ) + }; + let x = layout.lines[0] + .position_for_index(3, &layout, false) .unwrap() - .line_number_width; - assert_eq!(middle, narrow, "one to three digits must share a width"); + .x; + assert_eq!( + layout.cursor_bounds.unwrap().left(), + input_bounds.left() + x + ); + let ime = editor + .update(cx, |state, cx| { + state.bounds_for_range(3..4, bounds, window, cx) + }) + .unwrap(); + assert_eq!(ime.left(), input_bounds.left() + x); + let range = editor.read(cx).range_to_bounds(&(3..4)).unwrap(); + assert_eq!(range.left(), input_bounds.left() + x); + editor.update(cx, |state, cx| state.set_selected_range(3..4, cx)); + let mut bounds = input_bounds; + let selection = TextElement::new(editor.clone()) + .layout_selections(&layout, &mut bounds, window, cx) + .remove(0); + assert_eq!(selection.bounds.left(), input_bounds.left() + x); - let longest_text = "x\n".repeat(999); + // The caret at the end of a long line scrolls into view, left of the gutter. editor.update(cx, |state, cx| { - state.set_value(longest_text.as_str(), window, cx) + let end = state.text.len(); + state.set_selected_range(end..end, cx); }); window.draw(cx).clear(cx); - let wide = editor - .read(cx) - .last_layout - .as_ref() - .unwrap() - .line_number_width; - + window.draw(cx).clear(cx); + let state = editor.read(cx); + let layout = state.last_layout.as_ref().unwrap(); + let caret = layout.cursor_bounds.unwrap(); + assert!(state.scroll_handle.offset().x < px(0.)); + assert!(caret.right() <= input_bounds.left() + layout.gutter_origin_x); assert!( - wide > narrow, - "more line-number digits must widen the gutter" + caret.left() > input_bounds.left() + layout.gutter_origin_x - RIGHT_MARGIN * 2. ); }); } @@ -6545,6 +8887,46 @@ mod tests { }); } + /// With the scrollbar placed on the left, the overview ruler marks follow + /// the vertical track there, and a supplied scrollbar is told the placement. + #[gpui::test] + fn overview_ruler_marks_follow_a_left_scrollbar(cx: &mut TestAppContext) { + let text = "x\n".repeat(99) + "x"; + let (editor, window) = decoration_editor(cx, &text, false); + let presented = Rc::new(std::cell::Cell::new(None)); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.update(|window, cx| { + editor.update(cx, |state, cx| { + state.create_overview_ruler_decorations_collection( + vec![ + OverviewRulerDecoration::new(0..10) + .with_lane(OverviewRulerLane::Left) + .with_color(gpui::green()), + ], + cx, + ); + state.set_scrollbar_placement(ScrollbarPlacement::BottomLeft, cx); + }); + window.draw(cx).clear(cx); + let state = editor.read(cx); + let snapshot = state.editor_scrollbar_snapshot.get().unwrap(); + let marks = layout_overview_ruler(state, &snapshot, Scrollbar::width()); + assert_eq!(marks.len(), 1); + assert_eq!(marks[0].bounds.left(), snapshot.layout.bounds.left()); + assert_eq!(marks[0].bounds.size.width, Scrollbar::width() / 3.); + + editor.update(cx, |state, _| { + let presented = presented.clone(); + state.set_scrollbar_renderer(Some(Rc::new(move |context, _, _| { + presented.set(Some(context.placement())); + Scrollbar::vertical(&context).into_any_element() + }))); + }); + window.draw(cx).clear(cx); + }); + assert_eq!(presented.get(), Some(ScrollbarPlacement::BottomLeft)); + } + #[gpui::test] fn overview_ruler_marks_follow_edits_folds_and_new_decorations(cx: &mut TestAppContext) { let text = "x\n".repeat(99) + "x"; @@ -6949,8 +9331,13 @@ mod tests { left: px(7.), }; - let layout = - EditorScrollbarLayout::new(input_bounds, px(40.), size(px(1000.), px(200.)), paddings); + let layout = EditorScrollbarLayout::new( + input_bounds, + px(40.), + size(px(1000.), px(200.)), + paddings, + ScrollbarPlacement::BottomRight, + ); assert_eq!( layout.bounds, @@ -6959,8 +9346,13 @@ mod tests { assert_eq!(layout.scroll_size, size(px(972.), px(200.))); assert_eq!(layout.scroll_viewport_size, size(px(262.), px(80.))); - let layout_without_gutter = - EditorScrollbarLayout::new(input_bounds, px(0.), size(px(500.), px(120.)), paddings); + let layout_without_gutter = EditorScrollbarLayout::new( + input_bounds, + px(0.), + size(px(500.), px(120.)), + paddings, + ScrollbarPlacement::BottomRight, + ); assert_eq!( layout_without_gutter.bounds, @@ -6973,6 +9365,41 @@ mod tests { ); } + #[test] + fn test_editor_scrollbar_layout_on_the_left_covers_the_gutter() { + let input_bounds = Bounds::new(point(px(10.), px(20.)), size(px(300.), px(80.))); + let paddings = Edges { + top: px(2.), + right: px(3.), + bottom: px(5.), + left: px(7.), + }; + + let layout = EditorScrollbarLayout::new( + input_bounds, + px(40.), + size(px(1000.), px(200.)), + paddings, + ScrollbarPlacement::BottomLeft, + ); + + assert_eq!( + layout.bounds, + Bounds::new(point(px(3.), px(18.)), size(px(310.), px(87.))) + ); + assert_eq!(layout.scroll_size, size(px(1020.), px(200.))); + assert_eq!( + EditorScrollbarLayout::new( + input_bounds, + px(40.), + size(px(1000.), px(200.)), + paddings, + ScrollbarPlacement::TopLeft, + ), + layout + ); + } + #[test] fn test_editor_gutter_covers_the_complete_fixed_column() { let input_bounds = Bounds::new(point(px(10.), px(20.)), size(px(300.), px(80.))); @@ -6988,9 +9415,25 @@ mod tests { bottom: px(5.), left: px(7.), }, + Side::Left, ), Bounds::new(point(px(3.), px(18.)), size(px(55.), px(103.))) ); + assert_eq!( + editor_gutter_bounds( + input_bounds, + px(48.), + px(16.), + Edges { + top: px(2.), + right: px(3.), + bottom: px(5.), + left: px(7.), + }, + Side::Right, + ), + Bounds::new(point(px(262.), px(18.)), size(px(51.), px(103.))) + ); } #[test] @@ -7434,6 +9877,229 @@ mod tests { ); } + /// The middle of the `column`'s band in the gutter, in window coordinates. + fn gutter_column_middle(state: &EditorState, column: GutterColumn) -> Option { + let layout = state.last_layout.as_ref().unwrap(); + let (x, width) = gutter_column(layout, state.mode.is_folding(), column); + (width > px(0.)).then(|| state.input_bounds.origin.x + x + width.half()) + } + + #[gpui::test] + fn hit_test_tells_the_gutter_from_the_text(cx: &mut TestAppContext) { + let (editor, window) = decoration_editor(cx, "one\ntwo\nthree", false); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.update(|window, cx| { + let unpainted = cx.new(|cx| EditorState::new(window, cx).default_value("a")); + assert!(unpainted.read(cx).gutter_bounds().is_none()); + assert!(unpainted.read(cx).hit_test(point(px(1.), px(1.))).is_none()); + + for side in [Side::Left, Side::Right] { + editor.update(cx, |state, cx| state.set_gutter_side(side, cx)); + window.draw(cx).clear(cx); + let state = editor.read(cx); + let gutter = state.gutter_bounds().unwrap(); + let row = state.row_bounds(1).unwrap(); + let y = row.center().y; + if side.is_left() { + assert_eq!( + gutter.left(), + state.input_bounds.left() - state.editor_paddings.left + ); + } else { + assert_eq!( + gutter.right(), + state.input_bounds.right() + state.editor_paddings.right + ); + } + + let mut columns = 0; + for column in [ + GutterColumn::FoldIcons, + GutterColumn::LineNumbers, + GutterColumn::Markers, + ] { + let Some(x) = gutter_column_middle(state, column) else { + continue; + }; + columns += 1; + let hit = state.hit_test(point(x, y)).unwrap(); + assert!(hit.is_gutter(), "{side:?} {column:?}"); + assert_eq!(hit.gutter_column(), Some(column), "{side:?}"); + assert_eq!(hit.row(), Some(1)); + assert_eq!(hit.offset(), None); + assert!(!hit.is_spacer()); + } + assert!(columns >= 2, "fold icons and line numbers"); + + // The margin between the text and the gutter's columns is the + // gutter, in no column. + let margin = if side.is_left() { + gutter.right() - px(1.) + } else { + gutter.left() + px(1.) + }; + let hit = state.hit_test(point(margin, y)).unwrap(); + assert_eq!(hit.area(), InputHitArea::Gutter { column: None }); + assert_eq!(hit.row(), Some(1)); + + // Below the last row the gutter is beside no row. + let below = state.row_bounds(2).unwrap().bottom() + state.line_height().unwrap(); + let x = gutter_column_middle(state, GutterColumn::LineNumbers).unwrap(); + let hit = state.hit_test(point(x, below)).unwrap(); + assert!(hit.is_gutter()); + assert_eq!(hit.row(), None); + + // The text is where a click places the caret. + let x = if side.is_left() { + gutter.right() + px(30.) + } else { + gutter.left() - px(30.) + }; + let hit = state.hit_test(point(x, y)).unwrap(); + assert!(!hit.is_gutter()); + assert_eq!(hit.row(), Some(1)); + assert_eq!( + hit.offset(), + Some(state.index_for_mouse_position(point(x, y)).0) + ); + assert!((4..=7).contains(&hit.offset().unwrap()), "{hit:?}"); + + let outside = point(state.input_bounds.right() + px(500.), y); + assert!(state.hit_test(outside).is_none()); + } + }); + } + + #[gpui::test] + fn hit_test_puts_a_spacer_row_beside_its_line(cx: &mut TestAppContext) { + use crate::input::Spacer; + let (editor, window, _) = + spaced_editor(cx, false, vec![Spacer::above(1, 1), Spacer::below(1, 2)]); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.update(|window, cx| { + window.draw(cx).clear(cx); + let state = editor.read(cx); + let line_height = state.line_height().unwrap(); + let row = state.row_bounds(1).unwrap(); + let gutter_x = gutter_column_middle(state, GutterColumn::LineNumbers).unwrap(); + let text_x = state.gutter_bounds().unwrap().right() + px(10.); + for (y, spacer) in [ + (row.top() - line_height.half(), true), + (row.center().y, false), + (row.bottom() + line_height.half(), true), + (row.bottom() + line_height * 1.5, true), + ] { + for x in [gutter_x, text_x] { + let hit = state.hit_test(point(x, y)).unwrap(); + assert_eq!(hit.row(), Some(1), "{y:?} {hit:?}"); + assert_eq!(hit.is_spacer(), spacer, "{y:?} {hit:?}"); + } + } + let probe = point(gutter_x, state.row_bounds(2).unwrap().top() + px(1.)); + let next = state.hit_test(probe).unwrap(); + assert_eq!((next.row(), next.is_spacer()), (Some(2), false)); + + // Ghost lines stand between the row's text and its spacers below. + editor.update(cx, |state, cx| { + state.set_cursor_position(lsp_types::Position::new(1, 3), window, cx); + state.extras.inline_completion.item = Some(lsp_types::InlineCompletionItem { + insert_text: "\nghost".into(), + filter_text: None, + range: None, + command: None, + insert_text_format: None, + }); + cx.notify(); + }); + window.draw(cx).clear(cx); + let state = editor.read(cx); + let row = state.row_bounds(1).unwrap(); + let ghost = state.hit_test(point(gutter_x, row.bottom() + line_height.half())); + assert_eq!(ghost.unwrap().row(), None); + // In the text, the ghost lines are on the row they follow. + let ghost = state.hit_test(point(text_x, row.bottom() + line_height.half())); + assert_eq!( + ghost.map(|hit| (hit.row(), hit.is_spacer())), + Some((Some(1), false)) + ); + for y in [ + row.bottom() + line_height * 1.5, + row.bottom() + line_height * 2.5, + ] { + for x in [gutter_x, text_x] { + let hit = state.hit_test(point(x, y)).unwrap(); + assert_eq!((hit.row(), hit.is_spacer()), (Some(1), true), "{y:?}"); + } + } + for x in [gutter_x, text_x] { + let probe = point(x, state.row_bounds(2).unwrap().top() + px(1.)); + let next = state.hit_test(probe).unwrap(); + assert_eq!((next.row(), next.is_spacer()), (Some(2), false)); + } + }); + } + + #[gpui::test] + fn a_right_click_on_the_gutter_tells_the_menu_its_row(cx: &mut TestAppContext) { + let (editor, window) = decoration_editor(cx, "one\ntwo\nthree", false); + let mut cx = VisualTestContext::from_window(window.into(), cx); + let opened: Rc>>> = Default::default(); + cx.update(|window, cx| { + editor.update(cx, |state, _| { + let opened = opened.clone(); + state.on_context_menu_with_hit(Rc::new(move |_, _, hit, _, _, _| { + opened.borrow_mut().push(hit); + })); + }); + window.draw(cx).clear(cx); + }); + let (gutter, text, rows) = cx.update(|_, cx| { + let state = editor.read(cx); + let gutter = gutter_column_middle(state, GutterColumn::LineNumbers).unwrap(); + let text = state.gutter_bounds().unwrap().right() + px(10.); + let rows: Vec = (0..3) + .map(|row| state.row_bounds(row).unwrap().center().y) + .collect(); + (gutter, text, rows) + }); + let right_click = |cx: &mut VisualTestContext, position: Point| { + cx.simulate_mouse_down(position, MouseButton::Right, Default::default()); + cx.simulate_mouse_up(position, MouseButton::Right, Default::default()); + cx.run_until_parked(); + let hit = opened.borrow_mut().pop().expect("the menu opened"); + let selected = cx.update(|_, cx| editor.read(cx).selected_range()); + (hit.unwrap(), selected) + }; + let select = |cx: &mut VisualTestContext| { + cx.update(|_, cx| editor.update(cx, |state, cx| state.set_selected_range(0..2, cx))); + }; + + // By default the gutter moves the caret to its row, as the text does. + select(&mut cx); + let (hit, selected) = right_click(&mut cx, point(gutter, rows[1])); + assert_eq!(hit.gutter_column(), Some(GutterColumn::LineNumbers)); + assert_eq!(hit.row(), Some(1)); + assert_eq!(selected, 4..4); + + // Turned off, a menu for a row of the gutter keeps the selection. + cx.update(|_, cx| { + editor.update(cx, |state, _| { + state.set_gutter_context_menu_moves_cursor(false) + }) + }); + select(&mut cx); + let (hit, selected) = right_click(&mut cx, point(gutter, rows[2])); + assert!(hit.is_gutter()); + assert_eq!(hit.row(), Some(2)); + assert_eq!(selected, 0..2); + + // The text still moves the caret. + let (hit, selected) = right_click(&mut cx, point(text, rows[2])); + assert_eq!(hit.row(), Some(2)); + assert_eq!(selected, hit.offset().unwrap()..hit.offset().unwrap()); + assert!(hit.offset().unwrap() >= 8); + } + #[test] fn large_line_count_coordinates_stay_aligned_past_f32_cliff() { for line_height in [px(22.5), px(23.0)] { @@ -7474,6 +10140,16 @@ mod tests { wrap_width: None, wrapping_indent: crate::input::WrappingIndent::None, line_number_width: px(60.), + gutter_gap: LINE_NUMBER_RIGHT_MARGIN, + gutter_marker_width: px(0.), + gutter_decorations_width: px(0.), + ghost_lines: None, + spacer_rows: Vec::new(), + gutter_side: crate::Side::Left, + gutter_order: crate::input::GutterColumn::DEFAULT_ORDER, + text_origin_x: px(60.), + gutter_origin_x: px(0.), + text_width: px(800.), space_width: px(8.), cursor_bounds: None, text_align: gpui::TextAlign::Left, diff --git a/crates/base/src/input/base/kind.rs b/crates/base/src/input/base/kind.rs index 159f0777e3..587e838e3d 100644 --- a/crates/base/src/input/base/kind.rs +++ b/crates/base/src/input/base/kind.rs @@ -27,10 +27,12 @@ use gpui::{Div, Entity, Stateful, Window}; use ropey::Rope; use super::decorations::DecorationCollections; +use super::line_decorations::LineDecorationProviders; use super::lsp::{ContextMenuContent, HoverDefinition, InlineCompletion}; +use super::spacers::SpacerProvider; use crate::input::{ - GutterDecoration, HighlightStyleResolver, InputEdit, InputHighlighter, OverviewRulerDecoration, - RangeDecoration, SyntaxContext, TextDecoration, + GutterDecoration, HighlightStyleResolver, InputEdit, InputHighlighter, LineDecoration, + OverviewRulerDecoration, RangeDecoration, SyntaxContext, TextDecoration, }; use crate::input::{HoverPopoverState, Lsp}; use gpui::Task; @@ -111,6 +113,25 @@ pub trait InputExtras: Default + 'static { 0 } + /// Line decorations for the visible buffer rows, in collection order. + fn line_decorations( + &self, + _rows: std::ops::Range, + _cx: &gpui::App, + ) -> Vec { + Vec::new() + } + + /// Whether any line decoration collection has a provider. + fn has_line_decorations(&self) -> bool { + false + } + + /// The provider of the spacers, if one is set. + fn spacer_provider(&self) -> Option> { + None + } + /// Semantic-token styles for a visible range, when an LSP supplies them. fn semantic_token_styles( &self, @@ -409,6 +430,8 @@ pub struct EditorExtras { pub(crate) gutter_decorations: DecorationCollections, pub(crate) gutter_decorations_width: gpui::Pixels, pub(crate) overview_ruler_decorations: DecorationCollections, + pub(crate) line_decorations: LineDecorationProviders, + pub(crate) spacer_provider: Option>, pub(crate) inline_completion: InlineCompletion, pub(crate) context_menu_content: ContextMenuContent, pub(crate) hover_popover: Option, @@ -425,6 +448,8 @@ impl Default for EditorExtras { gutter_decorations: DecorationCollections::default(), gutter_decorations_width: gpui::px(3.), overview_ruler_decorations: DecorationCollections::default(), + line_decorations: LineDecorationProviders::default(), + spacer_provider: None, inline_completion: InlineCompletion::default(), context_menu_content: ContextMenuContent::default(), hover_popover: None, diff --git a/crates/base/src/input/base/layout.rs b/crates/base/src/input/base/layout.rs index 19a12aa9b6..ed33811978 100644 --- a/crates/base/src/input/base/layout.rs +++ b/crates/base/src/input/base/layout.rs @@ -2,6 +2,8 @@ use std::{ops::Range, rc::Rc}; use gpui::{Bounds, Pixels, ShapedLine, TextAlign, px}; +use crate::Side; + use super::{WrappingIndent, display_map::LineLayout}; #[derive(Clone, Default)] @@ -10,6 +12,119 @@ pub(crate) struct WhitespaceIndicators { pub(crate) tab: ShapedLine, } +/// A column of the editor's gutter, ordered from the text outward with +/// `gutter_order`. +/// +/// The order is the same on either [`Side`], so a gutter on the right is the +/// mirror of one on the left. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum GutterColumn { + /// The fold icons. + FoldIcons, + /// The line numbers. + LineNumbers, + /// The gutter markers of the line decorations. + Markers, + /// The strip of the gutter decorations. + Decorations, +} + +impl GutterColumn { + /// The columns in their default order, from the text outward. + pub(crate) const DEFAULT_ORDER: [Self; 4] = [ + Self::FoldIcons, + Self::LineNumbers, + Self::Markers, + Self::Decorations, + ]; + + /// Return every column once, those listed first and the rest in their + /// default order. + pub(super) fn order(columns: impl IntoIterator) -> [Self; 4] { + let mut order = Self::DEFAULT_ORDER; + let mut len = 0; + for column in columns.into_iter().chain(Self::DEFAULT_ORDER) { + if len == order.len() { + break; + } + if !order[..len].contains(&column) { + order[len] = column; + len += 1; + } + } + order + } +} + +/// What a point of an input is over, as it was last painted. +/// +/// Returned by [`hit_test`](super::InputBaseState::hit_test). The fields are private +/// and reached through the methods below, so that more can be told about a +/// point without breaking its readers. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct InputHit { + area: InputHitArea, + row: Option, + spacer: bool, +} + +/// The part of an input a point is over. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum InputHitArea { + /// The text, at the byte offset a click there places the caret at. + #[non_exhaustive] + Text { offset: usize }, + /// The gutter, in one of its columns, or `None` in its margin or padding. + #[non_exhaustive] + Gutter { column: Option }, +} + +impl InputHit { + pub(crate) fn new(area: InputHitArea, row: Option, spacer: bool) -> Self { + Self { area, row, spacer } + } + + pub fn area(&self) -> InputHitArea { + self.area + } + + /// The zero-based buffer row the point is beside. + /// + /// In the text it is the row of [`Self::offset`]. In the gutter it is + /// `None` above the first laid-out row and below the last. + pub fn row(&self) -> Option { + self.row + } + + /// The byte offset in the text, when the point is over the text. + pub fn offset(&self) -> Option { + match self.area { + InputHitArea::Text { offset } => Some(offset), + InputHitArea::Gutter { .. } => None, + } + } + + pub fn is_gutter(&self) -> bool { + matches!(self.area, InputHitArea::Gutter { .. }) + } + + /// The gutter column the point is in, when it is in one. + pub fn gutter_column(&self) -> Option { + match self.area { + InputHitArea::Gutter { column } => column, + InputHitArea::Text { .. } => None, + } + } + + /// Returns true when the point is on a spacer row beside [`Self::row`] + /// rather than on the row itself. + pub fn is_spacer(&self) -> bool { + self.spacer + } +} + #[derive(Clone)] pub(super) struct LastLayout { pub(super) visible_range: Range, @@ -23,6 +138,30 @@ pub(super) struct LastLayout { pub(super) wrap_width: Option, pub(super) wrapping_indent: WrappingIndent, pub(super) line_number_width: Pixels, + /// Resolved gap between the text and the gutter columns for this frame. + pub(super) gutter_gap: Pixels, + /// Width reserved between the line numbers and the outer edge of the gutter + /// for gutter markers, zero when none can be painted. Part of + /// `line_number_width`. + pub(super) gutter_marker_width: Pixels, + /// Width reserved for the gutter decoration strip and its gap toward the + /// line numbers, zero without a gutter decoration collection. Part of + /// `line_number_width`. + pub(super) gutter_decorations_width: Pixels, + /// The buffer row that inline completion ghost lines follow, and their height. + pub(super) ghost_lines: Option<(usize, Pixels)>, + /// How many spacer rows stand above and below each laid-out row, in + /// `visible_buffer_lines` order; empty when the editor has no spacers. + pub(super) spacer_rows: Vec<(usize, usize)>, + pub(super) gutter_side: Side, + pub(super) gutter_order: [GutterColumn; 4], + /// The x of the text, relative to the input bounds. + pub(super) text_origin_x: Pixels, + /// The x of the gutter, relative to the input bounds. + pub(super) gutter_origin_x: Pixels, + /// The width of the text, without the gutter and the margin kept from a + /// scrollbar on the left. + pub(super) text_width: Pixels, /// Width of one space in the editor font. /// /// Past the end of a line there are no glyphs to hit-test against, so this is the @@ -39,6 +178,64 @@ impl LastLayout { self.lines.get(pos) } + /// The heights of the spacer rows above and below the `ix`th laid-out row. + pub(super) fn spacers(&self, ix: usize) -> (Pixels, Pixels) { + self.spacer_rows + .get(ix) + .map_or((px(0.), px(0.)), |&(above, below)| { + (self.line_height * above, self.line_height * below) + }) + } + + /// The top and height of each laid-out row, in `visible_buffer_lines` order. + /// + /// Tops are relative to the content origin and, as painted, rows after the + /// ghost lines are shifted down by their height. A row's spacers are not + /// part of its height; ghost lines stand between its text and the spacers + /// below it. + pub(super) fn row_extents(&self) -> impl Iterator + '_ { + let mut top = self.visible_top; + self.lines + .iter() + .zip(&self.visible_buffer_lines) + .enumerate() + .map(move |(ix, (line, &row))| { + let (above, below) = self.spacers(ix); + top += above; + let height = line.size(self.line_height).height; + let extent = (top, height); + top += height; + if let Some((ghost_row, ghost_height)) = self.ghost_lines + && ghost_row == row + { + top += ghost_height; + } + top += below; + extent + }) + } + + /// The buffer row at `y`, relative to the content origin, and whether `y` + /// is on one of its spacer rows. `None` above the first row, below the + /// last and on ghost lines. + pub(super) fn row_at(&self, y: Pixels) -> Option<(usize, bool)> { + self.row_extents() + .zip(&self.visible_buffer_lines) + .enumerate() + .find_map(|(ix, ((top, height), &row))| { + let (above, below) = self.spacers(ix); + let bottom = top + height; + let below_top = match self.ghost_lines { + Some((ghost_row, ghost_height)) if ghost_row == row => bottom + ghost_height, + _ => bottom, + }; + let spacer = + (y >= top - above && y < top) || (y >= below_top && y < below_top + below); + (spacer || (y >= top && y < bottom)).then_some((row, spacer)) + }) + } + + #[cfg(test)] pub(super) fn local_row_y(&self, row_offset: isize) -> Pixels { self.visible_top + self.line_height * (row_offset as f32) } diff --git a/crates/base/src/input/base/movement.rs b/crates/base/src/input/base/movement.rs index f04821725b..55481f1456 100644 --- a/crates/base/src/input/base/movement.rs +++ b/crates/base/src/input/base/movement.rs @@ -126,9 +126,13 @@ impl InputBaseState { .nearest_visible_display_row(display_point.row) }); let max_display_row = self.display_map.display_row_count().saturating_sub(1); - let target_display_row = current_display_row - .saturating_add_signed(move_lines) - .min(max_display_row); + // A spacer row holds no text: the caret steps past it. + let target_display_row = self.display_map.text_display_row( + current_display_row + .saturating_add_signed(move_lines) + .min(max_display_row), + move_lines > 0, + ); let target_wrap_row = self .display_map .display_row_to_wrap_row(target_display_row) diff --git a/crates/base/src/input/base/state.rs b/crates/base/src/input/base/state.rs index 63815f8c57..986d3d1701 100644 --- a/crates/base/src/input/base/state.rs +++ b/crates/base/src/input/base/state.rs @@ -22,7 +22,7 @@ use sum_tree::Bias; use unicode_segmentation::*; use super::{ - DiagnosticSet, DisplayMap, FoldPlaceholderRenderer, InputContextMenuCapabilities, + DiagnosticSet, DisplayMap, FoldPlaceholderRenderer, GutterColumn, InputContextMenuCapabilities, InputEditorStyle, InputHighlighterFactory, MASK_CHAR, MaskPattern, NativeMenu, NumberStep, WrappingIndent, blink_cursor::BlinkCursor, @@ -37,13 +37,16 @@ use super::{ mode::LayoutMode, undo_manager::{EditIntent, UndoManager}, }; +use crate::ScrollbarPlacement; +use crate::Side; use crate::actions::{SelectDown, SelectLeft, SelectRight, SelectUp}; use crate::input::blink_cursor::CURSOR_WIDTH; use crate::input::movement::MoveDirection; use crate::input::rope_ext::{next_grapheme_boundary, previous_grapheme_boundary}; use crate::input::{ EditorLineNumberRenderer, InputEdit, InputExtras as _, Position, RopeExt as _, - element::RIGHT_MARGIN, layout::LastLayout, + element::RIGHT_MARGIN, + layout::{InputHit, InputHitArea, LastLayout}, }; use crate::overscroll::Overscroll; use crate::{AutoScroll, StepAction, TestSupportExt as _}; @@ -445,6 +448,9 @@ pub struct InputBaseState { pub(super) mode: LayoutMode, pub(super) text: Rope, pub(super) display_map: DisplayMap, + /// The display rows version the spacer provider was last asked at, `None` + /// when it must be asked again. + pub(super) spacers_asked: Option, pub(super) undo_manager: UndoManager, pub(super) inline_tokens: Option>, pub(super) pending_token: Option, @@ -503,6 +509,8 @@ pub struct InputBaseState { /// The fully visible part of the window this input last asked its scroll /// containers to reveal it in, while focused. `None` while unfocused. pub(super) revealed_viewport: Option>, + /// The gutter bounds, `None` without a gutter. + pub(super) last_gutter_bounds: Option>, pub(super) last_selected_range: Option, /// The current edit batch, copied into an event when a change is emitted. pub(super) last_input_edits: Vec<(InputEdit, Rope)>, @@ -551,6 +559,9 @@ pub struct InputBaseState { pub(super) editor_scrollbar_snapshot: Cell>, /// Overview ruler marks in display rows, kept between frames. pub(super) overview_ruler_rows: std::cell::RefCell, + pub(super) scrollbar_placement: ScrollbarPlacement, + pub(super) gutter_side: Side, + pub(super) gutter_order: [GutterColumn; 4], /// The widest measured unwrapped line width and what it was measured for. pub(super) longest_line_width: Cell>, pub(super) editor_paddings: Edges, @@ -583,10 +594,22 @@ pub struct InputBaseState { pub(super) diagnostic_popover: Option>, context_menu_handler: Option< - Rc, &mut Window, &mut App)>, + Rc< + dyn Fn( + NativeMenu, + InputContextMenuCapabilities, + Option, + Point, + &mut Window, + &mut App, + ), + >, >, - pending_context_menu: Option<(Point, usize)>, + pending_context_menu: Option<(Point, usize, Option)>, context_menu_offset: Option, + /// Whether a right-click on the gutter moves the caret to its row, as one + /// on the text does. + pub(super) gutter_context_menu_moves_cursor: bool, /// Whether the context menu that shows on right-click is enabled. /// @@ -700,6 +723,7 @@ pub struct InputPresentation { masked: bool, multi_line: bool, code_editor: bool, + gutter_side: Side, text_align: TextAlign, placeholder: SharedString, mask_placeholder: Option, @@ -741,6 +765,10 @@ impl InputPresentation { self.code_editor } + pub fn gutter_side(&self) -> Side { + self.gutter_side + } + pub fn text_align(&self) -> TextAlign { self.text_align } @@ -794,6 +822,15 @@ impl InputBaseState { /// Text edits use the cached wrapping parameters. Layout refreshes the /// cache after width or font changes; consume that count on a subsequent /// render, or use [`Self::prewrap`] to prepare it before the first layout. + /// + /// The map covers the whole buffer, including lines outside the viewport, + /// and the state owns all updates. Use [`DisplayMap::version`] to + /// invalidate cached mappings after edits, rewrapping, or folding changes. + /// + /// Display coordinates describe text after wrapping and folding, with the + /// spacer rows between lines. They do not include inline completion ghost + /// lines; use [`Self::row_bounds`] for the actual painted geometry of a + /// visible buffer line. pub fn display_map(&self) -> &DisplayMap { &self.display_map } @@ -842,6 +879,7 @@ impl InputBaseState { masked: self.masked, multi_line: self.is_multi_line(), code_editor: self.is_code_editor(), + gutter_side: self.gutter_side, text_align: self.text_align, placeholder: self.placeholder.clone(), mask_placeholder: self.mask_pattern.placeholder(), @@ -923,6 +961,28 @@ impl InputBaseState { handler: Rc< dyn Fn(NativeMenu, InputContextMenuCapabilities, Point, &mut Window, &mut App), >, + ) { + self.context_menu_handler = Some(Rc::new( + move |menu, capabilities, _, position, window, cx| { + handler(menu, capabilities, position, window, cx) + }, + )); + } + + /// Like [`Self::on_context_menu`], also told what the right-click was over. + #[doc(hidden)] + pub fn on_context_menu_with_hit( + &mut self, + handler: Rc< + dyn Fn( + NativeMenu, + InputContextMenuCapabilities, + Option, + Point, + &mut Window, + &mut App, + ), + >, ) { self.context_menu_handler = Some(handler); } @@ -993,6 +1053,7 @@ impl InputBaseState { selection_focus: None, text: "".into(), display_map: DisplayMap::new(text_style.font(), window.rem_size(), None), + spacers_asked: None, search_session: super::SearchSession::default(), search_activation_revision: 0, searchable: false, @@ -1042,6 +1103,7 @@ impl InputBaseState { prepaint_caret_geometry: None, last_bounds: None, revealed_viewport: None, + last_gutter_bounds: None, last_selected_range: None, last_input_edits: Vec::new(), column_select_start: None, @@ -1057,6 +1119,9 @@ impl InputBaseState { scroll_height_f64: 0.0, editor_scrollbar_snapshot: Cell::new(None), overview_ruler_rows: Default::default(), + scrollbar_placement: ScrollbarPlacement::default(), + gutter_side: Side::Left, + gutter_order: GutterColumn::DEFAULT_ORDER, longest_line_width: Cell::new(None), editor_paddings: Edges::default(), deferred_scroll_offset: None, @@ -1073,6 +1138,7 @@ impl InputBaseState { context_menu_handler: None, pending_context_menu: None, context_menu_offset: None, + gutter_context_menu_moves_cursor: true, enable_context_menu: true, completion_inserting: false, overlay_action_handler: None, @@ -1096,6 +1162,25 @@ impl InputBaseState { self } + /// Sets whether a right-click on the gutter moves the caret to the row + /// clicked, as a right-click on the text does. + /// + /// It does by default. Turn it off to keep the selection while a menu for + /// a row of the gutter is open. + pub fn gutter_context_menu_moves_cursor(mut self, moves: bool) -> Self { + self.gutter_context_menu_moves_cursor = moves; + self + } + + pub fn set_gutter_context_menu_moves_cursor(&mut self, moves: bool) { + self.gutter_context_menu_moves_cursor = moves; + } + + /// Returns true when a right-click at `hit` leaves the caret where it is. + fn keeps_cursor_on_context_menu(&self, hit: Option) -> bool { + !self.gutter_context_menu_moves_cursor && hit.is_some_and(|hit| hit.is_gutter()) + } + pub fn set_context_menu_enabled(&mut self, enabled: bool) { self.enable_context_menu = enabled; } @@ -1278,22 +1363,23 @@ impl InputBaseState { let line_height = last_layout.line_height; let target_row = self.text.offset_to_point(offset.min(self.text.len())).row; - let mut row_offset: isize = 0; + let mut y_offset = last_layout.visible_top; for (vi, line) in last_layout.lines.iter().enumerate() { + let (spacer_above, spacer_below) = last_layout.spacers(vi); + y_offset += spacer_above; let buffer_line = last_layout.visible_buffer_lines[vi]; if buffer_line == target_row { - let y_offset = last_layout.local_row_y(row_offset); let prev_lines_offset = last_layout.visible_line_byte_offsets[vi]; let local_offset = offset.saturating_sub(prev_lines_offset).min(line.len()); let pos = line .position_for_index(local_offset, last_layout, false) .unwrap_or_else(|| point(px(0.), px(0.))); let sub_line_index = (pos.y / line_height) as usize; - let adjusted_pos = point(pos.x + last_layout.line_number_width, pos.y + y_offset); + let adjusted_pos = point(pos.x + last_layout.text_origin_x, pos.y + y_offset); return (vi, sub_line_index, Some(adjusted_pos)); } - row_offset += line.wrapped_lines.len() as isize; + y_offset += line.size(line_height).height + spacer_below; } (0, 0, None) } @@ -2641,6 +2727,7 @@ impl InputBaseState { &mut self, position: Point, offset: usize, + hit: Option, window: &mut Window, cx: &mut Context, ) { @@ -2652,11 +2739,12 @@ impl InputBaseState { } self.context_menu_offset = Some(offset); - if !self.active_selection().contains(offset) { + let keep_cursor = self.keeps_cursor_on_context_menu(hit); + if !keep_cursor && !self.active_selection().contains(offset) { self.move_to(offset, None, cx); } - if self.is_code_editor() { + if self.is_code_editor() && !keep_cursor { M::on_hover_definition(self, offset, window, cx); } @@ -2670,7 +2758,7 @@ impl InputBaseState { return; } let previous_focus = window.focused(cx); - handler(NativeMenu::new(), capabilities, position, window, cx); + handler(NativeMenu::new(), capabilities, hit, position, window, cx); // A drawn menu takes focus synchronously; native menus leave it // on the input. Capture it here rather than in the handler. input @@ -2810,6 +2898,9 @@ impl InputBaseState { let mut new_selections = Vec::with_capacity(end_row - start_row + 1); for row in start_row..=end_row { + if self.display_map.is_spacer_row(row) { + continue; + } let sel_start = self .display_map .display_row_column_to_offset(row, start_col); @@ -2920,10 +3011,13 @@ impl InputBaseState { // Show Mouse context menu if event.button == MouseButton::Right { if self.enable_context_menu { - if !self.active_selection().contains(offset) { + let hit = self.hit_test(event.position); + if !self.keeps_cursor_on_context_menu(hit) + && !self.active_selection().contains(offset) + { self.move_to(offset, None, cx); } - self.pending_context_menu = Some((event.position, offset)); + self.pending_context_menu = Some((event.position, offset, hit)); } return; } @@ -2962,8 +3056,8 @@ impl InputBaseState { cx: &mut Context, ) { if event.button == MouseButton::Right { - if let Some((position, offset)) = self.pending_context_menu.take() { - self.handle_right_click_menu(position, offset, window, cx); + if let Some((position, offset, hit)) = self.pending_context_menu.take() { + self.handle_right_click_menu(position, offset, hit, window, cx); } } if self.active_selection().is_empty() { @@ -3265,7 +3359,7 @@ impl InputBaseState { let line = &last_layout.lines[vi]; let local_offset = offset.saturating_sub(last_layout.visible_line_byte_offsets[vi]); if let Some(pos) = line.position_for_index(local_offset, last_layout, false) { - let bounds_width = bounds.size.width - last_layout.line_number_width; + let bounds_width = last_layout.text_width; let col_offset_x = pos.x; if col_offset_x - safety_margin < -scroll_offset.x { // If the position is out of the visible area, scroll to make it visible @@ -3903,7 +3997,7 @@ impl InputBaseState { }; let line_height = last_layout.line_height; - let line_number_width = last_layout.line_number_width; + let text_origin_x = last_layout.text_origin_x; // TIP: About the IBeam cursor // @@ -3915,26 +4009,41 @@ impl InputBaseState { // // - included the input padding. // - included the scroll offset. - let inner_position = position - bounds.origin - point(line_number_width, px(0.)); + let inner_position = position - bounds.origin - point(text_origin_x, px(0.)); - let mut row_offset: isize = 0; + let mut y_offset = last_layout.visible_top; // Position relative to the last line walked, kept for a pointer that ends up // below every line. let mut last_line_pos = None; // Traverse visible buffer lines (compact, no hidden entries) - for (vi, (line_layout, _buffer_line)) in last_layout + for (vi, (line_layout, &buffer_line)) in last_layout .lines .iter() .zip(last_layout.visible_buffer_lines.iter()) .enumerate() { let line_start_offset = last_layout.visible_line_byte_offsets[vi]; - let y_offset = last_layout.local_row_y(row_offset); + let (spacer_above, spacer_below) = last_layout.spacers(vi); + y_offset += spacer_above; + let height = line_layout.size(line_height).height; + // Ghost lines stand between the row's text and its spacers below, + // and push every row after it down, as `row_extents` lays them out. + let ghost_height = match last_layout.ghost_lines { + Some((ghost_row, ghost_height)) if ghost_row == buffer_line => ghost_height, + _ => px(0.), + }; // Calculate line origin for this display row let line_origin = point(px(0.), y_offset); - let pos = inner_position - line_origin; + let mut pos = inner_position - line_origin; + // A pointer on a spacer row, or on the ghost lines, is on the row + // of text it stands beside. + if pos.y < px(0.) && pos.y >= -spacer_above { + pos.y = px(0.); + } else if pos.y >= height && pos.y < height + ghost_height + spacer_below { + pos.y = height - line_height; + } // Return offset by use closest_index_for_x if is single line mode. if self.is_single_line() { @@ -3961,7 +4070,7 @@ impl InputBaseState { return (self.resolve_index(line_start_offset), false, 0); } - row_offset += line_layout.wrapped_lines.len() as isize; + y_offset += height + ghost_height + spacer_below; last_line_pos = Some(pos); } @@ -4497,6 +4606,77 @@ impl InputBaseState { )) } + /// Return the rendered bounds of a zero-based buffer row, across its soft wraps. + /// + /// The bounds span the input from the gutter to the right edge, and follow the + /// row down past inline completion ghost lines above it. Returns `None` when + /// the row is not currently laid out or visible. + pub fn row_bounds(&self, row: usize) -> Option> { + let last_layout = self.last_layout.as_ref()?; + let last_bounds = self.last_bounds?; + let ix = last_layout.visible_buffer_lines.binary_search(&row).ok()?; + let (top, height) = last_layout.row_extents().nth(ix)?; + + Some(Bounds::new( + point(self.input_bounds.origin.x, last_bounds.origin.y + top), + gpui::size(self.input_bounds.size.width, height), + )) + } + + /// Return the bounds of the gutter as last painted, from the text's margin to + /// the outer edge of the input's padding. + /// + /// Returns `None` before the first paint and when the input has no gutter. + pub fn gutter_bounds(&self) -> Option> { + self.last_gutter_bounds + } + + /// Return what `position`, in window coordinates, is over, as last painted. + /// + /// A point on a spacer row is beside the row of text it stands by, as for + /// a click. Returns `None` before the first paint and outside the input. + pub fn hit_test(&self, position: Point) -> Option { + let last_layout = self.last_layout.as_ref()?; + let last_bounds = self.last_bounds?; + let beside = last_layout.row_at(position.y - last_bounds.origin.y); + let spacer = beside.is_some_and(|(_, spacer)| spacer); + + if self + .last_gutter_bounds + .is_some_and(|gutter| gutter.contains(&position)) + { + let folding = self.mode.is_folding(); + let column = last_layout.gutter_order.iter().copied().find(|&column| { + let (x, width) = super::element::gutter_column(last_layout, folding, column); + let left = self.input_bounds.origin.x + x; + position.x >= left && position.x < left + width + }); + return Some(InputHit::new( + InputHitArea::Gutter { column }, + beside.map(|(row, _)| row), + spacer, + )); + } + + // As for the gutter, the ghost lines extend the text below its bounds. + let paddings = self.editor_paddings; + let ghost_height = last_layout.ghost_lines.map_or(px(0.), |(_, height)| height); + let outer = Bounds::from_corners( + self.input_bounds.origin - point(paddings.left, paddings.top), + self.input_bounds.bottom_right() + + point(paddings.right, paddings.bottom + ghost_height), + ); + if !outer.contains(&position) { + return None; + } + let (offset, _) = self.index_for_mouse_position(position); + Some(InputHit::new( + InputHitArea::Text { offset }, + Some(self.text.offset_to_point(offset).row), + spacer, + )) + } + /// Replace text in range in silent. /// /// This will not trigger any UI interaction, such as auto-completion. @@ -5301,13 +5481,12 @@ impl EntityInputHandler for InputBaseState { ) -> Option> { let last_layout = self.last_layout.as_ref()?; let line_height = last_layout.line_height; - let line_number_width = last_layout.line_number_width; let range = self.range_from_utf16(&range_utf16); let mut start_origin = None; let mut end_origin = None; - let line_number_origin = point(line_number_width, px(0.)); - let mut row_offset: isize = 0; + let text_origin = point(last_layout.text_origin_x, px(0.)); + let mut y_offset = last_layout.visible_top; let start_row = self .text @@ -5323,7 +5502,8 @@ impl EntityInputHandler for InputBaseState { break; } - let y_offset = last_layout.local_row_y(row_offset); + let (spacer_above, spacer_below) = last_layout.spacers(vi); + y_offset += spacer_above; let buffer_line = last_layout.visible_buffer_lines[vi]; let index_offset = last_layout.visible_line_byte_offsets[vi]; @@ -5343,13 +5523,13 @@ impl EntityInputHandler for InputBaseState { end_origin = Some(p + point(px(0.), y_offset)); } - row_offset += line.wrapped_lines.len() as isize; + y_offset += line.size(line_height).height + spacer_below; } let start_origin = start_origin.or_else(|| { let offset = self.last_cursor.or(Some(self.cursor()))?; let (_, _, origin) = self.line_and_position_for_offset(offset); - origin.map(|origin| origin - line_number_origin) + origin.map(|origin| origin - text_origin) })?; let mut end_origin = end_origin.unwrap_or(start_origin); // Ensure at same line. @@ -5359,9 +5539,9 @@ impl EntityInputHandler for InputBaseState { } Some(Bounds::from_corners( - bounds.origin + line_number_origin + start_origin, + bounds.origin + text_origin + start_origin, // + line_height for show IME panel under the cursor line. - bounds.origin + line_number_origin + point(end_origin.x, end_origin.y + line_height), + bounds.origin + text_origin + point(end_origin.x, end_origin.y + line_height), )) } @@ -5375,17 +5555,18 @@ impl EntityInputHandler for InputBaseState { // The same origin as `resolve_mouse_position`: past the gutter, at the first // visible line. let inner_point = self.last_bounds?.localize(&point)? - - gpui::point(last_layout.line_number_width, last_layout.visible_top); + - gpui::point(last_layout.text_origin_x, last_layout.visible_top); - let mut row_offset: usize = 0; + let mut line_top = px(0.); for (vi, line) in last_layout.lines.iter().enumerate() { + let (spacer_above, spacer_below) = last_layout.spacers(vi); + line_top += spacer_above; let offset = last_layout.visible_line_byte_offsets[vi]; - let line_top = last_layout.line_height * (row_offset as f32); let line_point = inner_point - gpui::point(px(0.), line_top); if let Some(utf8_index) = line.index_for_position(line_point, last_layout) { return Some(self.offset_to_utf16(self.resolve_index(offset + utf8_index))); } - row_offset += line.wrapped_lines.len(); + line_top += line.size(last_layout.line_height).height + spacer_below; } None @@ -7712,7 +7893,7 @@ mod tests { items2.set(menu.items.len()); menu_focus.focus(window, cx); })); - state.handle_right_click_menu(point(px(0.), px(0.)), 0, window, cx); + state.handle_right_click_menu(point(px(0.), px(0.)), 0, None, window, cx); }) }); assert_eq!(calls.get(), 1); @@ -7732,7 +7913,7 @@ mod tests { // A custom handler may keep using the same, already-focused menu. cx.update(|window, cx| { input.update(cx, |state, cx| { - state.handle_right_click_menu(point(px(0.), px(0.)), 0, window, cx); + state.handle_right_click_menu(point(px(0.), px(0.)), 0, None, window, cx); }); }); assert_eq!(calls.get(), 2); @@ -7743,7 +7924,7 @@ mod tests { cx.update(|window, cx| { input.update(cx, |state, cx| { state.disabled = true; - state.handle_right_click_menu(point(px(0.), px(0.)), 0, window, cx); + state.handle_right_click_menu(point(px(0.), px(0.)), 0, None, window, cx); }) }); assert_eq!(calls.get(), 2); @@ -7766,7 +7947,7 @@ mod tests { state.on_context_menu(Rc::new(move |_, _, _, _, cx| { cursor.set(weak.upgrade().map(|input| input.read(cx).cursor())); })); - state.handle_right_click_menu(point(px(0.), px(0.)), 2, window, cx); + state.handle_right_click_menu(point(px(0.), px(0.)), 2, None, window, cx); }) }); assert_eq!(cursor.get(), Some(2)); @@ -7795,7 +7976,7 @@ mod tests { })); })); // A right-click inside the selection keeps the cursor at its end. - state.handle_right_click_menu(point(px(0.), px(0.)), 2, window, cx); + state.handle_right_click_menu(point(px(0.), px(0.)), 2, None, window, cx); }) }); assert_eq!(seen.get(), Some((11, Some(2)))); @@ -13681,6 +13862,68 @@ impl InputBaseState { cx.notify(); } + /// The placement of the scrollbars, default is [`ScrollbarPlacement::BottomRight`]. + /// + /// On the left, the vertical scrollbar sits on the input's left edge, over + /// the gutter when that is on the left too; otherwise the text keeps clear + /// of it. At the top, the horizontal scrollbar overlays the first line, as + /// at the bottom it overlays the last. + pub fn scrollbar_placement(mut self, placement: ScrollbarPlacement) -> Self { + self.scrollbar_placement = placement; + self + } + + /// See [`InputBaseState::scrollbar_placement`]. + pub fn set_scrollbar_placement( + &mut self, + placement: ScrollbarPlacement, + cx: &mut Context, + ) { + self.scrollbar_placement = placement; + cx.notify(); + } + + /// The side of the gutter with the line numbers and fold icons, default is + /// [`Side::Left`]. + /// + /// [`Side::Right`] is for the left pane of a side-by-side diff, so that both + /// gutters face the center and corresponding line numbers sit next to each + /// other. On the right, the gutter is mirrored: its columns keep their order + /// from the text outward, see [`InputBaseState::gutter_order`], and the + /// line numbers are aligned toward the text. A vertical scrollbar on the + /// same side stays outermost. + pub fn gutter_side(mut self, side: Side) -> Self { + self.gutter_side = side; + self + } + + /// See [`InputBaseState::gutter_side`]. + pub fn set_gutter_side(&mut self, side: Side, cx: &mut Context) { + self.gutter_side = side; + cx.notify(); + } + + /// The order of the gutter's columns from the text outward, default is + /// `[GutterColumn::FoldIcons, GutterColumn::LineNumbers, GutterColumn::Markers, + /// GutterColumn::Decorations]`. + /// + /// A column left out follows the listed ones in its default order, and a + /// repeated one is ignored. The order holds on either side. + pub fn gutter_order(mut self, columns: impl IntoIterator) -> Self { + self.gutter_order = GutterColumn::order(columns); + self + } + + /// See [`InputBaseState::gutter_order`]. + pub fn set_gutter_order( + &mut self, + columns: impl IntoIterator, + cx: &mut Context, + ) { + self.gutter_order = GutterColumn::order(columns); + cx.notify(); + } + /// Set the soft wrap mode, default is true. #[doc(hidden)] pub fn soft_wrap(mut self, wrap: bool) -> Self { @@ -13963,18 +14206,18 @@ impl InputBaseState { /// Horizontal offset from the content area's left edge to unscrolled source text. /// - /// Includes the laid-out gap, line numbers, folding controls, and gutter - /// decorations. Excludes input-frame padding, horizontal scrolling, and - /// text alignment. For left-aligned text, add this to the content area's - /// origin and the horizontal scroll offset to recover the text origin. + /// With the gutter on the left, includes the laid-out gap, line numbers, + /// folding controls, and gutter decorations; with it on the right, only the + /// clearance kept from a scrollbar on the left. Excludes input-frame padding, + /// horizontal scrolling, and text alignment. For left-aligned text, add this + /// to the content area's origin and the horizontal scroll offset to recover + /// the text origin. /// /// Returns `None` before the first layout. Like [`Self::range_to_bounds`], /// this describes the most recent layout; render again after changing /// gutter settings or typography before using it to align a static view. pub fn text_origin_offset(&self) -> Option { - self.last_layout - .as_ref() - .map(|layout| layout.line_number_width) + self.last_layout.as_ref().map(|layout| layout.text_origin_x) } /// Set enable/disable line number. diff --git a/crates/base/src/input/editor/display_map/display_map.rs b/crates/base/src/input/editor/display_map/display_map.rs index 3bbe3dbd65..7cecbaa913 100644 --- a/crates/base/src/input/editor/display_map/display_map.rs +++ b/crates/base/src/input/editor/display_map/display_map.rs @@ -1,6 +1,6 @@ /// DisplayMap: Public facade for Editor/Input display mapping. /// -/// This combines WrapMap and FoldMap to provide a unified API: +/// This combines WrapMap, FoldMap and SpacerMap to provide a unified API: /// - BufferPoint ↔ DisplayPoint conversion /// - Fold management (candidates, toggle, query) /// - Automatic projection updates on text/layout changes @@ -11,24 +11,41 @@ use ropey::Rope; use super::fold_map::FoldMap; use super::folding::FoldRange; +use super::spacer_map::{DisplayRow, SpacerMap}; pub use super::text_wrapper::WrappingIndent; use super::text_wrapper::{LineItem, WrapDisplayPoint}; use super::wrap_map::WrapMap; use super::{BufferPoint, DisplayPoint}; use crate::input::Point as TreeSitterPoint; +use crate::input::Spacer; use crate::input::display_map::WrapPoint; use crate::input::rope_ext::RopeExt as _; /// DisplayMap is the main interface for Editor/Input coordinate mapping. /// -/// It manages the two-layer projection: +/// It manages the three-layer projection: /// 1. Buffer → Wrap (soft-wrapping) -/// 2. Wrap → Display (folding) +/// 2. Wrap → Fold (folding) +/// 3. Fold → Display (spacers) /// -/// Editor/Input only needs to work with BufferPoint and DisplayPoint. +/// [`crate::input::InputBaseState::display_map`] exposes the editor-owned map +/// through a shared reference for application coordinate queries. Text edits, +/// wrapping, and folding remain owned by the editor state. +/// +/// Coordinates describe the prepared text projection, including offscreen +/// lines. They exclude inline completion ghost lines and other painted geometry. pub struct DisplayMap { wrap_map: WrapMap, fold_map: FoldMap, + spacer_map: SpacerMap, + /// The spacers as they were last set, before projection. + spacers: Vec, + /// The rows version the spacers were last projected at, `None` when they + /// must be projected again. + spacers_projected: Option, + /// Counts the changes of the spacers, so that [`Self::version`] moves with + /// them. + spacers_version: usize, } impl DisplayMap { @@ -36,6 +53,10 @@ impl DisplayMap { Self { wrap_map: WrapMap::new(font, font_size, wrap_width), fold_map: FoldMap::new(), + spacer_map: SpacerMap::default(), + spacers: Vec::new(), + spacers_projected: None, + spacers_version: 0, } } @@ -46,39 +67,74 @@ impl DisplayMap { // Buffer → Wrap let wrap_pos = self.wrap_map.buffer_pos_to_wrap_pos(pos); - // Wrap → Display - if let Some(display_row) = self.fold_map.wrap_row_to_display_row(wrap_pos.row) { - DisplayPoint::new(display_row, wrap_pos.col) + // Wrap → Fold → Display + if let Some(fold_row) = self.fold_map.wrap_row_to_display_row(wrap_pos.row) { + DisplayPoint::new( + self.spacer_map.fold_row_to_display_row(fold_row), + wrap_pos.col, + ) } else { // Cursor is in a folded region, find nearest visible row - let display_row = self.fold_map.nearest_visible_display_row(wrap_pos.row); + let display_row = self.nearest_visible_display_row(wrap_pos.row); DisplayPoint::new(display_row, 0) // Column 0 at fold boundary } } /// Convert display position to buffer position + /// + /// A spacer row is read as the nearest row of the line it stands beside. pub fn display_pos_to_buffer_pos(&self, pos: DisplayPoint) -> BufferPoint { - // Display → Wrap - let wrap_row = self.fold_map.display_row_to_wrap_row(pos.row).unwrap_or(0); + // Display → Fold → Wrap + let wrap_row = self + .fold_map + .display_row_to_wrap_row(self.text_fold_row(pos.row)) + .unwrap_or(0); // Wrap → Buffer let wrap_pos = WrapPoint::new(wrap_row, pos.col); self.wrap_map.wrap_pos_to_buffer_pos(wrap_pos) } - /// Get total number of visible display rows + /// A number that changes whenever a buffer line may have taken different + /// display rows: an edit, a rewrap, a change of folds or of spacers. + /// + /// Compare versions for equality on the same map to invalidate cached + /// queries. The counter can wrap; it is not a document revision or a count + /// of edits. Scrolling and inline completion ghost lines do not change it, + /// nor does a [`crate::input::SpacerProvider`] answering with the spacers + /// already shown. + #[inline] + pub fn version(&self) -> usize { + self.rows_version().wrapping_add(self.spacers_version) + } + + /// Like [`Self::version`], without the spacers: what the spacers are + /// placed by and asked for again at, so that an answer does not ask anew. + #[inline] + pub(crate) fn rows_version(&self) -> usize { + self.wrap_map + .wrapper() + .version() + .wrapping_add(self.fold_map.version()) + } + + /// Get total number of visible display rows, spacer rows included #[inline] pub fn display_row_count(&self) -> usize { - self.fold_map.display_row_count() + self.fold_map.display_row_count() + self.spacer_map.row_count() } /// Get the buffer line for a given display row + /// + /// A spacer row belongs to the line it stands beside. pub fn display_row_to_buffer_line(&self, display_row: usize) -> usize { - // Display → Wrap - let wrap_row = self - .fold_map - .display_row_to_wrap_row(display_row) - .unwrap_or(0); + let fold_row = match self.spacer_map.display_row(display_row) { + DisplayRow::Text(fold_row) => fold_row, + DisplayRow::Spacer(index) => return self.spacer_map.run(index).line, + }; + + // Fold → Wrap + let wrap_row = self.fold_map.display_row_to_wrap_row(fold_row).unwrap_or(0); // Wrap → Buffer line self.wrap_map.wrap_row_to_buffer_line(wrap_row) @@ -86,7 +142,19 @@ impl DisplayMap { /// Get the display row range for a buffer line: [start, end) /// Returns None if the buffer line is completely hidden + /// + /// The range holds the rows of the line's text, not its spacers. pub fn buffer_line_to_display_row_range(&self, line: usize) -> Option> { + let rows = self.fold_row_range(line)?; + Some( + self.spacer_map.fold_row_to_display_row(rows.start) + ..self.spacer_map.fold_row_to_display_row(rows.end - 1) + 1, + ) + } + + /// The fold rows of a buffer line: [start, end) + /// Returns None if the buffer line is completely hidden + fn fold_row_range(&self, line: usize) -> Option> { // Buffer line → Wrap row range let wrap_row_range = self.wrap_map.buffer_line_to_wrap_row_range(line); @@ -123,11 +191,108 @@ impl DisplayMap { Some(range) => range.start, None => { let wrap_row = self.wrap_map.buffer_line_to_first_wrap_row(line); - self.fold_map.nearest_visible_display_row(wrap_row) + self.nearest_visible_display_row(wrap_row) + } + } + } + + // ==================== Spacers ==================== + + /// Replace the spacers. They are placed again whenever the rows move. + pub(crate) fn set_spacers(&mut self, spacers: Vec) { + if spacers == self.spacers { + return; + } + self.spacers = spacers; + self.spacers_version = self.spacers_version.wrapping_add(1); + self.spacers_projected = None; + self.project_spacers(); + } + + /// How many spacer rows there are, beside lines not hidden by a fold. + #[inline] + pub(crate) fn spacer_row_count(&self) -> usize { + self.spacer_map.row_count() + } + + /// Whether a display row is a spacer row: a blank row that holds no text, + /// standing above or below a line. See [`Spacer`]. + pub fn is_spacer_row(&self, display_row: usize) -> bool { + matches!( + self.spacer_map.display_row(display_row), + DisplayRow::Spacer(_) + ) + } + + /// How many spacer rows stand above and below a buffer line. + pub(crate) fn spacer_rows_beside(&self, line: usize) -> (usize, usize) { + self.spacer_map.rows_beside(line) + } + + /// The spacer rows that have a background, beside the buffer lines within + /// `lines`: the display rows they take, and the color. + pub(crate) fn spacer_backgrounds( + &self, + lines: Range, + ) -> impl Iterator, gpui::Hsla)> + '_ { + self.spacer_map + .runs_beside(lines) + .filter_map(|(start, run)| Some((start..start + run.rows, run.background?))) + } + + /// The display row of text nearest a display row: the row itself when it + /// holds text, else the first one past its spacers in the direction of + /// `forward`, or the other way when there is none that way. + pub(crate) fn text_display_row(&self, display_row: usize, forward: bool) -> usize { + let row = display_row.min(self.display_row_count().saturating_sub(1)); + let DisplayRow::Spacer(index) = self.spacer_map.display_row(row) else { + return row; + }; + let before = self.spacer_map.run(index).before; + let fold_row = if forward && before < self.fold_map.display_row_count() { + before + } else { + before.saturating_sub(1) + }; + self.spacer_map.fold_row_to_display_row(fold_row) + } + + /// The fold row a display row stands for: its own, or for a spacer row the + /// nearest row of the line it stands beside. + fn text_fold_row(&self, display_row: usize) -> usize { + match self.spacer_map.display_row(display_row) { + DisplayRow::Text(fold_row) => fold_row, + DisplayRow::Spacer(index) => { + let run = self.spacer_map.run(index); + if run.above { + run.before + } else { + run.before.saturating_sub(1) + } } } } + /// Place the spacers again if the rows moved since they were last placed. + fn project_spacers(&mut self) { + if self.spacers.is_empty() && self.spacer_map.row_count() == 0 { + return; + } + let version = self.rows_version(); + if self.spacers_projected == Some(version) { + return; + } + self.spacers_projected = Some(version); + let line_count = self.buffer_line_count(); + let mut map = std::mem::take(&mut self.spacer_map); + map.rebuild(&self.spacers, |line| { + (line < line_count) + .then(|| self.fold_row_range(line)) + .flatten() + }); + self.spacer_map = map; + } + /// Set fold candidates (from tree-sitter/LSP) pub fn set_fold_candidates(&mut self, candidates: Vec) { self.fold_map.set_candidates(candidates); @@ -319,6 +484,7 @@ impl DisplayMap { self.fold_map .mark_dirty_with_wrap_count(self.wrap_map.wrap_row_count()); } + self.project_spacers(); } // ==================== Wrap Display Point Operations ==================== @@ -365,25 +531,32 @@ impl DisplayMap { /// Returns None if the wrap row is folded. #[inline] pub fn wrap_row_to_display_row(&self, wrap_row: usize) -> Option { - self.fold_map.wrap_row_to_display_row(wrap_row) + self.fold_map + .wrap_row_to_display_row(wrap_row) + .map(|fold_row| self.spacer_map.fold_row_to_display_row(fold_row)) } /// Find the nearest visible display row for a given wrap row. #[inline] pub fn nearest_visible_display_row(&self, wrap_row: usize) -> usize { - self.fold_map.nearest_visible_display_row(wrap_row) + self.spacer_map + .fold_row_to_display_row(self.fold_map.nearest_visible_display_row(wrap_row)) } /// Convert a display row to a wrap row. + /// Returns None for a spacer row. #[inline] pub fn display_row_to_wrap_row(&self, display_row: usize) -> Option { - self.fold_map.display_row_to_wrap_row(display_row) + match self.spacer_map.display_row(display_row) { + DisplayRow::Text(fold_row) => self.fold_map.display_row_to_wrap_row(fold_row), + DisplayRow::Spacer(_) => None, + } } pub(crate) fn display_row_column_to_offset(&self, display_row: usize, column: usize) -> usize { let wrap_row = self .fold_map - .display_row_to_wrap_row(display_row) + .display_row_to_wrap_row(self.text_fold_row(display_row)) .unwrap_or(0); self.wrap_map .wrapper() diff --git a/crates/base/src/input/editor/display_map/fold_map.rs b/crates/base/src/input/editor/display_map/fold_map.rs index 32c6b0a29a..34b8deeba9 100644 --- a/crates/base/src/input/editor/display_map/fold_map.rs +++ b/crates/base/src/input/editor/display_map/fold_map.rs @@ -51,6 +51,9 @@ pub(super) struct FoldMap { /// Used for lazy evaluation to avoid expensive rebuilds on every text change needs_rebuild: bool, + /// Bumped whenever the folded ranges change. + version: usize, + /// Cached wrap_row_count from last rebuild /// Used to detect if WrapMap changed and rebuild is needed cached_wrap_row_count: usize, @@ -66,6 +69,7 @@ impl FoldMap { folded: Vec::new(), needs_rebuild: true, cached_wrap_row_count: 0, + version: 0, } } @@ -167,11 +171,15 @@ impl FoldMap { self.candidates = candidates; // Remove any folded ranges that are no longer in candidates + let folded = self.folded.len(); self.folded.retain(|fold| { self.candidates .iter() .any(|c| c.start_line == fold.start_line) }); + if self.folded.len() != folded { + self.version = self.version.wrapping_add(1); + } } /// Merge new candidates extracted from an edited region into existing candidates. @@ -205,12 +213,17 @@ impl FoldMap { self.folded.push(*candidate); self.folded.sort_by_key(|r| r.start_line); self.needs_rebuild = true; + self.version = self.version.wrapping_add(1); } } } else { // Remove from folded + let folded = self.folded.len(); self.folded.retain(|f| f.start_line != start_line); self.needs_rebuild = true; + if self.folded.len() != folded { + self.version = self.version.wrapping_add(1); + } } } @@ -236,6 +249,12 @@ impl FoldMap { &self.candidates } + /// A number that changes whenever the folded ranges change. + #[inline] + pub(super) fn version(&self) -> usize { + self.version + } + /// Get all currently folded ranges #[inline] pub(super) fn folded_ranges(&self) -> &[FoldRange] { @@ -245,7 +264,10 @@ impl FoldMap { /// Clear all folds #[inline] pub(super) fn clear_folds(&mut self) { - self.folded.clear(); + if !self.folded.is_empty() { + self.folded.clear(); + self.version = self.version.wrapping_add(1); + } } /// Adjust folds and candidates after a text edit. @@ -262,6 +284,7 @@ impl FoldMap { ) { // Adjust folded ranges if !self.folded.is_empty() { + self.version = self.version.wrapping_add(1); self.folded.retain(|fold| { !(fold.start_line <= edit_end_line && fold.end_line >= edit_start_line) }); diff --git a/crates/base/src/input/editor/display_map/mod.rs b/crates/base/src/input/editor/display_map/mod.rs index 0ebaf62215..58b1997abd 100644 --- a/crates/base/src/input/editor/display_map/mod.rs +++ b/crates/base/src/input/editor/display_map/mod.rs @@ -2,7 +2,8 @@ /// /// This module implements a layered display mapping architecture: /// - **WrapMap**: Handles soft-wrapping (buffer → wrap rows) -/// - **FoldMap**: Handles folding (wrap rows → display rows) +/// - **FoldMap**: Handles folding (wrap rows → fold rows) +/// - **SpacerMap**: Handles spacers (fold rows → display rows) /// - **DisplayMap**: Public facade for Editor/Input /// /// The goal is to provide a clean, unified API where Editor only needs to know @@ -12,6 +13,7 @@ mod inline_line; pub(crate) use inline_line::{InlineFragment, InputLine}; mod fold_map; mod folding; +mod spacer_map; mod text_wrapper; mod wrap_map; diff --git a/crates/base/src/input/editor/display_map/spacer_map.rs b/crates/base/src/input/editor/display_map/spacer_map.rs new file mode 100644 index 0000000000..0c8011b75b --- /dev/null +++ b/crates/base/src/input/editor/display_map/spacer_map.rs @@ -0,0 +1,266 @@ +/// SpacerMap: Spacer projection layer (Fold rows → Display rows). +/// +/// This module adds blank rows above or below buffer lines, the inverse of +/// what [`FoldMap`](super::fold_map::FoldMap) does: +/// - Placing each spacer between the fold rows of its line and its neighbor +/// - Maintaining bidirectional mapping: fold row ↔ display row +/// - Telling a spacer row from a row that holds text +use std::ops::Range; + +use gpui::Hsla; + +use crate::input::Spacer; + +/// Blank rows standing together between two fold rows. +#[derive(Debug, Clone, PartialEq)] +pub(super) struct SpacerRows { + /// The fold row the rows stand above, or the fold row count when they + /// stand below the last one. + pub(super) before: usize, + /// The buffer line the rows belong to. + pub(super) line: usize, + /// Whether the rows stand above `line` rather than below it. + pub(super) above: bool, + pub(super) rows: usize, + pub(super) background: Option, + /// How many spacer rows the runs before this one hold. + rows_before: usize, +} + +impl SpacerRows { + /// The first display row of the run. + fn display_start(&self) -> usize { + self.before + self.rows_before + } + + /// The display row after the run. + fn display_end(&self) -> usize { + self.display_start() + self.rows + } +} + +/// What a display row shows. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum DisplayRow { + /// A row of text: this fold row. + Text(usize), + /// A row of the spacer run at this index. + Spacer(usize), +} + +/// SpacerMap projects fold rows to display rows by inserting spacer rows. +#[derive(Default)] +pub(super) struct SpacerMap { + /// The spacer runs, in display order: sorted by `before`, and at one place + /// the rows below a line before the rows above the next one. + runs: Vec, + /// How many rows the runs hold in total. + total: usize, +} + +impl SpacerMap { + /// Place `spacers` between fold rows; `fold_rows` gives the fold rows of a + /// buffer line, or `None` for a line that is hidden or does not exist. + pub(super) fn rebuild( + &mut self, + spacers: &[Spacer], + fold_rows: impl Fn(usize) -> Option>, + ) { + let mut runs: Vec = spacers + .iter() + .filter(|spacer| spacer.rows() > 0) + .filter_map(|spacer| { + let rows = fold_rows(spacer.line())?; + Some(SpacerRows { + before: if spacer.is_above() { + rows.start + } else { + rows.end + }, + line: spacer.line(), + above: spacer.is_above(), + rows: spacer.rows(), + background: spacer.background(), + rows_before: 0, + }) + }) + .collect(); + runs.sort_by_key(|run| (run.before, run.above)); + + let mut total = 0; + for run in &mut runs { + run.rows_before = total; + total += run.rows; + } + self.runs = runs; + self.total = total; + } + + /// How many rows the spacers hold in total. + pub(super) fn row_count(&self) -> usize { + self.total + } + + /// How many spacer rows the runs before `index` hold. + fn rows_before(&self, index: usize) -> usize { + self.runs + .get(index) + .map_or(self.total, |run| run.rows_before) + } + + /// The display row of a fold row: pushed down by every spacer row above it. + pub(super) fn fold_row_to_display_row(&self, fold_row: usize) -> usize { + let index = self.runs.partition_point(|run| run.before <= fold_row); + fold_row + self.rows_before(index) + } + + /// What a display row shows: a fold row or a spacer row. + pub(super) fn display_row(&self, display_row: usize) -> DisplayRow { + let index = self + .runs + .partition_point(|run| run.display_end() <= display_row); + match self.runs.get(index) { + Some(run) if run.display_start() <= display_row => DisplayRow::Spacer(index), + _ => DisplayRow::Text(display_row - self.rows_before(index)), + } + } + + /// The spacer run at `index`. + pub(super) fn run(&self, index: usize) -> &SpacerRows { + &self.runs[index] + } + + /// The spacer runs beside the buffer lines within `lines`, in display order, + /// each with the display row it starts at. + pub(super) fn runs_beside( + &self, + lines: Range, + ) -> impl Iterator + '_ { + let start = self.runs.partition_point(|run| run.line < lines.start); + self.runs[start..] + .iter() + .take_while(move |run| run.line < lines.end) + .map(|run| (run.display_start(), run)) + } + + /// How many spacer rows stand above and below a buffer line. + pub(super) fn rows_beside(&self, line: usize) -> (usize, usize) { + self.runs_beside(line..line + 1) + .fold((0, 0), |(above, below), (_, run)| { + if run.above { + (above + run.rows, below) + } else { + (above, below + run.rows) + } + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// One entry per display row: `Some(fold row)` for text, `None` for a + /// spacer row — the projection built row by row, the slow obvious way. + fn dense_projection(fold_row_count: usize, spacers: &[(usize, usize)]) -> Vec> { + let mut rows = Vec::new(); + for fold_row in 0..=fold_row_count { + for &(before, count) in spacers { + if before == fold_row { + rows.extend(std::iter::repeat_n(None, count)); + } + } + if fold_row < fold_row_count { + rows.push(Some(fold_row)); + } + } + rows + } + + /// Lines of one, three, one, two and one rows; line 3 hidden by a fold. + fn lines() -> Vec>> { + vec![ + Some(0..1), + Some(1..4), + Some(4..5), + None, + Some(5..7), + Some(7..8), + ] + } + + fn map(spacers: &[Spacer]) -> SpacerMap { + let lines = lines(); + let mut map = SpacerMap::default(); + map.rebuild(spacers, |line| lines.get(line).cloned().flatten()); + map + } + + #[test] + fn spacer_runs_match_the_dense_projection() { + let spacers = [ + Spacer::above(0, 2), + Spacer::below(1, 1), + Spacer::above(2, 3), + Spacer::below(3, 4), + Spacer::below(5, 2), + Spacer::below(6, 9), + Spacer::above(4, 0), + ]; + let map = map(&spacers); + // Line 3 is hidden and line 6 does not exist; a spacer of no rows is none. + let dense = dense_projection(8, &[(0, 2), (4, 1), (4, 3), (8, 2)]); + assert_eq!(map.row_count(), 8); + + for (display_row, expected) in dense.iter().enumerate() { + match (map.display_row(display_row), expected) { + (DisplayRow::Text(fold_row), Some(expected)) => { + assert_eq!(fold_row, *expected, "display row {display_row}"); + assert_eq!(map.fold_row_to_display_row(fold_row), display_row); + } + (DisplayRow::Spacer(_), None) => {} + (shown, expected) => { + panic!("display row {display_row}: {shown:?}, expected {expected:?}") + } + } + } + assert_eq!( + map.display_row(dense.len()), + DisplayRow::Text(8), + "past the end is past the last fold row" + ); + } + + #[test] + fn the_rows_below_a_line_come_before_the_rows_above_the_next() { + let map = map(&[Spacer::above(2, 3), Spacer::below(1, 1)]); + let runs: Vec<_> = map + .runs_beside(0..6) + .map(|(start, run)| (start, run.line)) + .collect(); + assert_eq!(runs, vec![(4, 1), (5, 2)]); + assert_eq!(map.rows_beside(1), (0, 1)); + assert_eq!(map.rows_beside(2), (3, 0)); + assert_eq!(map.rows_beside(4), (0, 0)); + } + + #[test] + fn a_line_with_spacers_on_both_sides_counts_both() { + let background = gpui::red(); + let map = map(&[ + Spacer::below(4, 2).with_background(background), + Spacer::above(4, 1), + ]); + assert_eq!(map.rows_beside(4), (1, 2)); + let runs: Vec<_> = map + .runs_beside(4..5) + .map(|(start, run)| (start, run.above, run.background)) + .collect(); + assert_eq!(runs, vec![(5, true, None), (8, false, Some(background))]); + // The line's two rows stand between its spacers. + assert_eq!(map.fold_row_to_display_row(5), 6); + assert_eq!(map.fold_row_to_display_row(6), 7); + assert_eq!(map.display_row(8), DisplayRow::Spacer(1)); + assert_eq!(map.display_row(10), DisplayRow::Text(7)); + } +} diff --git a/crates/base/src/input/editor/display_map/text_wrapper.rs b/crates/base/src/input/editor/display_map/text_wrapper.rs index 56c46c2e7b..b44500a0f1 100644 --- a/crates/base/src/input/editor/display_map/text_wrapper.rs +++ b/crates/base/src/input/editor/display_map/text_wrapper.rs @@ -519,6 +519,8 @@ pub(crate) struct TextWrapper { inline_metrics: Rc<[(Range, Pixels)]>, /// Exact native widths avoid reshaping the same prefix when a drag crosses wrap thresholds. width_measurements: Rc>, + /// Bumped whenever the lines are wrapped again. + version: usize, /// Whether the font measures printable ASCII by lookup; `None` until first needed. monospace: Option>>, scratch: WrapScratch, @@ -542,6 +544,7 @@ impl TextWrapper { lines: SumTree::new(&()), inline_metrics: Rc::from([]), width_measurements: Rc::default(), + version: 0, monospace: None, scratch: WrapScratch::default(), char_widths: CharWidths::default(), @@ -574,6 +577,12 @@ impl TextWrapper { self.lines.summary().wrap_rows } + /// A number that changes whenever the lines are wrapped again. + #[inline] + pub(crate) fn version(&self) -> usize { + self.version + } + /// Get the total number of buffer lines. #[inline] pub(crate) fn lines_count(&self) -> usize { @@ -1138,6 +1147,7 @@ impl TextWrapper { } self.text = changed_text.clone(); + self.version = self.version.wrapping_add(1); } /// Update the text wrapper and recalculate the wrapped lines. @@ -2298,6 +2308,16 @@ mod tests { wrap_width: None, wrapping_indent: WrappingIndent::default(), line_number_width: px(0.), + gutter_gap: px(0.), + gutter_marker_width: px(0.), + gutter_decorations_width: px(0.), + ghost_lines: None, + spacer_rows: Vec::new(), + gutter_side: crate::Side::Left, + gutter_order: crate::input::GutterColumn::DEFAULT_ORDER, + text_origin_x: px(0.), + gutter_origin_x: px(0.), + text_width: px(0.), space_width: px(0.), cursor_bounds: None, text_align: TextAlign::Left, @@ -2632,6 +2652,16 @@ mod tests { wrap_width: Some(px(10.)), wrapping_indent: WrappingIndent::Same, line_number_width: px(0.), + gutter_gap: px(0.), + gutter_marker_width: px(0.), + gutter_decorations_width: px(0.), + ghost_lines: None, + spacer_rows: Vec::new(), + gutter_side: crate::Side::Left, + gutter_order: crate::input::GutterColumn::DEFAULT_ORDER, + text_origin_x: px(0.), + gutter_origin_x: px(0.), + text_width: px(0.), space_width: px(0.), cursor_bounds: None, text_align: TextAlign::Left, diff --git a/crates/base/src/input/editor/highlighting.rs b/crates/base/src/input/editor/highlighting.rs index b4f52aee9f..1fc6e2ddd9 100644 --- a/crates/base/src/input/editor/highlighting.rs +++ b/crates/base/src/input/editor/highlighting.rs @@ -1,9 +1,9 @@ use std::{ops::Range, rc::Rc, sync::Arc}; -use gpui::{AnyElement, Context, HighlightStyle, Hsla, SharedString, Window}; +use gpui::{AbsoluteLength, AnyElement, Context, HighlightStyle, Hsla, SharedString, Window, px}; use ropey::Rope; -use super::{EditorState, FoldRange, InputEdit}; +use super::{EditorState, FoldRange, GutterMarker, InputEdit}; use crate::SemanticThemeTokens; /// Resolves semantic highlight names into renderable GPUI styles. @@ -77,6 +77,8 @@ pub type InputHighlighterFactory = Rc Option; pub type FoldIconRenderer = Rc AnyElement>; pub type FoldPlaceholderRenderer = Rc AnyElement>; +/// Renders a [`GutterMarker`] within the size supplied by [`InputEditorStyle`]. +pub type GutterMarkerRenderer = Rc AnyElement>; /// Where in the syntax tree an offset sits, for editing decisions. /// @@ -106,7 +108,11 @@ pub struct DiagnosticColors { } /// Application-owned colors and highlight resolver consumed by editor painting. +/// +/// Start from [`Default`]. Configure gutter markers through its builders; +/// existing fields retain their direct-access API. #[derive(Clone)] +#[non_exhaustive] pub struct InputEditorStyle { pub foreground: Hsla, pub muted_foreground: Hsla, @@ -120,9 +126,48 @@ pub struct InputEditorStyle { pub editor_active_line: Option, pub editor_gutter_background: Option, pub fold_icon_renderer: Option, + /// Renders line decoration gutter markers; without one, markers are not painted. + gutter_marker_renderer: Option, + gutter_marker_size: AbsoluteLength, + gutter_marker_gap: AbsoluteLength, } impl InputEditorStyle { + /// Set the gutter marker renderer, or `None` to stop rendering markers. + pub fn with_gutter_marker_renderer(mut self, renderer: Option) -> Self { + self.gutter_marker_renderer = renderer; + self + } + + /// The gutter marker renderer, if one has been supplied. + pub fn gutter_marker_renderer(&self) -> Option<&GutterMarkerRenderer> { + self.gutter_marker_renderer.as_ref() + } + + /// Set the square marker size. The presentation layer supplies its scale. + /// + /// Defaults to zero; configure this together with the renderer. + pub fn with_gutter_marker_size(mut self, size: impl Into) -> Self { + self.gutter_marker_size = size.into(); + self + } + + /// The square marker size, resolved against the window's rem during layout. + pub fn gutter_marker_size(&self) -> AbsoluteLength { + self.gutter_marker_size + } + + /// Set the gap between markers and line numbers. Defaults to zero. + pub fn with_gutter_marker_gap(mut self, gap: impl Into) -> Self { + self.gutter_marker_gap = gap.into(); + self + } + + /// The gap between markers and line numbers. + pub fn gutter_marker_gap(&self) -> AbsoluteLength { + self.gutter_marker_gap + } + /// Fills in every colour that was left unset, from the active palette. /// /// `Hsla::default()` is fully transparent, and every colour on `Default` is @@ -175,16 +220,20 @@ impl Default for InputEditorStyle { editor_active_line: None, editor_gutter_background: None, fold_icon_renderer: None, + gutter_marker_renderer: None, + gutter_marker_size: px(0.).into(), + gutter_marker_gap: px(0.).into(), } } } #[cfg(test)] mod tests { - use gpui::hsla; + use gpui::{IntoElement as _, hsla, px, rems}; - use super::InputEditorStyle; + use super::{GutterMarkerRenderer, InputEditorStyle}; use crate::SemanticThemeTokens; + use std::rc::Rc; fn dark() -> SemanticThemeTokens { let mut tokens = SemanticThemeTokens::default(); @@ -196,6 +245,29 @@ mod tests { tokens } + #[test] + fn test_input_editor_style_builder() { + let renderer: GutterMarkerRenderer = Rc::new(|_| gpui::Empty.into_any_element()); + let style = InputEditorStyle::default() + .with_gutter_marker_renderer(Some(renderer)) + .with_gutter_marker_size(rems(0.75)) + .with_gutter_marker_gap(rems(0.25)); + // Palette resolution and cloning must preserve the presentation seam. + let resolved = style.resolved(&dark()); + assert!(Rc::ptr_eq( + resolved.gutter_marker_renderer().unwrap(), + style.gutter_marker_renderer().unwrap() + )); + assert_eq!(resolved.gutter_marker_size().to_pixels(px(32.)), px(24.)); + assert_eq!(resolved.gutter_marker_gap().to_pixels(px(32.)), px(8.)); + assert!( + resolved + .with_gutter_marker_renderer(None) + .gutter_marker_renderer() + .is_none() + ); + } + #[test] fn an_unprojected_style_takes_its_ink_from_the_palette() { let tokens = dark(); diff --git a/crates/base/src/input/editor/indent.rs b/crates/base/src/input/editor/indent.rs index 66faf319de..342c659375 100644 --- a/crates/base/src/input/editor/indent.rs +++ b/crates/base/src/input/editor/indent.rs @@ -123,15 +123,17 @@ impl TextElement { let tab_size = state.mode.tab_size(); let line_height = last_layout.line_height; let mut builder = PathBuilder::stroke(px(1.)); - let mut row_offset: isize = 0; + let mut offset_y = last_layout.visible_top; let mut last_indents = vec![]; - for (&buffer_line, line_layout) in last_layout + for (ix, (&buffer_line, line_layout)) in last_layout .visible_buffer_lines .iter() .zip(last_layout.lines.iter()) + .enumerate() { - let offset_y = last_layout.local_row_y(row_offset); + let (spacer_above, spacer_below) = last_layout.spacers(ix); + offset_y += spacer_above; let line = state.text.slice_line(buffer_line); let mut current_indents = vec![]; if line.len() > 0 { @@ -143,7 +145,7 @@ impl TextElement { px(0.) }; - let pos = point(x + last_layout.line_number_width, offset_y); + let pos = point(x + last_layout.text_origin_x, offset_y); builder.move_to(pos); builder.line_to(point(pos.x, pos.y + line_height)); @@ -158,7 +160,7 @@ impl TextElement { current_indents = last_indents.clone(); } - row_offset += line_layout.wrapped_lines.len() as isize; + offset_y += line_layout.wrapped_lines.len() * line_height + spacer_below; last_indents = current_indents; } diff --git a/crates/base/src/input/editor/line_decorations.rs b/crates/base/src/input/editor/line_decorations.rs new file mode 100644 index 0000000000..2ffb9af18e --- /dev/null +++ b/crates/base/src/input/editor/line_decorations.rs @@ -0,0 +1,407 @@ +use std::{collections::BTreeMap, ops::Range, rc::Rc}; + +use gpui::{App, Context, Hsla, SharedString, WeakEntity}; + +use super::{EditorMode, InputBaseState}; + +/// The meaning of a gutter marker beside a row. +/// +/// How a marker looks is chosen by +/// [`InputEditorStyle::gutter_marker_renderer`](super::InputEditorStyle::gutter_marker_renderer). +#[non_exhaustive] +#[derive(Clone, Debug, PartialEq)] +pub enum GutterMarker { + /// A row a diff added. + DiffAdded, + /// A row a diff removed. + DiffRemoved, + /// A row a diff changed. + DiffChanged, + /// A merge conflict awaiting resolution. + Conflict, + /// A row the user bookmarked. + Bookmark, + /// A breakpoint. + Breakpoint, + /// An application-chosen icon, painted as given. + Custom { + /// The SVG asset path of the icon, for example `icons/star.svg`. + icon: SharedString, + /// The color the icon is painted in. + color: Hsla, + }, +} + +/// A decoration of one whole buffer row: a background band, a gutter marker, or both. +#[derive(Clone, Debug, PartialEq)] +pub struct LineDecoration { + row: usize, + background: Option, + marker: Option, +} + +impl LineDecoration { + /// Create an empty decoration for a zero-based buffer row. + pub fn new(row: usize) -> Self { + Self { + row, + background: None, + marker: None, + } + } + + /// The zero-based buffer row this decoration covers. + pub fn row(&self) -> usize { + self.row + } + + /// The color of the background band, if any. + pub fn background(&self) -> Option { + self.background + } + + /// The gutter marker, if any. + pub fn marker(&self) -> Option<&GutterMarker> { + self.marker.as_ref() + } + + /// Paint a band of `color` across the whole row. + pub fn with_background(mut self, color: Hsla) -> Self { + self.background = Some(color); + self + } + + /// Paint `marker` in the row's gutter. + pub fn with_marker(mut self, marker: GutterMarker) -> Self { + self.marker = Some(marker); + self + } +} + +/// Supplies the line decorations of the rows an editor paints. +/// +/// The editor asks on every frame with the visible buffer rows and ignores +/// decorations outside them, so an implementation must be cheap. Colors may be +/// read from `cx`, so they follow theme changes. +pub trait LineDecorationProvider { + /// Return the decorations for rows within `rows`. + fn line_decorations(&self, rows: Range, cx: &App) -> Vec; +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +struct LineDecorationCollectionId(usize); + +/// An independently managed collection of line decorations, supplied by a +/// [`LineDecorationProvider`]. +/// +/// Clones address the same collection. Dropping a handle does not clear it; use +/// [`Self::clear`] to stop painting it or [`Self::dispose`] to release it permanently. +/// Operations on a disposed collection or a dropped editor are harmless no-ops. +#[derive(Clone, Debug)] +pub struct LineDecorationCollection { + state: WeakEntity>, + id: LineDecorationCollectionId, +} + +impl LineDecorationCollection { + /// Replace this collection's provider. The next frame asks the new one. + pub fn set_provider(&self, provider: Rc, cx: &mut App) { + self.update(Some(provider), cx); + } + + /// Stop painting this collection without invalidating its handles. + pub fn clear(&self, cx: &mut App) { + self.update(None, cx); + } + + /// Release this collection, invalidating all of its cloned handles. + pub fn dispose(&self, cx: &mut App) { + let _ = self.state.update(cx, |state, cx| { + if state.extras.line_decorations.remove(self.id) { + cx.notify(); + } + }); + } + + /// Whether this collection has a provider; `false` once cleared, disposed or dropped. + pub fn has_provider(&self, cx: &App) -> bool { + self.state + .read_with(cx, |state, _| { + state.extras.line_decorations.has_provider(self.id) + }) + .unwrap_or(false) + } + + fn update(&self, provider: Option>, cx: &mut App) { + let _ = self.state.update(cx, |state, cx| { + if state.extras.line_decorations.set(self.id, provider) { + cx.notify(); + } + }); + } +} + +/// The line decoration providers of one editor, in creation order. +#[derive(Default)] +pub(crate) struct LineDecorationProviders { + entries: BTreeMap>>, + next_id: usize, +} + +impl LineDecorationProviders { + fn create(&mut self, provider: Rc) -> LineDecorationCollectionId { + let id = LineDecorationCollectionId(self.next_id); + self.next_id += 1; + self.entries.insert(id, Some(provider)); + id + } + + fn set( + &mut self, + id: LineDecorationCollectionId, + provider: Option>, + ) -> bool { + let Some(entry) = self.entries.get_mut(&id) else { + return false; + }; + *entry = provider; + true + } + + fn remove(&mut self, id: LineDecorationCollectionId) -> bool { + self.entries.remove(&id).is_some() + } + + fn has_provider(&self, id: LineDecorationCollectionId) -> bool { + self.entries.get(&id).is_some_and(Option::is_some) + } + + pub(crate) fn has_any_provider(&self) -> bool { + self.entries.values().any(Option::is_some) + } + + /// Ask every provider about `rows`, in creation order, keeping only the + /// decorations that fall within `rows`. + pub(crate) fn query(&self, rows: Range, cx: &App) -> Vec { + if rows.is_empty() { + return Vec::new(); + } + let mut decorations = Vec::new(); + for provider in self.entries.values().flatten() { + decorations.extend( + provider + .line_decorations(rows.clone(), cx) + .into_iter() + .filter(|decoration| rows.contains(&decoration.row)), + ); + } + decorations + } +} + +impl InputBaseState { + /// Create an independently owned collection of line decorations, supplied by + /// `provider`. + /// + /// The provider is asked for the visible rows on every frame. Unlike text and + /// range decorations, rows are not tracked across edits: the provider answers + /// for the text as it is when asked. + /// + /// A background spans the whole row, gutter included, across its soft wraps, + /// under the active line, indent guides, selections and text. A marker is + /// painted in a slot of its own, only while the line numbers are shown. In + /// the default order the slot sits between the line numbers and the outer + /// edge of the gutter; [`InputBaseState::gutter_order`] can move it nearer + /// the text. The gutter reserves the slot while any collection has a + /// provider and a marker renderer is set. Later collections paint over earlier + /// ones. Neither affects hit testing or focus. Collections live until + /// explicitly disposed or the editor is dropped. + pub fn create_line_decorations_collection( + &mut self, + provider: Rc, + cx: &mut Context, + ) -> LineDecorationCollection { + let id = self.extras.line_decorations.create(provider); + cx.notify(); + LineDecorationCollection { + state: cx.entity().downgrade(), + id, + } + } +} + +#[cfg(test)] +mod tests { + use std::cell::RefCell; + + use gpui::{AppContext as _, TestAppContext, hsla}; + + use super::*; + use crate::input::EditorState; + + /// Marks every row it is asked about whose index is a multiple of `every`, + /// and records each range it was asked for. + struct EveryNth { + every: usize, + marker: GutterMarker, + asked: RefCell>>, + } + + impl EveryNth { + fn new(every: usize, marker: GutterMarker) -> Rc { + Rc::new(Self { + every, + marker, + asked: RefCell::default(), + }) + } + } + + impl LineDecorationProvider for EveryNth { + fn line_decorations(&self, rows: Range, _: &App) -> Vec { + self.asked.borrow_mut().push(rows.clone()); + // One past each end too: the editor must drop what it did not ask for. + (rows.start.saturating_sub(1)..rows.end + 1) + .filter(|row| row % self.every == 0) + .map(|row| LineDecoration::new(row).with_marker(self.marker.clone())) + .collect() + } + } + + fn editor(cx: &mut TestAppContext) -> gpui::Entity { + cx.update(crate::init); + let window = cx.add_empty_window(); + window.update(|window, cx| cx.new(|cx| EditorState::new(window, cx))) + } + + #[test] + fn a_decoration_is_built_from_its_parts() { + let color = hsla(0.3, 0.5, 0.5, 0.2); + let decoration = LineDecoration::new(7); + assert_eq!(decoration.row(), 7); + assert_eq!(decoration.background(), None); + assert_eq!(decoration.marker(), None); + + let decoration = decoration + .with_background(color) + .with_marker(GutterMarker::Bookmark); + assert_eq!(decoration.background(), Some(color)); + assert_eq!(decoration.marker(), Some(&GutterMarker::Bookmark)); + } + + #[gpui::test] + fn line_decoration_collection_round_trips(cx: &mut TestAppContext) { + let editor = editor(cx); + let provider = EveryNth::new(1, GutterMarker::DiffAdded); + + let collection = editor.update(cx, |state, cx| { + assert!(state.extras.line_decorations.entries.is_empty()); + state.create_line_decorations_collection(provider.clone(), cx) + }); + cx.read(|cx| assert!(collection.has_provider(cx))); + + // Cleared: the handle stays usable, and nothing is asked. + cx.update(|cx| collection.clear(cx)); + cx.read(|cx| { + assert!(!collection.has_provider(cx)); + let state = editor.read(cx); + assert!(state.extras.line_decorations.query(0..4, cx).is_empty()); + }); + + // A clone addresses the same collection. + cx.update(|cx| collection.clone().set_provider(provider.clone(), cx)); + cx.read(|cx| { + assert!(collection.has_provider(cx)); + let state = editor.read(cx); + assert_eq!(state.extras.line_decorations.query(0..2, cx).len(), 2); + }); + + // Disposed: every handle is spent, and setting a provider is a no-op. + cx.update(|cx| { + collection.dispose(cx); + collection.set_provider(provider.clone(), cx); + }); + cx.read(|cx| { + assert!(!collection.has_provider(cx)); + let state = editor.read(cx); + assert!(state.extras.line_decorations.query(0..4, cx).is_empty()); + }); + } + + #[gpui::test] + fn collections_are_independent_and_asked_in_creation_order(cx: &mut TestAppContext) { + let editor = editor(cx); + let bookmarks = EveryNth::new(2, GutterMarker::Bookmark); + let breakpoints = EveryNth::new(3, GutterMarker::Breakpoint); + + let (first, second) = editor.update(cx, |state, cx| { + ( + state.create_line_decorations_collection(bookmarks.clone(), cx), + state.create_line_decorations_collection(breakpoints.clone(), cx), + ) + }); + + let query = |cx: &mut TestAppContext, rows: Range| { + cx.read(|cx| { + editor + .read(cx) + .extras + .line_decorations + .query(rows, cx) + .into_iter() + .map(|decoration| (decoration.row(), decoration.marker().cloned().unwrap())) + .collect::>() + }) + }; + + // Out-of-range answers are dropped; the first collection comes first. + assert_eq!( + query(cx, 1..7), + vec![ + (2, GutterMarker::Bookmark), + (4, GutterMarker::Bookmark), + (6, GutterMarker::Bookmark), + (3, GutterMarker::Breakpoint), + (6, GutterMarker::Breakpoint), + ] + ); + assert_eq!(*bookmarks.asked.borrow(), vec![1..7]); + assert_eq!(*breakpoints.asked.borrow(), vec![1..7]); + + // An empty range asks nobody. + assert!(query(cx, 3..3).is_empty()); + assert_eq!(bookmarks.asked.borrow().len(), 1); + + // Disposing one owner's collection leaves the other's alone. + cx.update(|cx| first.dispose(cx)); + assert_eq!( + query(cx, 0..4), + vec![(0, GutterMarker::Breakpoint), (3, GutterMarker::Breakpoint)] + ); + cx.read(|cx| assert!(second.has_provider(cx))); + + // A collection created after a disposal gets a fresh identity. + let third = editor.update(cx, |state, cx| { + state.create_line_decorations_collection(bookmarks.clone(), cx) + }); + assert_ne!(third.id, first.id); + cx.read(|cx| assert!(!first.has_provider(cx))); + } + + #[gpui::test] + fn a_dropped_editor_makes_its_collections_no_ops(cx: &mut TestAppContext) { + let editor = editor(cx); + let collection = editor.update(cx, |state, cx| { + state.create_line_decorations_collection(EveryNth::new(1, GutterMarker::Conflict), cx) + }); + drop(editor); + cx.run_until_parked(); + + cx.update(|cx| { + collection.set_provider(EveryNth::new(1, GutterMarker::DiffChanged), cx); + collection.clear(cx); + collection.dispose(cx); + assert!(!collection.has_provider(cx)); + }); + } +} diff --git a/crates/base/src/input/editor/mod.rs b/crates/base/src/input/editor/mod.rs index 7dcd32eac0..218bfa3830 100644 --- a/crates/base/src/input/editor/mod.rs +++ b/crates/base/src/input/editor/mod.rs @@ -394,6 +394,22 @@ impl crate::input::InputExtras for super::EditorExtras { self.overview_ruler_decorations.revision() } + fn line_decorations( + &self, + rows: std::ops::Range, + cx: &App, + ) -> Vec { + self.line_decorations.query(rows, cx) + } + + fn has_line_decorations(&self) -> bool { + self.line_decorations.has_any_provider() + } + + fn spacer_provider(&self) -> Option> { + self.spacer_provider.clone() + } + fn semantic_token_styles( &self, text: &ropey::Rope, diff --git a/crates/base/src/input/editor/spacers.rs b/crates/base/src/input/editor/spacers.rs new file mode 100644 index 0000000000..afe5032034 --- /dev/null +++ b/crates/base/src/input/editor/spacers.rs @@ -0,0 +1,107 @@ +use std::{ops::Range, rc::Rc}; + +use gpui::{App, Context, Hsla}; + +use super::{EditorMode, InputBaseState}; + +/// Blank rows an editor shows above or below a buffer line. +/// +/// A spacer row holds no text: it has no line number, the caret never stands +/// on it, and line decorations, selections and search matches pass it by. +/// Two editors shown side by side pad their shorter lines with spacers, so that +/// lines paired across them start level however each one wraps. +#[derive(Clone, Debug, PartialEq)] +pub struct Spacer { + line: usize, + rows: usize, + above: bool, + background: Option, +} + +impl Spacer { + /// Create `rows` blank rows below a zero-based buffer line, after its last + /// soft-wrapped row. + pub fn below(line: usize, rows: usize) -> Self { + Self { + line, + rows, + above: false, + background: None, + } + } + + /// Create `rows` blank rows above a zero-based buffer line, before its first + /// row. + pub fn above(line: usize, rows: usize) -> Self { + Self { + above: true, + ..Self::below(line, rows) + } + } + + /// The zero-based buffer line the rows stand beside. + pub fn line(&self) -> usize { + self.line + } + + /// How many blank rows there are. + pub fn rows(&self) -> usize { + self.rows + } + + /// Whether the rows stand above the line rather than below it. + pub fn is_above(&self) -> bool { + self.above + } + + /// The color the rows are filled with, if any. + pub fn background(&self) -> Option { + self.background + } + + /// Fill the rows with `color`, gutter included. + pub fn with_background(mut self, color: Hsla) -> Self { + self.background = Some(color); + self + } +} + +/// Supplies the spacers of an editor. +/// +/// Unlike line decorations, spacers move every row below them, so the editor +/// asks for those of every line at once and keeps the answer: when the provider +/// is set, after an edit, after the text is wrapped again or a fold changes, +/// and when [`InputBaseState::refresh_spacers`] is called. A spacer on a line +/// hidden by a fold, or past the last line, is not shown. +pub trait SpacerProvider { + /// Return the spacers of the buffer lines within `lines`. + fn spacers(&self, lines: Range, cx: &App) -> Vec; +} + +impl InputBaseState { + /// Set the provider of this editor's spacers, or `None` to show none. + /// + /// The provider is asked during the next layout, after the text has been + /// wrapped to the editor's width, so it can read how many rows each line + /// takes from [`InputBaseState::display_map`] — of this editor and of + /// another one it pads against. + pub fn set_spacer_provider( + &mut self, + provider: Option>, + cx: &mut Context, + ) { + self.extras.spacer_provider = provider; + self.spacers_asked = None; + cx.notify(); + } + + /// Ask the spacer provider again during the next layout. + /// + /// The editor asks by itself after its own rows change; call this when + /// something the answer depends on changes elsewhere, such as the rows of + /// another editor this one is padded against. + pub fn refresh_spacers(&mut self, cx: &mut Context) { + self.spacers_asked = None; + cx.notify(); + } +} diff --git a/crates/base/src/input/mod.rs b/crates/base/src/input/mod.rs index 29c6909985..7055a13c88 100644 --- a/crates/base/src/input/mod.rs +++ b/crates/base/src/input/mod.rs @@ -53,6 +53,8 @@ mod language; pub mod language_config; #[path = "base/layout.rs"] mod layout; +#[path = "editor/line_decorations.rs"] +mod line_decorations; #[path = "editor/lsp/mod.rs"] mod lsp; #[path = "base/mask_pattern.rs"] @@ -70,6 +72,8 @@ mod scrollbar_presentation; mod search; #[path = "base/selection.rs"] mod selection; +#[path = "editor/spacers.rs"] +mod spacers; #[path = "base/state.rs"] mod state; #[path = "base/tab_stops.rs"] @@ -101,9 +105,9 @@ pub use diagnostics::{ pub use display_map::{BufferPoint, DisplayMap, DisplayPoint, FoldRange, WrappingIndent}; pub use editor::{Editor, EditorLineNumberRenderer, EditorState}; pub use highlighting::{ - DiagnosticColors, FoldIconRenderer, FoldPlaceholderRenderer, HighlightStyleResolver, - InputEditorStyle, InputHighlighter, InputHighlighterFactory, SharedHighlightStyleResolver, - SyntaxContext, SyntaxContextProvider, + DiagnosticColors, FoldIconRenderer, FoldPlaceholderRenderer, GutterMarkerRenderer, + HighlightStyleResolver, InputEditorStyle, InputHighlighter, InputHighlighterFactory, + SharedHighlightStyleResolver, SyntaxContext, SyntaxContextProvider, }; pub use indent::TabSize; pub use input::{Input, InputState}; @@ -115,6 +119,10 @@ pub(crate) use language::EditorLanguage; pub use language::{LanguageProvider, set_language_config, set_language_provider}; pub(crate) use language_config::LanguageConfig; pub use language_config::{AutoClosingPair, BracketPair, IndentationRules}; +pub use layout::{GutterColumn, InputHit, InputHitArea}; +pub use line_decorations::{ + GutterMarker, LineDecoration, LineDecorationCollection, LineDecorationProvider, +}; pub use lsp::{ CodeActionItem, CodeActionMenuState, CodeActionProvider, CompletionHighlighter, CompletionMenuOptions, CompletionMenuState, CompletionProvider, DefinitionProvider, @@ -131,5 +139,6 @@ pub use native::{NativeMenu, NativeMenuItem}; pub use rope_ext::{InputEdit, Point, RopeExt, RopeLines}; pub use ropey::Rope; pub use search::{SearchMatcher, SearchSession}; +pub use spacers::{Spacer, SpacerProvider}; pub use state::*; pub use textarea::{Textarea, TextareaState}; diff --git a/crates/base/src/input/scrollbar_presentation.rs b/crates/base/src/input/scrollbar_presentation.rs index ddb0d93115..4561f04868 100644 --- a/crates/base/src/input/scrollbar_presentation.rs +++ b/crates/base/src/input/scrollbar_presentation.rs @@ -1,5 +1,5 @@ //! Presentation hook for an editor's existing viewport, without a second scroll system. -use crate::{ScrollbarAxis, ScrollbarHandle}; +use crate::{ScrollbarAxis, ScrollbarHandle, ScrollbarPlacement}; use gpui::{AnyElement, App, Bounds, Pixels, Point, ScrollHandle, Size, Window}; use std::rc::Rc; @@ -16,6 +16,7 @@ pub struct EditorScrollbarContext { pub(crate) content_height_f64: f64, pub(crate) scroll_y_f64: f64, pub(crate) axis: ScrollbarAxis, + pub(crate) placement: ScrollbarPlacement, } impl EditorScrollbarContext { @@ -23,6 +24,12 @@ impl EditorScrollbarContext { self.axis } + /// Where the editor places its scrollbars, as set with + /// `scrollbar_placement`, for a supplied scrollbar to follow. + pub fn placement(&self) -> ScrollbarPlacement { + self.placement + } + /// Authoritative vertical content height in `f64` pixels (including padding /// when combined via `scroll_viewport_size`). pub fn content_height_f64(&self) -> f64 { diff --git a/crates/base/src/lib.rs b/crates/base/src/lib.rs index 51e9ef6f30..eec27db44d 100644 --- a/crates/base/src/lib.rs +++ b/crates/base/src/lib.rs @@ -178,7 +178,7 @@ pub use scrollable_mask::{ }; pub use scrollbar::{ Scrollbar, ScrollbarAxis, ScrollbarEntrance, ScrollbarHandle, ScrollbarMode, ScrollbarMotion, - ScrollbarStyles, ScrollbarThumbStyle, ScrollbarTrackStyle, + ScrollbarPlacement, ScrollbarStyles, ScrollbarThumbStyle, ScrollbarTrackStyle, }; pub use select::Select; pub use selectable_text::SelectableText; diff --git a/crates/base/src/scrollbar.rs b/crates/base/src/scrollbar.rs index 9ffcc7a339..ecf721c9f1 100644 --- a/crates/base/src/scrollbar.rs +++ b/crates/base/src/scrollbar.rs @@ -473,10 +473,21 @@ impl VisibilityAnimation { } } -fn visibility_translation(axis: Axis, track_width: Pixels, progress: f32) -> Point { +fn visibility_translation( + axis: Axis, + placement: ScrollbarPlacement, + track_width: Pixels, + progress: f32, +) -> Point { let offset = track_width * (1.0 - progress.clamp(0.0, 1.0)); if axis.is_vertical() { - point(offset, px(0.)) + if placement.is_left() { + point(-offset, px(0.)) + } else { + point(offset, px(0.)) + } + } else if placement.is_top() { + point(px(0.), -offset) } else { point(px(0.), offset) } @@ -635,6 +646,36 @@ pub enum ScrollbarAxis { Both, } +/// Where the scrollbars sit in the viewport. +/// +/// A single-axis scrollbar uses only the part of the placement for its axis. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum ScrollbarPlacement { + /// Vertical scrollbar on the right, horizontal scrollbar at the bottom. + #[default] + BottomRight, + /// Vertical scrollbar on the left, horizontal scrollbar at the bottom. + BottomLeft, + /// Vertical scrollbar on the right, horizontal scrollbar at the top. + TopRight, + /// Vertical scrollbar on the left, horizontal scrollbar at the top. + TopLeft, +} + +impl ScrollbarPlacement { + /// Return true if the vertical scrollbar is on the left. + #[inline] + pub fn is_left(&self) -> bool { + matches!(self, Self::BottomLeft | Self::TopLeft) + } + + /// Return true if the horizontal scrollbar is at the top. + #[inline] + pub fn is_top(&self) -> bool { + matches!(self, Self::TopRight | Self::TopLeft) + } +} + /// Paint-only styles for a scrollbar track. #[derive(Clone, Default)] pub struct ScrollbarTrackStyle { @@ -814,12 +855,14 @@ impl ScrollbarAxis { pub struct Scrollbar { pub(crate) id: ElementId, axis: ScrollbarAxis, + placement: ScrollbarPlacement, mode: Option, scroll_handle: Rc, scroll_size: Option>, viewport_bounds: Option>, // Scroll range may use a smaller viewport than the padded track bounds. scroll_viewport_size: Option>, + horizontal_viewport_bounds: Option>, use_layout_bounds: bool, /// Maximum frames per second for scrolling by drag. Default is 120 FPS. /// @@ -839,12 +882,14 @@ impl Scrollbar { Self { id: ElementId::CodeLocation(*caller), axis: ScrollbarAxis::Both, + placement: ScrollbarPlacement::default(), mode: None, scroll_handle: Rc::new(scroll_handle.clone()), max_fps: 120, scroll_size: None, viewport_bounds: None, scroll_viewport_size: None, + horizontal_viewport_bounds: None, use_layout_bounds: false, styles: ScrollbarStyles::default(), } @@ -870,6 +915,13 @@ impl Scrollbar { self } + /// Editors can exclude a fixed gutter from horizontal scrolling while the + /// vertical track stays at the outside edge of the full viewport. + pub(crate) fn horizontal_viewport_bounds(mut self, bounds: Bounds) -> Self { + self.horizontal_viewport_bounds = Some(bounds); + self + } + /// Set the scrollbar show mode [`ScrollbarMode`]. /// /// If unset, the current application theme projection is used. @@ -928,6 +980,15 @@ impl Scrollbar { self } + /// Set the scrollbar placement, default is [`ScrollbarPlacement::BottomRight`]. + /// + /// When both scrollbars are shown, the horizontal track ends before the + /// vertical one, on the vertical scrollbar's side. + pub fn placement(mut self, placement: ScrollbarPlacement) -> Self { + self.placement = placement; + self + } + pub fn styles(mut self, build: impl FnOnce(ScrollbarStyles) -> ScrollbarStyles) -> Self { self.styles = build(self.styles); self @@ -955,6 +1016,21 @@ impl Scrollbar { cx.theme().scrollbar.styles().track.width.unwrap_or(WIDTH) } + fn track_width(&self, cx: &App) -> Pixels { + self.styles + .track + .width + .or(cx.theme().scrollbar.styles().track.width) + .unwrap_or(WIDTH) + } + + /// The width the scrollbar takes from the edge it sits on: its track, or + /// its active thumb where that reaches further. + pub(crate) fn full_width(&self, cx: &App) -> Pixels { + let (_, _, _, width, inset, _, _) = self.style_for_active(cx); + self.track_width(cx).max(inset + width) + } + fn resolve_track( &self, cx: &App, @@ -1388,31 +1464,34 @@ impl Element for Scrollbar { for axis in self.axis.all().into_iter() { let is_vertical = axis.is_vertical(); - let track_width = self - .styles - .track - .width - .or(cx.theme().scrollbar.styles().track.width) - .unwrap_or(WIDTH); + let viewport = if is_vertical { + hitbox.bounds + } else { + self.horizontal_viewport_bounds.unwrap_or(hitbox.bounds) + }; + let track_width = self.track_width(cx); let (scroll_area_size, container_size, scroll_viewport_size, scroll_position) = if is_vertical { ( scroll_size.height, - hitbox.size.height, + viewport.size.height, scroll_viewport_size.height, self.scroll_handle.offset().y, ) } else { + // Keep the scroll range unchanged when only the track's + // viewport excludes a fixed gutter. + let excluded = hitbox.size.width - viewport.size.width; ( - scroll_size.width, - hitbox.size.width, - scroll_viewport_size.width, + scroll_size.width - excluded, + viewport.size.width, + scroll_viewport_size.width - excluded, self.scroll_handle.offset().x, ) }; // The horizontal scrollbar is set avoid overlapping with the vertical scrollbar, if the vertical scrollbar is visible. - let margin_end = if has_both && !is_vertical { + let margin = if has_both && !is_vertical { track_width } else { px(0.) @@ -1426,24 +1505,30 @@ impl Element for Scrollbar { let bounds = Bounds { origin: if is_vertical { - point( - hitbox.origin.x + hitbox.size.width - track_width, - hitbox.origin.y, - ) + if self.placement.is_left() { + viewport.origin + } else { + point( + viewport.origin.x + viewport.size.width - track_width, + viewport.origin.y, + ) + } + } else if self.placement.is_top() { + viewport.origin } else { point( - hitbox.origin.x, - hitbox.origin.y + hitbox.size.height - track_width, + viewport.origin.x, + viewport.origin.y + viewport.size.height - track_width, ) }, size: gpui::Size { width: if is_vertical { track_width } else { - hitbox.size.width + viewport.size.width }, height: if is_vertical { - hitbox.size.height + viewport.size.height } else { track_width }, @@ -1499,57 +1584,65 @@ impl Element for Scrollbar { } else { bounds.origin.x }; + let track_origin = if !is_vertical && self.placement.is_left() { + origin + margin + } else { + origin + }; let geometry = ThumbGeometry::new( - origin, + track_origin, container_size, scroll_viewport_size, scroll_area_size, - margin_end, + margin, inset, min_length, ); let (_, _, _, _, active_inset, _, active_min_length) = self.style_for_active(cx); let active_geometry = ThumbGeometry::new( - origin, + track_origin, container_size, scroll_viewport_size, scroll_area_size, - margin_end, + margin, active_inset, active_min_length, ); let thumb_start = geometry.start(scroll_position) - origin; - // The clickable area of the thumb let thumb_length = geometry.length; - let thumb_bounds = if is_vertical { - Bounds::from_anchor_and_size( - Anchor::TopRight, - bounds.top_right() + point(-inset, thumb_start), - size(track_width, thumb_length), - ) + let (thumb_anchor, thumb_origin) = if is_vertical { + if self.placement.is_left() { + (Anchor::TopLeft, bounds.origin + point(inset, thumb_start)) + } else { + ( + Anchor::TopRight, + bounds.top_right() + point(-inset, thumb_start), + ) + } + } else if self.placement.is_top() { + (Anchor::TopLeft, bounds.origin + point(thumb_start, inset)) } else { - Bounds::from_anchor_and_size( + ( Anchor::BottomLeft, bounds.bottom_left() + point(thumb_start, -inset), - size(thumb_length, track_width), ) }; + let thumb_size = |width: Pixels| { + if is_vertical { + size(width, thumb_length) + } else { + size(thumb_length, width) + } + }; + + // The clickable area of the thumb + let thumb_bounds = + Bounds::from_anchor_and_size(thumb_anchor, thumb_origin, thumb_size(track_width)); // The actual render area of the thumb - let thumb_fill_bounds = if is_vertical { - Bounds::from_anchor_and_size( - Anchor::TopRight, - bounds.top_right() + point(-inset, thumb_start), - size(thumb_width, thumb_length), - ) - } else { - Bounds::from_anchor_and_size( - Anchor::BottomLeft, - bounds.bottom_left() + point(thumb_start, -inset), - size(thumb_length, thumb_width), - ) - }; + let thumb_fill_bounds = + Bounds::from_anchor_and_size(thumb_anchor, thumb_origin, thumb_size(thumb_width)); let bar_hitbox = window.with_content_mask(Some(ContentMask { bounds }), |window| { window.insert_hitbox(bounds, gpui::HitboxBehavior::Normal) @@ -1616,8 +1709,12 @@ impl Element for Scrollbar { let is_vertical = axis.is_vertical(); let visibility_opacity = state.visibility_opacity; let is_visible = state.visibility_requested || visibility_opacity > 0.0; - let translation = - visibility_translation(axis, state.track_width, state.visibility_position); + let translation = visibility_translation( + axis, + self.placement, + state.track_width, + state.visibility_position, + ); let painted_bounds = state.bounds + translation; let painted_thumb_bounds = state.thumb_fill_bounds + translation; let painted_track_bg = state.bg.opacity(visibility_opacity); @@ -2034,7 +2131,12 @@ mod tests { assert_eq!(shown.position, 1.0); assert!(!shown.running, "a motionless theme must request no frames"); assert_eq!( - visibility_translation(Axis::Vertical, px(16.), shown.position), + visibility_translation( + Axis::Vertical, + ScrollbarPlacement::BottomRight, + px(16.), + shown.position + ), Point::default() ); @@ -2104,18 +2206,29 @@ mod tests { #[test] fn visibility_translation_moves_toward_the_nearest_edge() { - assert_eq!( - visibility_translation(Axis::Vertical, px(16.), 0.0), - point(px(16.), px(0.)) - ); - assert_eq!( - visibility_translation(Axis::Horizontal, px(16.), 0.0), - point(px(0.), px(16.)) - ); - assert_eq!( - visibility_translation(Axis::Vertical, px(16.), 1.0), - Point::default() - ); + for (placement, vertical, horizontal) in [ + (ScrollbarPlacement::BottomRight, px(16.), px(16.)), + (ScrollbarPlacement::BottomLeft, px(-16.), px(16.)), + (ScrollbarPlacement::TopRight, px(16.), px(-16.)), + (ScrollbarPlacement::TopLeft, px(-16.), px(-16.)), + ] { + assert_eq!( + visibility_translation(Axis::Vertical, placement, px(16.), 0.0), + point(vertical, px(0.)) + ); + assert_eq!( + visibility_translation(Axis::Horizontal, placement, px(16.), 0.0), + point(px(0.), horizontal) + ); + assert_eq!( + visibility_translation(Axis::Vertical, placement, px(16.), 1.0), + Point::default() + ); + assert_eq!( + visibility_translation(Axis::Horizontal, placement, px(16.), 1.0), + Point::default() + ); + } } #[test] @@ -2287,13 +2400,17 @@ mod tests { struct ScrollbarHarness { handle: TestHandle, axis: ScrollbarAxis, + placement: ScrollbarPlacement, mode: ScrollbarMode, scroll_viewport_size: Option>, } impl Render for ScrollbarHarness { fn render(&mut self, _: &mut Window, _: &mut Context) -> impl gpui::IntoElement { - let mut scrollbar = Scrollbar::new(&self.handle).axis(self.axis).mode(self.mode); + let mut scrollbar = Scrollbar::new(&self.handle) + .axis(self.axis) + .placement(self.placement) + .mode(self.mode); if let Some(size) = self.scroll_viewport_size { scrollbar = scrollbar.scroll_viewport_size(size); } @@ -2307,6 +2424,16 @@ mod tests { axis: ScrollbarAxis, mode: ScrollbarMode, content_size: Size, + ) -> (&mut VisualTestContext, TestHandle) { + harness_with_placement(cx, axis, ScrollbarPlacement::default(), mode, content_size) + } + + fn harness_with_placement( + cx: &mut TestAppContext, + axis: ScrollbarAxis, + placement: ScrollbarPlacement, + mode: ScrollbarMode, + content_size: Size, ) -> (&mut VisualTestContext, TestHandle) { let handle = TestHandle::new(content_size); let (_, cx) = cx.add_window_view({ @@ -2314,6 +2441,7 @@ mod tests { move |_, _| ScrollbarHarness { handle, axis, + placement, mode, scroll_viewport_size: None, } @@ -2330,6 +2458,7 @@ mod tests { move |_, _| ScrollbarHarness { handle, axis: ScrollbarAxis::Vertical, + placement: ScrollbarPlacement::default(), mode: ScrollbarMode::Always, scroll_viewport_size: Some(size(px(100.), px(80.))), } @@ -2482,6 +2611,23 @@ mod tests { }); } + #[gpui::test] + fn the_full_width_is_the_track_or_an_active_thumb_reaching_further(cx: &mut TestAppContext) { + cx.update(|cx| { + let scrollbar = Scrollbar::vertical(&TestHandle::new(Size::default())); + assert_eq!(scrollbar.full_width(cx), Scrollbar::width()); + + crate::Theme::global_mut(cx).scrollbar = crate::ScrollbarTheme::new() + .with_styles(ScrollbarStyles::default().track(|style| style.width(px(24.)))); + assert_eq!(scrollbar.full_width(cx), px(24.)); + + crate::Theme::global_mut(cx).scrollbar = crate::ScrollbarTheme::new().with_styles( + ScrollbarStyles::default().thumb_active(|style| style.width(px(20.)).inset(px(4.))), + ); + assert_eq!(scrollbar.full_width(cx), px(24.)); + }); + } + #[gpui::test] fn auto_hide_modes_use_a_six_pixel_resting_thumb(cx: &mut TestAppContext) { cx.update(|cx| { @@ -2524,6 +2670,185 @@ mod tests { assert_eq!(vertical.offset().x, px(0.)); } + #[gpui::test] + fn horizontal_viewport_excludes_fixed_content_without_changing_scroll_extent( + cx: &mut TestAppContext, + ) { + struct FixedGutterHarness(TestHandle); + impl Render for FixedGutterHarness { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl gpui::IntoElement { + div().relative().size(px(100.)).child( + Scrollbar::new(&self.0) + .mode(ScrollbarMode::Always) + .placement(ScrollbarPlacement::BottomLeft) + .horizontal_viewport_bounds(Bounds::new( + Point::default(), + size(px(70.), px(100.)), + )), + ) + } + } + let handle = TestHandle::new(size(px(500.), px(500.))); + let (_, cx) = cx.add_window_view(|_, _| FixedGutterHarness(handle.clone())); + cx.update(|window, cx| window.draw(cx).clear(cx)); + cx.simulate_click(point(px(90.), px(95.)), Modifiers::default()); + assert_eq!( + handle.offset(), + Point::default(), + "fixed gutter must not be a horizontal track" + ); + cx.simulate_click(point(px(69.), px(95.)), Modifiers::default()); + assert_eq!( + handle.offset(), + point(px(-400.), px(0.)), + "cropping the track must preserve the horizontal range" + ); + cx.simulate_click(point(px(5.), px(80.)), Modifiers::default()); + assert_eq!( + handle.offset(), + point(px(-400.), px(-400.)), + "vertical range must use the full viewport" + ); + } + + #[gpui::test] + fn left_placement_puts_the_vertical_track_and_thumb_on_the_left_edge(cx: &mut TestAppContext) { + let (cx, handle) = harness_with_placement( + cx, + ScrollbarAxis::Vertical, + ScrollbarPlacement::BottomLeft, + ScrollbarMode::Always, + size(px(100.), px(500.)), + ); + cx.simulate_click(point(px(95.), px(80.)), Modifiers::default()); + assert_eq!(handle.offset(), Point::default()); + + cx.simulate_mouse_down( + point(px(14.), px(20.)), + MouseButton::Left, + Modifiers::default(), + ); + assert_eq!(handle.drag_starts.get(), 1); + assert_eq!(handle.offset(), Point::default()); + // Half of the 52 px travel scrolls half of the 400 px extent. + cx.simulate_mouse_move( + point(px(14.), px(46.)), + Some(MouseButton::Left), + Modifiers::default(), + ); + cx.simulate_mouse_up( + point(px(14.), px(46.)), + MouseButton::Left, + Modifiers::default(), + ); + assert_eq!(handle.offset(), point(px(0.), px(-200.))); + + cx.simulate_click(point(px(5.), px(80.)), Modifiers::default()); + assert_eq!(handle.offset(), point(px(0.), px(-400.))); + } + + #[gpui::test] + fn left_placement_starts_the_horizontal_track_after_the_vertical_one(cx: &mut TestAppContext) { + let (cx, handle) = harness_with_placement( + cx, + ScrollbarAxis::Both, + ScrollbarPlacement::BottomLeft, + ScrollbarMode::Always, + size(px(500.), px(500.)), + ); + // The 48 px thumb, inset by 4 px, covers 50 px only when the track + // begins after the 16 px vertical track. + cx.simulate_click(point(px(50.), px(95.)), Modifiers::default()); + assert_eq!(handle.drag_starts.get(), 1); + assert_eq!(handle.offset(), Point::default()); + + cx.simulate_click(point(px(99.), px(95.)), Modifiers::default()); + assert_eq!(handle.offset(), point(px(-400.), px(0.))); + } + + #[gpui::test] + fn top_placement_puts_the_horizontal_track_and_thumb_on_the_top_edge(cx: &mut TestAppContext) { + let (cx, handle) = harness_with_placement( + cx, + ScrollbarAxis::Horizontal, + ScrollbarPlacement::TopRight, + ScrollbarMode::Always, + size(px(500.), px(100.)), + ); + cx.simulate_click(point(px(80.), px(95.)), Modifiers::default()); + assert_eq!(handle.offset(), Point::default()); + + cx.simulate_mouse_down( + point(px(20.), px(14.)), + MouseButton::Left, + Modifiers::default(), + ); + assert_eq!(handle.drag_starts.get(), 1); + assert_eq!(handle.offset(), Point::default()); + // Half of the 52 px travel scrolls half of the 400 px extent. + cx.simulate_mouse_move( + point(px(46.), px(14.)), + Some(MouseButton::Left), + Modifiers::default(), + ); + cx.simulate_mouse_up( + point(px(46.), px(14.)), + MouseButton::Left, + Modifiers::default(), + ); + assert_eq!(handle.offset(), point(px(-200.), px(0.))); + + cx.simulate_click(point(px(90.), px(5.)), Modifiers::default()); + assert_eq!(handle.offset(), point(px(-400.), px(0.))); + } + + #[gpui::test] + fn top_right_placement_ends_the_horizontal_track_before_the_vertical_one( + cx: &mut TestAppContext, + ) { + let (cx, handle) = harness_with_placement( + cx, + ScrollbarAxis::Both, + ScrollbarPlacement::TopRight, + ScrollbarMode::Always, + size(px(500.), px(500.)), + ); + // The thumb's centre reaches the end at 60 px only when the track + // ends before the 16 px vertical track. + cx.simulate_click(point(px(60.), px(5.)), Modifiers::default()); + assert_eq!(handle.offset(), point(px(-400.), px(0.))); + + // The vertical track keeps the full height and the corner. + cx.simulate_click(point(px(95.), px(90.)), Modifiers::default()); + assert_eq!(handle.offset(), point(px(-400.), px(-400.))); + cx.simulate_click(point(px(95.), px(5.)), Modifiers::default()); + assert_eq!(handle.offset(), point(px(-400.), px(0.))); + } + + #[gpui::test] + fn top_left_placement_starts_the_horizontal_track_after_the_vertical_one( + cx: &mut TestAppContext, + ) { + let (cx, handle) = harness_with_placement( + cx, + ScrollbarAxis::Both, + ScrollbarPlacement::TopLeft, + ScrollbarMode::Always, + size(px(500.), px(500.)), + ); + // The 48 px thumb, inset by 4 px, covers 50 px only when the track + // begins after the 16 px vertical track. + cx.simulate_click(point(px(50.), px(5.)), Modifiers::default()); + assert_eq!(handle.drag_starts.get(), 1); + assert_eq!(handle.offset(), Point::default()); + + cx.simulate_click(point(px(99.), px(5.)), Modifiers::default()); + assert_eq!(handle.offset(), point(px(-400.), px(0.))); + + cx.simulate_click(point(px(5.), px(95.)), Modifiers::default()); + assert_eq!(handle.offset(), point(px(-400.), px(-400.))); + } + #[gpui::test] fn horizontal_track_click_updates_horizontal_offset(cx: &mut TestAppContext) { let (cx, horizontal) = harness( @@ -2686,6 +3011,7 @@ mod tests { move |_, _| ScrollbarHarness { handle, axis: ScrollbarAxis::Vertical, + placement: ScrollbarPlacement::default(), mode: ScrollbarMode::Always, scroll_viewport_size: None, } diff --git a/crates/component/src/button/button.rs b/crates/component/src/button/button.rs index 1105952758..ada255f7e3 100644 --- a/crates/component/src/button/button.rs +++ b/crates/component/src/button/button.rs @@ -874,9 +874,7 @@ impl RenderOnce for Button { gpui::accesskit::Toggled::False }) }) - .when_some(self.expanded, |this, expanded| { - this.aria_expanded(expanded) - }) + .when_some(self.expanded, |this, expanded| this.aria_expanded(expanded)) .track_focus(&focus_handle) .tab_index(self.tab_index) .tab_stop(self.tab_stop) diff --git a/crates/component/src/input/editor.rs b/crates/component/src/input/editor.rs index 2a789153dc..68623c2652 100644 --- a/crates/component/src/input/editor.rs +++ b/crates/component/src/input/editor.rs @@ -5,7 +5,8 @@ use gpui::{ Window, prelude::FluentBuilder as _, relative, }; -use super::{EditorState, GutterStyle, Input}; +use super::input::ContextMenuBuilder; +use super::{EditorState, GutterStyle, Input, InputContextMenuCapabilities, InputHit}; use crate::native_menu::NativeMenu; use crate::{ActiveTheme as _, RoleOverride, Sizable, Size, StyledExt as _}; @@ -32,7 +33,7 @@ pub struct Editor { /// An optional context menu builder to allow a custom context menu. /// /// If set, this overrides the built-in context menu. - context_menu_builder: Option NativeMenu>>, + context_menu_builder: Option, paste_handler: Option bool>>, } @@ -119,6 +120,27 @@ impl Editor { pub fn context_menu( mut self, f: impl Fn(NativeMenu, &mut Window, &mut App) -> NativeMenu + 'static, + ) -> Self { + self.context_menu_builder = + Some(Rc::new(move |menu, _, _, window, cx| f(menu, window, cx))); + self + } + + /// Replace the built-in context menu, told what it was opened on. + /// + /// See [`Input::context_menu_with`]: a menu for a row of the gutter reads + /// the row from the [`InputHit`] it is given, and + /// [`super::default_context_menu`] keeps the built-in items for the text. + pub fn context_menu_with( + mut self, + f: impl Fn( + NativeMenu, + InputContextMenuCapabilities, + Option, + &mut Window, + &mut App, + ) -> NativeMenu + + 'static, ) -> Self { self.context_menu_builder = Some(Rc::new(f)); self @@ -177,7 +199,9 @@ impl RenderOnce for Editor { .when_some(self.height, |this, height| this.h(height)) .when_some(self.aria_label, |this, label| this.aria_label(label)) .when_some(self.context_menu_builder, |this, build| { - this.context_menu(move |menu, window, cx| build(menu, window, cx)) + this.context_menu_with(move |menu, capabilities, hit, window, cx| { + build(menu, capabilities, hit, window, cx) + }) }) .when_some(self.paste_handler, |this, handler| { this.on_paste(move |item, window, cx| handler(item, window, cx)) @@ -529,6 +553,35 @@ mod tests { } } + #[gpui::test] + fn a_gutter_on_the_right_keeps_the_padding_it_has_on_the_left(cx: &mut TestAppContext) { + cx.update(crate::init); + let mut state = None; + let (_, cx) = cx.add_window_view(|window, cx| { + let editor = cx.new(|cx| EditorState::new(window, cx).default_value("fn main() {}")); + state = Some(editor.clone()); + Harness { + state: editor, + text_size: None, + } + }); + let state = state.unwrap(); + let mut padding = |side: crate::Side| { + VisualTestContext::update(cx, |window, cx| { + state.update(cx, |state, cx| state.set_gutter_side(side, cx)); + window.draw(cx).clear(cx); + let bounds = state.read(cx).input_bounds(); + (bounds.left(), window.viewport_size().width - bounds.right()) + }) + }; + + let (left_outer, left_inner) = padding(crate::Side::Left); + let (right_inner, right_outer) = padding(crate::Side::Right); + assert!(left_outer < left_inner); + assert_eq!(right_outer, left_outer); + assert_eq!(right_inner, left_inner); + } + #[gpui::test] fn language_config_works_without_render_sync(cx: &mut TestAppContext) { use crate::input::{AutoClosingPair, language_config::LanguageConfig, set_language_config}; @@ -712,6 +765,145 @@ mod tests { }); } + /// The styled editor projects a presentation for every gutter marker, and + /// paints them through the editor's own prepaint. + #[gpui::test] + fn line_decorations_paint_every_marker_kind(cx: &mut TestAppContext) { + use crate::IconName; + use crate::input::{GutterMarker, LineDecoration, LineDecorationProvider}; + use gpui_kit_assets::IconNamed as _; + use std::{cell::Cell, ops::Range}; + + struct EveryKind(Rc>); + + impl LineDecorationProvider for EveryKind { + fn line_decorations(&self, rows: Range, cx: &App) -> Vec { + self.0.set(self.0.get() + 1); + let markers = [ + GutterMarker::DiffAdded, + GutterMarker::DiffRemoved, + GutterMarker::DiffChanged, + GutterMarker::Conflict, + GutterMarker::Bookmark, + GutterMarker::Breakpoint, + GutterMarker::Custom { + icon: IconName::Star.path(), + color: cx.theme().primary, + }, + ]; + rows.zip(markers) + .map(|(row, marker)| { + LineDecoration::new(row) + .with_background(cx.theme().success.opacity(0.16)) + .with_marker(marker) + }) + .collect() + } + } + + cx.update(crate::init); + let asked = Rc::new(Cell::new(0)); + let mut state = None; + let (_, cx) = cx.add_window_view(|window, cx| { + let editor = cx.new(|cx| EditorState::new(window, cx).default_value("a\n".repeat(7))); + editor.update(cx, |state, cx| { + state.create_line_decorations_collection(Rc::new(EveryKind(asked.clone())), cx); + }); + state = Some(editor.clone()); + Harness { + state: editor, + text_size: None, + } + }); + let state = state.unwrap(); + VisualTestContext::update(cx, |window, cx| window.draw(cx).clear(cx)); + + assert!(asked.get() > 0, "the provider was never asked"); + cx.read(|cx| { + let first = state + .read(cx) + .row_bounds(0) + .expect("the first row is laid out"); + let second = state + .read(cx) + .row_bounds(1) + .expect("the second row is laid out"); + assert_eq!(second.origin.y, first.bottom()); + }); + } + + #[gpui::test] + fn gutter_markers_follow_editor_font_changes_without_changing_rem(cx: &mut TestAppContext) { + use crate::input::{GutterMarker, LineDecoration, LineDecorationProvider}; + use std::ops::Range; + + struct Marker; + + impl LineDecorationProvider for Marker { + fn line_decorations(&self, rows: Range, _: &App) -> Vec { + rows.map(|row| LineDecoration::new(row).with_marker(GutterMarker::DiffAdded)) + .collect() + } + } + + cx.update(crate::init); + let mut editor = None; + let mut harness = None; + let (_, cx) = cx.add_window_view(|window, cx| { + let state = cx.new(|cx| EditorState::new(window, cx).default_value("first\nsecond")); + editor = Some(state.clone()); + harness = Some(cx.entity()); + Harness { + state, + text_size: None, + } + }); + let editor = editor.unwrap(); + let harness = harness.unwrap(); + VisualTestContext::update(cx, |window, cx| { + let rem_size = window.rem_size(); + let mut previous = None; + for font_size in [px(11.), px(20.)] { + harness.update(cx, |view, cx| { + view.text_size = Some(font_size); + cx.notify(); + }); + window.draw(cx).clear(cx); + let unmarked = editor.read(cx).range_to_bounds(&(0..0)).unwrap().left(); + let collection = editor.update(cx, |state, cx| { + state.create_line_decorations_collection(Rc::new(Marker), cx) + }); + window.draw(cx).clear(cx); + let state = editor.read(cx); + let slot = state.range_to_bounds(&(0..0)).unwrap().left() - unmarked; + let row_height = state.row_bounds(0).unwrap().size.height; + assert!(slot > px(0.)); + if let Some((previous_slot, previous_font, previous_height)) = previous { + assert!( + slot > previous_slot, + "the marker slot did not follow the font" + ); + assert!(row_height > previous_height); + // Row heights round to device pixels; compare the marker's + // scale against font size rather than rounded row height. + let expected = previous_slot * (font_size / previous_font); + assert!( + (slot - expected).abs() < px(0.01), + "marker and text scale diverged: slot {slot:?}, previous slot {previous_slot:?}, font {font_size:?}, previous font {previous_font:?}" + ); + } + previous = Some((slot, font_size, row_height)); + assert_eq!(window.rem_size(), rem_size); + collection.clear(cx); + window.draw(cx).clear(cx); + assert_eq!( + editor.read(cx).range_to_bounds(&(0..0)).unwrap().left(), + unmarked + ); + } + }); + } + #[gpui::test] fn test_on_paste_builder(cx: &mut TestAppContext) { use gpui::{AppContext as _, Render}; @@ -732,4 +924,76 @@ mod tests { PasteProbe }); } + + /// An editor whose right-click menu records what it was opened on, through + /// `context_menu_with` or, with `with` off, through `context_menu`. + struct MenuHarness { + state: Entity, + with: bool, + opened: Rc>>>, + } + + impl Render for MenuHarness { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + let opened = self.opened.clone(); + let editor = Editor::new(&self.state); + let editor = if self.with { + editor.context_menu_with(move |menu, _, hit, _, _| { + opened.borrow_mut().push(hit); + menu + }) + } else { + editor.context_menu(move |menu, _, _| { + opened.borrow_mut().push(None); + menu + }) + }; + div().size_full().child(editor) + } + } + + #[gpui::test] + fn a_menu_built_with_its_target_knows_the_row_of_the_gutter(cx: &mut TestAppContext) { + cx.update(crate::init); + for with in [true, false] { + let opened: Rc>> = Default::default(); + let mut state = None; + let (_, cx) = cx.add_window_view(|window, cx| { + let editor = + cx.new(|cx| EditorState::new(window, cx).default_value("one\ntwo\nthree")); + state = Some(editor.clone()); + MenuHarness { + state: editor, + with, + opened: opened.clone(), + } + }); + let state = state.unwrap(); + VisualTestContext::update(cx, |window, cx| window.draw(cx).clear(cx)); + let (gutter, text) = cx.read(|cx| { + let state = state.read(cx); + let y = state.row_bounds(1).unwrap().center().y; + let gutter = state.gutter_bounds().unwrap(); + ( + gpui::point(gutter.center().x, y), + gpui::point(gutter.right() + px(10.), y), + ) + }); + for position in [gutter, text] { + cx.simulate_mouse_down(position, gpui::MouseButton::Right, Default::default()); + cx.simulate_mouse_up(position, gpui::MouseButton::Right, Default::default()); + cx.run_until_parked(); + } + + let opened = opened.borrow(); + assert_eq!(opened.len(), 2, "with {with}"); + if with { + let (on_gutter, on_text) = (opened[0].unwrap(), opened[1].unwrap()); + assert!(on_gutter.is_gutter()); + assert_eq!(on_gutter.row(), Some(1)); + assert!(!on_text.is_gutter()); + assert_eq!(on_text.row(), Some(1)); + } + } + } } diff --git a/crates/component/src/input/input.rs b/crates/component/src/input/input.rs index 5a7ed3931b..bf379c7251 100644 --- a/crates/component/src/input/input.rs +++ b/crates/component/src/input/input.rs @@ -14,7 +14,7 @@ use crate::native_menu::NativeMenu; use crate::spinner::Spinner; use crate::touch_selection::{EditMenuItem, TouchSelectionOverlay}; use crate::{ActiveTheme, Colorize, v_flex}; -use crate::{IconName, Size}; +use crate::{Icon, IconName, Size}; use crate::{RoleOverride, Selectable, StyledExt, h_flex}; use crate::{Sizable, StyleSized}; use gpui_base::InputBase as BaseInput; @@ -23,7 +23,10 @@ use gpui_base::{LayoutDirection, LogicalStyledExt as _}; use rust_i18n::t; use super::state::{TextInputState, sync_focused_input_registry}; -use super::{GutterStyle, InputContentType, InputState, sync_native_content_type}; +use super::{ + GutterStyle, InputContentType, InputContextMenuCapabilities, InputHit, InputState, + sync_native_content_type, +}; use crate::ThemeStyled as _; /// Set when the platform draws the touch selection UI of a focused input. @@ -130,6 +133,17 @@ pub(crate) fn input_style(disabled: bool, cx: &App) -> (Hsla, Hsla) { } } +/// A custom context menu builder, told what the menu was opened on. +pub(crate) type ContextMenuBuilder = Rc< + dyn Fn( + NativeMenu, + InputContextMenuCapabilities, + Option, + &mut Window, + &mut App, + ) -> NativeMenu, +>; + /// A text input element bind to an [`InputState`]. #[derive(IntoElement)] pub struct Input { @@ -161,7 +175,7 @@ pub struct Input { /// An optional context menu builder to allow a custom context menu on the input. /// /// If set, this overrides the built-in context menu. - context_menu_builder: Option NativeMenu>>, + context_menu_builder: Option, /// An optional paste handler. If set, it is invoked with the clipboard item /// before the default text insertion. Return `true` if handled. @@ -429,6 +443,31 @@ impl Input { pub fn context_menu( mut self, f: impl Fn(NativeMenu, &mut Window, &mut App) -> NativeMenu + 'static, + ) -> Self { + self.context_menu_builder = + Some(Rc::new(move |menu, _, _, window, cx| f(menu, window, cx))); + self + } + + /// Sets a custom context menu builder that is told what the menu was + /// opened on. + /// + /// Like [`Self::context_menu`], with the input's + /// [`InputContextMenuCapabilities`], what the menu may offer, and the + /// [`InputHit`] of the right-click: whether it was on the text or on a row + /// of the gutter, `None` when the menu was not opened by a click on the + /// input. [`default_context_menu`] builds the built-in items, for the + /// clicks the builder leaves alone. + pub fn context_menu_with( + mut self, + f: impl Fn( + NativeMenu, + InputContextMenuCapabilities, + Option, + &mut Window, + &mut App, + ) -> NativeMenu + + 'static, ) -> Self { self.context_menu_builder = Some(Rc::new(f)); self @@ -571,6 +610,76 @@ impl Input { } } +const GUTTER_MARKER_FONT_SCALE: f32 = 0.9; +const GUTTER_MARKER_GAP_FONT_SCALE: f32 = 0.3; + +/// The editor style projected from the theme. +fn editor_style(font_size: gpui::Pixels, cx: &App) -> gpui_base::input::InputEditorStyle { + let theme = cx.theme(); + let highlight = &theme.highlight_theme.style; + let mut style = gpui_base::input::InputEditorStyle::default(); + style.foreground = theme.foreground; + style.muted_foreground = theme.muted_foreground; + style.background = theme.editor_background(); + style.border = theme.border; + style.selection = theme.selection; + style.caret = theme.caret; + style.diagnostics = gpui_base::input::DiagnosticColors { + error: highlight.status.error(cx), + warning: highlight.status.warning(cx), + info: highlight.status.info(cx), + hint: highlight.status.hint(cx), + }; + style.highlight_styles = theme.highlight_theme.clone(); + style.editor_invisible = highlight.editor_invisible; + style.editor_active_line = highlight.editor_active_line; + style.editor_gutter_background = highlight.editor_gutter_background; + style.fold_icon_renderer = Some(Rc::new(|ix, is_folded| { + Button::new(("fold-icon", ix)) + .ghost() + .icon(if is_folded { + IconName::ChevronRight + } else { + IconName::ChevronDown + }) + .xsmall() + .rounded(ButtonRounded::Small) + .size(px(14.)) + .selected(is_folded) + .into_any_element() + })); + let marker_size = font_size * GUTTER_MARKER_FONT_SCALE; + style + .with_gutter_marker_renderer(Some(gutter_marker_renderer(marker_size, cx))) + .with_gutter_marker_size(marker_size) + .with_gutter_marker_gap(font_size * GUTTER_MARKER_GAP_FONT_SCALE) +} + +/// Renders each line decoration gutter marker as an icon in a theme color. +fn gutter_marker_renderer( + marker_size: gpui::Pixels, + cx: &App, +) -> gpui_base::input::GutterMarkerRenderer { + use gpui_base::input::GutterMarker; + + let theme = cx.theme(); + let (success, danger, warning, info) = (theme.success, theme.danger, theme.warning, theme.info); + Rc::new(move |marker| { + let (icon, color) = match marker { + GutterMarker::DiffAdded => (Icon::new(IconName::Plus), success), + GutterMarker::DiffRemoved => (Icon::new(IconName::Minus), danger), + GutterMarker::DiffChanged => (Icon::new(IconName::Asterisk), warning), + GutterMarker::Conflict => (Icon::new(IconName::TriangleAlert), warning), + GutterMarker::Bookmark => (Icon::new(IconName::StarFill), info), + GutterMarker::Breakpoint => (Icon::new(IconName::CircleX), danger), + GutterMarker::Custom { icon, color } => (Icon::empty().path(icon.clone()), *color), + _ => return gpui::Empty.into_any_element(), + }; + // Match the size projected from the editor's effective font size. + icon.size(marker_size).text_color(color).into_any_element() + }) +} + impl Styled for Input { fn style(&mut self) -> &mut StyleRefinement { &mut self.style @@ -586,6 +695,59 @@ fn start_text_align(cx: &App) -> TextAlign { } } +/// Add the built-in items of an input's right-click menu to `menu`: Cut, Copy, +/// Paste and Select All, and for a code editor Go to Definition and Show Code +/// Actions, each enabled as `capabilities` allow. +/// +/// For a builder set with [`Input::context_menu_with`] that keeps the built-in +/// menu for some clicks. +pub fn default_context_menu( + mut menu: NativeMenu, + capabilities: InputContextMenuCapabilities, +) -> NativeMenu { + let enabled = !capabilities.is_disabled(); + // A read-only input can still navigate the code, it only + // rejects the items that would change the text. + let editable = enabled && !capabilities.is_readonly(); + if capabilities.is_code_editor() { + menu = menu + .menu_with_disabled( + t!("Input.Go to Definition"), + !(enabled && capabilities.has_definition()), + Box::new(gpui_base::input::GoToDefinition), + ) + .menu_with_disabled( + t!("Input.Show Code Actions"), + !(editable && capabilities.has_code_actions()), + Box::new(gpui_base::input::ToggleCodeActions), + ) + .separator(); + } + menu.menu_with_disabled( + t!("Input.Cut"), + !(editable && capabilities.is_copyable()), + Box::new(gpui_base::input::Cut), + ) + .menu_with_disabled( + t!("Input.Copy"), + !capabilities.is_copyable(), + Box::new(gpui_base::input::Copy), + ) + // Offered whenever the text can change, without peeking + // at the clipboard: the synchronous read is always empty + // on the web, and an empty clipboard pastes nothing. + .menu_with_disabled( + t!("Input.Paste"), + !editable, + Box::new(gpui_base::input::Paste), + ) + .separator() + .menu( + t!("Input.Select All"), + Box::new(gpui_base::input::SelectAll), + ) +} + impl RenderOnce for Input { fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement { const LINE_HEIGHT: Rems = Rems(1.25); @@ -612,52 +774,24 @@ impl RenderOnce for Input { sync_focused_input_registry(&state, window, cx); state.ensure_highlighter_factory(crate::highlighter::input_highlighter_factory(), cx); - state.set_editor_style( - gpui_base::input::InputEditorStyle { - foreground: cx.theme().foreground, - muted_foreground: cx.theme().muted_foreground, - background: cx.theme().editor_background(), - border: cx.theme().border, - selection: cx.theme().selection, - caret: cx.theme().caret, - diagnostics: gpui_base::input::DiagnosticColors { - error: cx.theme().highlight_theme.style.status.error(cx), - warning: cx.theme().highlight_theme.style.status.warning(cx), - info: cx.theme().highlight_theme.style.status.info(cx), - hint: cx.theme().highlight_theme.style.status.hint(cx), - }, - highlight_styles: cx.theme().highlight_theme.clone(), - editor_invisible: cx.theme().highlight_theme.style.editor_invisible, - editor_active_line: cx.theme().highlight_theme.style.editor_active_line, - editor_gutter_background: cx.theme().highlight_theme.style.editor_gutter_background, - fold_icon_renderer: Some(Rc::new(|ix, is_folded| { - Button::new(("fold-icon", ix)) - .ghost() - .icon(if is_folded { - IconName::ChevronRight - } else { - IconName::ChevronDown - }) - .xsmall() - .rounded(ButtonRounded::Small) - .size(px(14.)) - .selected(is_folded) - .into_any_element() - })), - }, - cx, - ); + let presentation = state.presentation(cx); state.set_editor_paddings( - if state.presentation(cx).is_multi_line() { + if presentation.is_multi_line() { + let gutter_padding = if presentation.is_code_editor() { + self.size.input_px().min(px(6.)) + } else { + self.size.input_px() + }; + let (left, right) = if presentation.gutter_side().is_left() { + (gutter_padding, self.size.input_px()) + } else { + (self.size.input_px(), gutter_padding) + }; Edges { top: self.size.input_py(), - right: self.size.input_px(), + right, bottom: self.size.input_py(), - left: if state.presentation(cx).is_code_editor() { - self.size.input_px().min(px(6.)) - } else { - self.size.input_px() - }, + left, } } else { Edges::default() @@ -668,53 +802,12 @@ impl RenderOnce for Input { state.set_readonly(self.readonly, cx); state.set_text_align(text_align, cx); let custom = self.context_menu_builder.clone(); - state.on_context_menu( - Rc::new(move |_, capabilities, position, window, cx| { + state.on_context_menu_with_hit( + Rc::new(move |_, capabilities, hit, position, window, cx| { let menu = if let Some(custom) = custom.as_ref() { - custom(NativeMenu::new(), window, cx) + custom(NativeMenu::new(), capabilities, hit, window, cx) } else { - let enabled = !capabilities.is_disabled(); - // A read-only input can still navigate the code, it only - // rejects the items that would change the text. - let editable = enabled && !capabilities.is_readonly(); - let mut menu = NativeMenu::new(); - if capabilities.is_code_editor() { - menu = menu - .menu_with_disabled( - t!("Input.Go to Definition"), - !(enabled && capabilities.has_definition()), - Box::new(gpui_base::input::GoToDefinition), - ) - .menu_with_disabled( - t!("Input.Show Code Actions"), - !(editable && capabilities.has_code_actions()), - Box::new(gpui_base::input::ToggleCodeActions), - ) - .separator(); - } - menu.menu_with_disabled( - t!("Input.Cut"), - !(editable && capabilities.is_copyable()), - Box::new(gpui_base::input::Cut), - ) - .menu_with_disabled( - t!("Input.Copy"), - !capabilities.is_copyable(), - Box::new(gpui_base::input::Copy), - ) - // Offered whenever the text can change, without peeking - // at the clipboard: the synchronous read is always empty - // on the web, and an empty clipboard pastes nothing. - .menu_with_disabled( - t!("Input.Paste"), - !editable, - Box::new(gpui_base::input::Paste), - ) - .separator() - .menu( - t!("Input.Select All"), - Box::new(gpui_base::input::SelectAll), - ) + default_context_menu(NativeMenu::new(), capabilities) }; menu.show(position, window, cx); }), @@ -871,6 +964,16 @@ impl RenderOnce for Input { .items_center() .gap(gap_x) .refine_style(&self.style) + .map(|mut this| { + let font_size = this + .style() + .text + .font_size + .unwrap_or_else(|| window.text_style().font_size) + .to_pixels(window.rem_size()); + state.set_editor_style(editor_style(font_size, cx), cx); + this + }) .when( focused && self.appearance && self.bordered && self.focus_bordered, |this| this.focus_ring_style(window, cx), diff --git a/crates/component/src/input/mod.rs b/crates/component/src/input/mod.rs index 787ec77887..99243176c7 100644 --- a/crates/component/src/input/mod.rs +++ b/crates/component/src/input/mod.rs @@ -30,19 +30,21 @@ pub use gpui_base::input::{ CompletionMenuOptions, CompletionProvider, Copy, Cut, DefinitionProvider, Delete, DeleteToBeginningOfLine, DeleteToEndOfLine, DeleteToNextWordEnd, DeleteToPreviousWordStart, DisplayMap, DisplayPoint, DocumentColorProvider, DocumentRangeSemanticTokensProvider, - EditorState, Enter, Escape, FoldRange, GoToDefinition, GutterDecoration, - GutterDecorationCollection, HighlightStyleResolver, HoverPopoverState, HoverProvider, Indent, - IndentInline, InputEdit, InputEditsEvent, InputEvent, InputHighlighter, - InputHighlighterFactory, InputState, Lsp, MaskPattern, MoveDown, MoveEnd, MoveHome, MoveLeft, - MovePageDown, MovePageUp, MoveRight, MoveToEnd, MoveToEndOfLine, MoveToNextWord, - MoveToPreviousWord, MoveToStart, MoveToStartOfLine, MoveUp, Outdent, OutdentInline, - OverviewRulerDecoration, OverviewRulerDecorationCollection, OverviewRulerLane, Paste, Point, - PrepaintCaretGeometry, RangeDecoration, RangeDecorationCollection, RangeDecorationStyle, Redo, - Replace, Rope, RopeExt, RopeLines, Search, SelectAll, SelectToEnd, SelectToEndOfLine, - SelectToNextWordEnd, SelectToPreviousWordStart, SelectToStart, SelectToStartOfLine, Selection, - ShowCharacterPalette, ShowCompletions, ShowDocumentHandler, TabSize, TextDecoration, - TextDecorationCollection, TextareaState, ToggleCodeActions, Undo, WrappingIndent, - highlight_characters, highlight_contains, highlight_prefix, + EditorState, Enter, Escape, FoldRange, GoToDefinition, GutterColumn, GutterDecoration, + GutterDecorationCollection, GutterMarker, HighlightStyleResolver, HoverPopoverState, + HoverProvider, Indent, IndentInline, InputContextMenuCapabilities, InputEdit, InputEditsEvent, + InputEvent, InputHighlighter, InputHighlighterFactory, InputHit, InputHitArea, InputState, + LineDecoration, LineDecorationCollection, LineDecorationProvider, Lsp, MaskPattern, MoveDown, + MoveEnd, MoveHome, MoveLeft, MovePageDown, MovePageUp, MoveRight, MoveToEnd, MoveToEndOfLine, + MoveToNextWord, MoveToPreviousWord, MoveToStart, MoveToStartOfLine, MoveUp, Outdent, + OutdentInline, OverviewRulerDecoration, OverviewRulerDecorationCollection, OverviewRulerLane, + Paste, Point, PrepaintCaretGeometry, RangeDecoration, RangeDecorationCollection, + RangeDecorationStyle, Redo, Replace, Rope, RopeExt, RopeLines, Search, SelectAll, SelectToEnd, + SelectToEndOfLine, SelectToNextWordEnd, SelectToPreviousWordStart, SelectToStart, + SelectToStartOfLine, Selection, ShowCharacterPalette, ShowCompletions, ShowDocumentHandler, + Spacer, SpacerProvider, TabSize, TextDecoration, TextDecorationCollection, TextareaState, + ToggleCodeActions, Undo, WrappingIndent, highlight_characters, highlight_contains, + highlight_prefix, }; pub use gpui_base::input::{EditorMode, InputMode, InputModeKind, TextareaMode}; pub use gutter_style::GutterStyle; diff --git a/crates/component/src/input/state.rs b/crates/component/src/input/state.rs index 779d5254c0..cb69c2d2c1 100644 --- a/crates/component/src/input/state.rs +++ b/crates/component/src/input/state.rs @@ -148,12 +148,13 @@ impl TextInputState { .update(cx, |state, _| state.ensure_highlighter_factory(factory))) } - pub(crate) fn on_context_menu( + pub(crate) fn on_context_menu_with_hit( &self, handler: std::rc::Rc< dyn Fn( gpui_base::input::NativeMenu, gpui_base::input::InputContextMenuCapabilities, + Option, gpui::Point, &mut Window, &mut App, @@ -162,7 +163,7 @@ impl TextInputState { cx: &mut App, ) { dispatch!(self, |state| state - .update(cx, |state, _| state.on_context_menu(handler))) + .update(cx, |state, _| state.on_context_menu_with_hit(handler))) } /// The selection a long press made, laid out for its handles and menu. diff --git a/crates/component/src/scroll/mod.rs b/crates/component/src/scroll/mod.rs index 83df6417f1..93c197a102 100644 --- a/crates/component/src/scroll/mod.rs +++ b/crates/component/src/scroll/mod.rs @@ -4,7 +4,7 @@ pub use gpui_base::AutoScroll; pub use gpui_base::ScrollableMask; pub use gpui_base::{ Scrollbar, ScrollbarAxis, ScrollbarEntrance, ScrollbarHandle, ScrollbarMode, ScrollbarMotion, - ScrollbarStyles, ScrollbarThumbStyle, ScrollbarTrackStyle, + ScrollbarPlacement, ScrollbarStyles, ScrollbarThumbStyle, ScrollbarTrackStyle, }; pub use scrollable::*; diff --git a/crates/shell/component-inventory.json b/crates/shell/component-inventory.json index e363484b2d..ccc15d018c 100644 --- a/crates/shell/component-inventory.json +++ b/crates/shell/component-inventory.json @@ -1731,6 +1731,12 @@ ] } }, + { + "source": "story", + "name": "editor_diff", + "classification": "infrastructure", + "explanation": "The Editor Diff story lays out two Editors, registered by the Editor story, as a side-by-side diff; it adds no constructor." + }, { "source": "story", "name": "empty", diff --git a/crates/story/src/gallery.rs b/crates/story/src/gallery.rs index 8b81fba9a8..2245cfa26a 100644 --- a/crates/story/src/gallery.rs +++ b/crates/story/src/gallery.rs @@ -90,6 +90,7 @@ impl Gallery { StoryContainer::panel::(window, cx), StoryContainer::panel::(window, cx), StoryContainer::panel::(window, cx), + StoryContainer::panel::(window, cx), StoryContainer::panel::(window, cx), StoryContainer::panel::(window, cx), StoryContainer::panel::(window, cx), diff --git a/crates/story/src/stories/editor_diff_story.rs b/crates/story/src/stories/editor_diff_story.rs new file mode 100644 index 0000000000..747fb29130 --- /dev/null +++ b/crates/story/src/stories/editor_diff_story.rs @@ -0,0 +1,570 @@ +use std::{ops::Range, rc::Rc}; + +use gpui_kit::component::{ + ActiveTheme, Side, + button::Button, + h_flex, + input::{ + Editor, EditorState, GutterColumn, GutterMarker, LineDecoration, LineDecorationCollection, + LineDecorationProvider, Spacer, SpacerProvider, + }, + menu::PopupMenuItem, + scroll::ScrollbarPlacement, + v_flex, +}; +use gpui_kit::{ + App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Pixels, Render, + Styled as _, Subscription, WeakEntity, Window, div, px, +}; + +use crate::story_toolbar_group; + +const ORIGINAL: &str = include_str!("editor_preview.rs"); + +struct ChangedLines { + rows: Rc>, + removed: bool, +} + +impl LineDecorationProvider for ChangedLines { + fn line_decorations(&self, visible: Range, cx: &App) -> Vec { + let (color, marker) = if self.removed { + (cx.theme().danger, GutterMarker::DiffRemoved) + } else { + (cx.theme().success, GutterMarker::DiffAdded) + }; + self.rows + .iter() + .copied() + .filter(|row| visible.contains(row)) + .map(|row| { + LineDecoration::new(row) + .with_background(color.opacity(0.12)) + .with_marker(marker.clone()) + }) + .collect() + } +} + +/// Pads each line of one side with the rows by which the other side's line +/// wraps taller, so that the two sides' lines start level. The two sources +/// have the same lines, so line `n` faces line `n`. +struct Padding { + this: WeakEntity, + other: WeakEntity, +} + +impl SpacerProvider for Padding { + fn spacers(&self, lines: Range, cx: &App) -> Vec { + let (Some(this), Some(other)) = (self.this.upgrade(), self.other.upgrade()) else { + return Vec::new(); + }; + let rows = |editor: &EditorState, line| { + editor + .display_map() + .buffer_line_to_display_row_range(line) + .map_or(0, |rows| rows.len()) + }; + let (this, other) = (this.read(cx), other.read(cx)); + lines + .filter_map(|line| { + let (own, theirs) = (rows(this, line), rows(other, line)); + (theirs > own).then(|| { + Spacer::below(line, theirs - own).with_background(cx.theme().muted.opacity(0.5)) + }) + }) + .collect() + } +} + +pub struct EditorDiffStory { + original: Entity, + modified: Entity, + mirrored: bool, + markers_before_numbers: bool, + wrap: bool, + /// The display rows each side's padding was last asked against. + rows_versions: [usize; 2], + scroll_y: [Pixels; 2], + _decorations: [LineDecorationCollection; 2], + _subscriptions: Vec, +} + +impl super::Story for EditorDiffStory { + fn title() -> &'static str { + "Editor Diff" + } + fn description() -> &'static str { + "Compare two source versions with ordinary or center-facing gutters, wrapped and padded level." + } + fn new_view(window: &mut Window, cx: &mut App) -> Entity { + cx.new(|cx| Self::new(window, cx)) + } +} + +impl EditorDiffStory { + fn new(window: &mut Window, cx: &mut Context) -> Self { + let modified_text = ORIGINAL + .replace("progress: 72.", "progress: 84.") + .replace( + "Everything is moving on schedule.", + "One milestone needs attention before the release can go ahead, and two \ + reviews are still waiting on it.", + ) + .replace(".gap_3()", ".gap_4()"); + let rows: Rc> = Rc::new( + ORIGINAL + .lines() + .zip(modified_text.lines()) + .enumerate() + .filter_map(|(row, (before, after))| (before != after).then_some(row)) + .collect(), + ); + let original = cx.new(|cx| { + EditorState::new(window, cx) + .language("rust") + .folding(true) + .soft_wrap(false) + .gutter_side(Side::Right) + .scrollbar_placement(ScrollbarPlacement::BottomLeft) + .default_value(ORIGINAL) + }); + let modified = cx.new(|cx| { + EditorState::new(window, cx) + .language("rust") + .folding(true) + .soft_wrap(false) + .default_value(modified_text) + }); + let decorations = [(&original, true), (&modified, false)].map(|(editor, removed)| { + editor.update(cx, |state, cx| { + state.create_line_decorations_collection( + Rc::new(ChangedLines { + rows: rows.clone(), + removed, + }), + cx, + ) + }) + }); + for (this, other) in [(&original, &modified), (&modified, &original)] { + let padding = Rc::new(Padding { + this: this.downgrade(), + other: other.downgrade(), + }); + this.update(cx, |state, cx| state.set_spacer_provider(Some(padding), cx)); + } + let subscriptions = + [&original, &modified].map(|editor| cx.observe(editor, |_, _, cx| cx.notify())); + Self { + original, + modified, + mirrored: true, + markers_before_numbers: false, + wrap: false, + rows_versions: [0; 2], + scroll_y: [px(0.); 2], + _decorations: decorations, + _subscriptions: subscriptions.into(), + } + } + + fn synchronize_scroll(&mut self, cx: &mut Context) { + let current = [ + self.original.read(cx).scroll_offset().y, + self.modified.read(cx).scroll_offset().y, + ]; + let changed = if current[0] != self.scroll_y[0] { + Some(0) + } else if current[1] != self.scroll_y[1] { + Some(1) + } else { + None + }; + if let Some(source) = changed { + let y = current[source]; + let target = if source == 0 { + &self.modified + } else { + &self.original + }; + if current[1 - source] != y { + target.update(cx, |state, cx| { + let mut offset = state.scroll_offset(); + offset.y = y; + state.set_scroll_offset(offset, cx); + }); + } + self.scroll_y = [y; 2]; + } + } + + /// Each side is padded against the other, so a change in either side's rows + /// is a change in both sides' spacers. + fn keep_level(&mut self, cx: &mut Context) { + let versions = [ + self.original.read(cx).display_map().version(), + self.modified.read(cx).display_map().version(), + ]; + if versions != self.rows_versions { + self.rows_versions = versions; + for editor in [&self.original, &self.modified] { + editor.update(cx, |state, cx| state.refresh_spacers(cx)); + } + } + } + + fn set_wrap(&mut self, wrap: bool, window: &mut Window, cx: &mut Context) { + self.wrap = wrap; + for editor in [&self.original, &self.modified] { + editor.update(cx, |state, cx| state.set_soft_wrap(wrap, window, cx)); + } + cx.notify(); + } + + fn set_mirrored(&mut self, mirrored: bool, cx: &mut Context) { + self.mirrored = mirrored; + self.original.update(cx, |state, cx| { + state.set_gutter_side(if mirrored { Side::Right } else { Side::Left }, cx); + state.set_scrollbar_placement( + if mirrored { + ScrollbarPlacement::BottomLeft + } else { + ScrollbarPlacement::BottomRight + }, + cx, + ); + }); + cx.notify(); + } + + fn render_toolbar(&self, cx: &Context) -> impl IntoElement { + let story = cx.entity(); + let mirrored = self.mirrored; + let markers_before_numbers = self.markers_before_numbers; + let wrap = self.wrap; + story_toolbar_group().dropdown_child( + Button::new("diff-options").label("Options"), + move |menu, window, _| { + [false, true] + .into_iter() + .fold(menu.label("Gutter layout"), |menu, value| { + menu.item( + PopupMenuItem::new(if value { + "Facing center" + } else { + "Both on left" + }) + .checked(mirrored == value) + .on_click(window.listener_for( + &story, + move |this, _, _, cx| { + this.set_mirrored(value, cx); + }, + )), + ) + }) + .separator() + .item( + PopupMenuItem::new("Markers before line numbers") + .checked(markers_before_numbers) + .on_click(window.listener_for(&story, |this, _, _, cx| { + this.markers_before_numbers = !this.markers_before_numbers; + let columns = if this.markers_before_numbers { + [ + GutterColumn::FoldIcons, + GutterColumn::Markers, + GutterColumn::LineNumbers, + ] + } else { + [ + GutterColumn::FoldIcons, + GutterColumn::LineNumbers, + GutterColumn::Markers, + ] + }; + for editor in [&this.original, &this.modified] { + editor.update(cx, |state, cx| { + state.set_gutter_order(columns, cx) + }); + } + cx.notify(); + })), + ) + .item( + PopupMenuItem::new("Wrap long lines") + .checked(wrap) + .on_click(window.listener_for(&story, move |this, _, window, cx| { + this.set_wrap(!wrap, window, cx); + })), + ) + }, + ) + } + + fn render_pane( + &self, + label: &'static str, + state: &Entity, + cx: &App, + ) -> impl IntoElement { + v_flex() + .flex_1() + .min_w_0() + .h_full() + .child( + div() + .px_3() + .py_2() + .text_sm() + .text_color(cx.theme().muted_foreground) + .border_b_1() + .border_color(cx.theme().border) + .child(label), + ) + .child( + div().flex_1().min_h_0().child( + Editor::new(state) + .readonly(true) + .bordered(false) + .size_full(), + ), + ) + } +} + +impl Render for EditorDiffStory { + fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { + // Wheel input notifies the editor; thumb dragging notifies the current + // Story view. Synchronize both paths before either pane is laid out. + // Padded, both sides have the same rows, so one offset suits both. + self.keep_level(cx); + self.synchronize_scroll(cx); + v_flex() + .size_full() + .gap_3() + .child(self.render_toolbar(cx)) + .child( + h_flex() + .flex_1() + .min_h_0() + .w_full() + .border_1() + .border_color(cx.theme().border) + .child(self.render_pane("Original · editor_preview.rs", &self.original, cx)) + .child(div().w_px().h_full().bg(cx.theme().border)) + .child(self.render_pane("Modified · editor_preview.rs", &self.modified, cx)), + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use gpui_kit::{ + Bounds, ScrollDelta, ScrollEvent, TestAppContext, VisualTestContext, WindowBounds, + WindowOptions, point, size, + }; + + #[gpui_kit::test] + fn wrapped_sides_are_padded_level(cx: &mut TestAppContext) { + cx.update(gpui_kit::init); + let (window, story) = cx.update(|cx| { + gpui_kit::open_window( + WindowOptions { + window_bounds: Some(WindowBounds::Windowed(Bounds::new( + point(px(0.), px(0.)), + size(px(900.), px(300.)), + ))), + ..Default::default() + }, + cx, + |window, cx| cx.new(|cx| EditorDiffStory::new(window, cx)), + ) + .unwrap() + }); + let mut cx = VisualTestContext::from_window(window.into(), cx); + let (original, modified) = story.read_with(&cx, |story, _| { + (story.original.clone(), story.modified.clone()) + }); + let lines = ORIGINAL.lines().count(); + let changed = ORIGINAL + .lines() + .position(|line| line.contains("Everything is moving on schedule.")) + .unwrap(); + let starts = |editor: &Entity, cx: &mut VisualTestContext| { + editor.read_with(cx, |state, _| { + (0..lines) + .map(|line| { + state + .display_map() + .buffer_line_to_display_row_range(line) + .unwrap() + .start + }) + .collect::>() + }) + }; + + for wrap in [true, false] { + cx.update(|window, cx| { + story.update(cx, |story, cx| story.set_wrap(wrap, window, cx)); + }); + for _ in 0..3 { + cx.update(|window, cx| window.draw(cx).clear(cx)); + cx.run_until_parked(); + } + let rows = |editor: &Entity, cx: &mut VisualTestContext| { + editor.read_with(cx, |state, _| { + state + .display_map() + .buffer_line_to_display_row_range(changed) + .unwrap() + .len() + }) + }; + if wrap { + assert!(rows(&modified, &mut cx) > rows(&original, &mut cx)); + } else { + assert_eq!(rows(&modified, &mut cx), 1); + } + assert_eq!( + starts(&original, &mut cx), + starts(&modified, &mut cx), + "every line starts level, wrap {wrap}" + ); + let counts = [&original, &modified].map(|editor| { + editor.read_with(&cx, |state, _| state.display_map().display_row_count()) + }); + assert_eq!(counts[0], counts[1]); + // The source ends with a newline, which the editor shows as a line. + assert_eq!(counts[0] == lines + 1, !wrap, "padded only while wrapping"); + } + } + + #[gpui_kit::test] + fn changing_diff_layout_preserves_sources_and_synchronized_scroll(cx: &mut TestAppContext) { + cx.update(gpui_kit::init); + let (window, story) = cx.update(|cx| { + gpui_kit::open_window( + WindowOptions { + window_bounds: Some(WindowBounds::Windowed(Bounds::new( + point(px(0.), px(0.)), + size(px(900.), px(300.)), + ))), + ..Default::default() + }, + cx, + |window, cx| cx.new(|cx| EditorDiffStory::new(window, cx)), + ) + .unwrap() + }); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.update(|window, cx| window.draw(cx).clear(cx)); + let (original, modified) = story.read_with(&cx, |story, _| { + (story.original.clone(), story.modified.clone()) + }); + let modified_source = modified.read_with(&cx, |state, _| state.text().to_string()); + assert_ne!(modified_source, ORIGINAL); + for mirrored in [false, true] { + story.update(&mut cx, |story, cx| story.set_mirrored(mirrored, cx)); + cx.update(|window, cx| window.draw(cx).clear(cx)); + original.read_with(&cx, |state, _| { + assert_eq!( + state.presentation().gutter_side(), + if mirrored { Side::Right } else { Side::Left } + ); + assert!(state.presentation().is_readonly()); + assert_eq!(state.text().to_string(), ORIGINAL); + }); + modified.read_with(&cx, |state, _| { + assert_eq!(state.presentation().gutter_side(), Side::Left); + assert_eq!(state.text().to_string(), modified_source); + }); + } + for (source, target) in [(&original, &modified), (&modified, &original)] { + let position = source.read_with(&cx, |state, _| state.input_bounds().center()); + cx.simulate_event(ScrollEvent { + position, + delta: ScrollDelta::Pixels(point(px(0.), px(-120.))), + ..Default::default() + }); + for frame in 0..3 { + cx.update(|window, cx| window.draw(cx).clear(cx)); + let row = + source.read_with(&cx, |state, _| state.visible_row_range().unwrap().start + 1); + let source_y = + source.read_with(&cx, |state, _| state.row_bounds(row).unwrap().top()); + let target_y = + target.read_with(&cx, |state, _| state.row_bounds(row).unwrap().top()); + assert_eq!( + source_y, target_y, + "row {row} is misaligned on frame {frame}" + ); + cx.run_until_parked(); + } + let y = source.read_with(&cx, |state, _| state.scroll_offset().y); + assert!(y < px(0.)); + assert_eq!(target.read_with(&cx, |state, _| state.scroll_offset().y), y); + cx.simulate_event(ScrollEvent { + position, + delta: ScrollDelta::Pixels(point(px(0.), px(120.))), + ..Default::default() + }); + for _ in 0..3 { + cx.update(|window, cx| window.draw(cx).clear(cx)); + cx.run_until_parked(); + } + } + for (source, target, left_track) in + [(&original, &modified, true), (&modified, &original, false)] + { + let bounds = source.read_with(&cx, |state, _| state.input_bounds()); + cx.simulate_event(ScrollEvent { + position: bounds.center(), + delta: ScrollDelta::Pixels(point(px(0.), px(10000.))), + ..Default::default() + }); + cx.update(|window, cx| window.draw(cx).clear(cx)); + let grab = point( + if left_track { + bounds.left() + px(1.) + } else { + bounds.right() - px(1.) + }, + bounds.top() + px(8.), + ); + cx.simulate_mouse_down( + grab, + gpui_kit::MouseButton::Left, + gpui_kit::Modifiers::default(), + ); + cx.update(|window, cx| window.draw(cx).clear(cx)); + let dragged = grab + point(px(0.), px(20.)); + cx.simulate_mouse_move( + dragged, + Some(gpui_kit::MouseButton::Left), + gpui_kit::Modifiers::default(), + ); + cx.update(|window, cx| window.draw(cx).clear(cx)); + let y = source.read_with(&cx, |state, _| state.scroll_offset().y); + assert!(y < px(0.), "the real scrollbar drag must move the pane"); + assert_eq!( + target.read_with(&cx, |state, _| state.scroll_offset().y), + y, + "scrollbar dragging must align both panes on the same frame" + ); + let row = + source.read_with(&cx, |state, _| state.visible_row_range().unwrap().start + 1); + assert_eq!( + source.read_with(&cx, |state, _| state.row_bounds(row).unwrap().top()), + target.read_with(&cx, |state, _| state.row_bounds(row).unwrap().top()) + ); + cx.simulate_mouse_up( + dragged, + gpui_kit::MouseButton::Left, + gpui_kit::Modifiers::default(), + ); + } + } +} diff --git a/crates/story/src/stories/editor_story.rs b/crates/story/src/stories/editor_story.rs index 7767942d4c..997a2704d0 100644 --- a/crates/story/src/stories/editor_story.rs +++ b/crates/story/src/stories/editor_story.rs @@ -1,8 +1,9 @@ -use std::{cell::Cell, rc::Rc}; +use std::{cell::Cell, ops::Range, rc::Rc}; use gpui_kit::{ App, AppContext as _, Context, Entity, HighlightStyle, IntoElement, ParentElement, Pixels, - Render, SharedString, Styled, Task, Window, div, prelude::FluentBuilder as _, px, rems, + Render, SharedString, Styled, Task, WeakEntity, Window, div, prelude::FluentBuilder as _, px, + rems, }; use gpui_kit::component::{ @@ -105,6 +106,7 @@ pub struct EditorStory { _range_decorations: RangeDecorationCollection, _gutter_decorations: GutterDecorationCollection, _overview_ruler_decorations: OverviewRulerDecorationCollection, + _line_decorations: LineDecorationCollection, active_tab: usize, readonly: bool, font_family: Option, @@ -162,7 +164,7 @@ impl EditorStory { }); } - let decoration_text = "Decoration styles\nColor highlights important text.\nItalic adds emphasis.\nUnderline marks review text.\n\nFill: marks a tracked range.\n\nFrame: outlines a tracked range."; + let decoration_text = "Decoration styles\nColor highlights important text.\nItalic adds emphasis.\nUnderline marks review text.\n\nFill: marks a tracked range.\n\nFrame: outlines a tracked range.\n\nAdded: a line background and a gutter marker.\nRemoved: asked again on every frame.\nBookmark: a gutter marker alone."; let decorations_state = cx.new(|cx| { EditorState::new(window, cx) .language("text") @@ -277,6 +279,14 @@ impl EditorStory { cx, ) }); + // Whole-line decorations come from a provider asked about the visible + // rows on every frame, so these follow edits and theme changes. + let line_decorations = decorations_state.update(cx, |state, cx| { + state.create_line_decorations_collection( + Rc::new(LineMarkers(cx.entity().downgrade())), + cx, + ) + }); let completion_highlight = Rc::new(Cell::new(StoryCompletionHighlight::Prefix)); let provider_highlight = completion_highlight.clone(); @@ -296,6 +306,7 @@ impl EditorStory { _range_decorations: range_decorations, _gutter_decorations: gutter_decorations, _overview_ruler_decorations: overview_ruler_decorations, + _line_decorations: line_decorations, active_tab: 0, readonly: false, font_family: None, @@ -305,6 +316,42 @@ impl EditorStory { } } +/// Marks the rows of the Decorations tab that start with `Added:`, `Removed:` +/// or `Bookmark:`, reading the text as it is when the editor asks. +struct LineMarkers(WeakEntity); + +impl LineDecorationProvider for LineMarkers { + fn line_decorations(&self, rows: Range, cx: &App) -> Vec { + let Some(editor) = self.0.upgrade() else { + return Vec::new(); + }; + let text = editor.read(cx).text(); + let theme = cx.theme(); + rows.filter_map(|row| { + let line = text.slice_line(row).to_string(); + let decoration = LineDecoration::new(row); + if line.starts_with("Added:") { + Some( + decoration + .with_background(theme.success.opacity(0.12)) + .with_marker(GutterMarker::DiffAdded), + ) + } else if line.starts_with("Removed:") { + Some( + decoration + .with_background(theme.danger.opacity(0.12)) + .with_marker(GutterMarker::DiffRemoved), + ) + } else if line.starts_with("Bookmark:") { + Some(decoration.with_marker(GutterMarker::Bookmark)) + } else { + None + } + }) + .collect() + } +} + impl EditorStory { /// The font families to offer beside the theme's own monospace one. const FONT_FAMILIES: [&'static str; 3] = ["Menlo", "Consolas", "Monaco"]; diff --git a/crates/story/src/stories/mod.rs b/crates/story/src/stories/mod.rs index abe1873a19..44b67ccbd4 100644 --- a/crates/story/src/stories/mod.rs +++ b/crates/story/src/stories/mod.rs @@ -26,6 +26,7 @@ mod dialog_story; mod diff_story; mod dock_story; mod dropdown_button_story; +mod editor_diff_story; mod editor_story; mod empty_story; mod form_story; @@ -111,6 +112,7 @@ pub use dialog_story::DialogStory; pub use diff_story::DiffStory; pub use dock_story::DockStory; pub use dropdown_button_story::DropdownButtonStory; +pub use editor_diff_story::EditorDiffStory; pub use editor_story::EditorStory; pub use empty_story::EmptyStory; pub use form_story::FormStory; diff --git a/crates/story/src/stories/scrollbar_story.rs b/crates/story/src/stories/scrollbar_story.rs index 11be76be61..714cc03ef0 100644 --- a/crates/story/src/stories/scrollbar_story.rs +++ b/crates/story/src/stories/scrollbar_story.rs @@ -1,6 +1,11 @@ use std::rc::Rc; -use gpui_kit::component::{ActiveTheme as _, button::Button, scroll::ScrollableElement, v_flex}; +use gpui_kit::component::{ + ActiveTheme as _, + button::Button, + scroll::{Scrollbar, ScrollbarPlacement}, + v_flex, +}; use gpui_kit::*; use serde::Deserialize; @@ -10,16 +15,27 @@ use crate::story_toolbar_group; #[action(namespace = scrollbar_story, no_json)] struct ChangeDataset(pub usize); +#[derive(Action, Clone, PartialEq, Eq, Deserialize)] +#[action(namespace = scrollbar_story, no_json)] +struct ChangePlacement(pub usize); + pub struct ScrollbarStory { focus_handle: FocusHandle, items: Rc>, item_sizes: Rc>>, test_width: Pixels, size_mode: usize, + placement: ScrollbarPlacement, scroll_handle: UniformListScrollHandle, } const ITEM_HEIGHT: Pixels = px(50.); +const PLACEMENTS: [ScrollbarPlacement; 4] = [ + ScrollbarPlacement::TopLeft, + ScrollbarPlacement::TopRight, + ScrollbarPlacement::BottomLeft, + ScrollbarPlacement::BottomRight, +]; impl ScrollbarStory { fn new(_: &mut Window, cx: &mut Context) -> Self { @@ -36,6 +52,7 @@ impl ScrollbarStory { item_sizes: Rc::new(item_sizes), test_width, size_mode: 0, + placement: ScrollbarPlacement::default(), scroll_handle: UniformListScrollHandle::new(), } } @@ -102,24 +119,45 @@ impl Render for ScrollbarStory { .on_action(cx.listener(|this, action: &ChangeDataset, _, cx| { this.change_test_cases(action.0, cx); })) + .on_action(cx.listener(|this, action: &ChangePlacement, _, cx| { + this.placement = PLACEMENTS[action.0]; + cx.notify(); + })) .child(story_toolbar_group().dropdown_child( - Button::new("scrollbar-dataset").label(format!( - "Dataset: {}", - ["Standard", "Wide", "Stress", "Short"][self.size_mode] - )), + Button::new("scrollbar-options").label("Options"), { - let selected = self.size_mode; - move |menu, _, _| { - ["Standard", "Wide", "Stress", "Short"] - .into_iter() - .enumerate() - .fold(menu, |menu, (index, label)| { - menu.menu_with_check( - label, - selected == index, - Box::new(ChangeDataset(index)), + let dataset = self.size_mode; + let placement = self.placement; + move |menu, window, cx| { + menu.submenu("Dataset", window, cx, move |menu, _, _| { + ["Standard", "Wide", "Stress", "Short"] + .into_iter() + .enumerate() + .fold(menu, |menu, (ix, label)| { + menu.menu_with_check( + label, + dataset == ix, + Box::new(ChangeDataset(ix)), + ) + }) + }) + .submenu( + "Placement", + window, + cx, + move |menu, _, _| { + PLACEMENTS.into_iter().enumerate().fold( + menu, + |menu, (ix, value)| { + menu.menu_with_check( + format!("{:?}", value), + placement == value, + Box::new(ChangePlacement(ix)), + ) + }, ) - }) + }, + ) } }, )) @@ -132,12 +170,14 @@ impl Render for ScrollbarStory { .child( uniform_list("list", self.items.len(), { let items = self.items.clone(); + let width = self.test_width; move |visible_range, _, cx| { let mut elements = Vec::with_capacity(visible_range.len()); for ix in visible_range { let item = &items[ix]; elements.push( div() + .w(width) .h(ITEM_HEIGHT) .pt_1() .items_center() @@ -154,12 +194,15 @@ impl Render for ScrollbarStory { elements } }) + .with_horizontal_sizing_behavior( + ListHorizontalSizingBehavior::Unconstrained, + ) .py_1() .px_3() .size_full() .track_scroll(&self.scroll_handle), ) - .vertical_scrollbar(&self.scroll_handle) + .child(Scrollbar::new(&self.scroll_handle).placement(self.placement)) }) } } diff --git a/examples/README.md b/examples/README.md index 22927598a4..75166365de 100644 --- a/examples/README.md +++ b/examples/README.md @@ -9,6 +9,8 @@ not enable the gallery's test-support development dependency. | Example | Command | | --- | --- | | Editor | `cargo run -p example-editor` | +| Editor spacers: two versions side by side, wrapped and padded level | `cargo run -p example-editor-spacers` | +| Editor gutter menu: a right-click menu of its own on a line number | `cargo run -p example-editor-gutter-menu` | | Editor and Markdown highlighted by syntect | `cargo run -p example-syntect` | | Brush | `cargo run -p example-brush` | | Dock | `cargo run -p example-dock` | diff --git a/examples/editor_gutter_menu/Cargo.toml b/examples/editor_gutter_menu/Cargo.toml new file mode 100644 index 0000000000..231e94f5e5 --- /dev/null +++ b/examples/editor_gutter_menu/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "example-editor-gutter-menu" +description = "An editor whose gutter has a right-click menu of its own, for the line clicked." +version = "0.10.0" +publish = false +edition.workspace = true + +[dependencies] +gpui-kit.workspace = true + +[lints] +workspace = true diff --git a/examples/editor_gutter_menu/src/main.rs b/examples/editor_gutter_menu/src/main.rs new file mode 100644 index 0000000000..697cd4b1e0 --- /dev/null +++ b/examples/editor_gutter_menu/src/main.rs @@ -0,0 +1,221 @@ +//! An editor whose gutter has a right-click menu of its own. On a line +//! number the menu is about that line — bookmark it, select it, copy it — and +//! on the text it is the editor's usual one. The selection stays where it is +//! while the gutter's menu is open. + +use std::{ + cell::{Cell, RefCell}, + collections::BTreeSet, + ops::Range, + rc::Rc, +}; + +use gpui_kit::assets::Assets; +use gpui_kit::component::{ + ActiveTheme as _, h_flex, + input::{ + Editor, EditorState, GutterMarker, LineDecoration, LineDecorationProvider, RopeExt as _, + default_context_menu, + }, + native_menu::NativeMenu, + v_flex, +}; +use gpui_kit::*; + +actions!(editor_gutter_menu, [ToggleBookmark, SelectLine, CopyLine]); + +const TEXT: &str = r#"use std::collections::HashMap; + +/// Counts how often each word occurs in `text`. +fn word_counts(text: &str) -> HashMap<&str, usize> { + let mut counts = HashMap::new(); + for word in text.split_whitespace() { + *counts.entry(word).or_insert(0) += 1; + } + counts +} + +fn main() { + let text = "the quick brown fox jumps over the lazy dog"; + let counts = word_counts(text); + let mut words: Vec<_> = counts.into_iter().collect(); + words.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0))); + for (word, count) in words { + println!("{word}: {count}"); + } +} +"#; + +/// The bookmarked rows, painted as markers in the gutter. +#[derive(Default)] +struct Bookmarks(RefCell>); + +impl LineDecorationProvider for Bookmarks { + fn line_decorations(&self, rows: Range, _: &App) -> Vec { + self.0 + .borrow() + .range(rows) + .map(|&row| LineDecoration::new(row).with_marker(GutterMarker::Bookmark)) + .collect() + } +} + +pub struct Example { + editor: Entity, + bookmarks: Rc, + /// The row the gutter's menu was last opened on. + menu_row: Rc>>, + _subscription: Subscription, +} + +impl Example { + fn new(window: &mut Window, cx: &mut Context) -> Self { + let editor = cx.new(|cx| { + EditorState::new(window, cx) + .line_number(true) + .language("rust") + // Keep the selection while the gutter's menu is open. + .gutter_context_menu_moves_cursor(false) + .default_value(TEXT) + }); + let bookmarks = Rc::new(Bookmarks::default()); + bookmarks.0.borrow_mut().insert(3); + editor.update(cx, |state, cx| { + state.create_line_decorations_collection(bookmarks.clone(), cx); + }); + let subscription = cx.observe(&editor, |_, _, cx| cx.notify()); + Self { + editor, + bookmarks, + menu_row: Rc::default(), + _subscription: subscription, + } + } + + /// The gutter's menu for `row`, zero-based. + fn line_menu(menu: NativeMenu, row: usize, bookmarked: bool) -> NativeMenu { + let line = row + 1; + let bookmark = if bookmarked { + format!("Remove Bookmark from Line {line}") + } else { + format!("Bookmark Line {line}") + }; + menu.menu(bookmark, Box::new(ToggleBookmark)) + .separator() + .menu(format!("Select Line {line}"), Box::new(SelectLine)) + .menu(format!("Copy Line {line}"), Box::new(CopyLine)) + } + + /// The byte range of `row`, without its line ending. + fn line_range(&self, row: usize, cx: &App) -> Range { + let text = self.editor.read(cx).text(); + text.line_start_offset(row)..text.line_end_offset(row) + } + + fn toggle_bookmark(&mut self, _: &ToggleBookmark, _: &mut Window, cx: &mut Context) { + let Some(row) = self.menu_row.get() else { + return; + }; + { + let mut rows = self.bookmarks.0.borrow_mut(); + if !rows.remove(&row) { + rows.insert(row); + } + } + self.editor.update(cx, |_, cx| cx.notify()); + } + + fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context) { + let Some(row) = self.menu_row.get() else { + return; + }; + let range = self.line_range(row, cx); + self.editor.update(cx, |state, cx| { + state.set_selected_range(range, cx); + state.focus(window, cx); + }); + } + + fn copy_line(&mut self, _: &CopyLine, _: &mut Window, cx: &mut Context) { + let Some(row) = self.menu_row.get() else { + return; + }; + let range = self.line_range(row, cx); + let line = self.editor.read(cx).text().slice(range).to_string(); + cx.write_to_clipboard(ClipboardItem::new_string(line)); + } +} + +impl Render for Example { + fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { + let menu_row = self.menu_row.clone(); + let bookmarks = self.bookmarks.clone(); + let marked = bookmarks + .0 + .borrow() + .iter() + .map(|row| (row + 1).to_string()) + .collect::>(); + let selected = self.editor.read(cx).selected_range(); + let status = format!( + "Bookmarks: {} · Selection: {}..{}", + if marked.is_empty() { + "none".into() + } else { + marked.join(", ") + }, + selected.start, + selected.end, + ); + v_flex() + .size_full() + .p_3() + .gap_2() + .on_action(cx.listener(Self::toggle_bookmark)) + .on_action(cx.listener(Self::select_line)) + .on_action(cx.listener(Self::copy_line)) + .child("Right-click a line number for the line's menu, the text for the usual one.") + .child(div().flex_1().min_h_0().child( + Editor::new(&self.editor).size_full().context_menu_with( + move |menu, capabilities, hit, _, _| { + match hit { + Some(hit) if hit.is_gutter() => { + menu_row.set(hit.row()); + match hit.row() { + Some(row) => Self::line_menu( + menu, + row, + bookmarks.0.borrow().contains(&row), + ), + // Below the last line: no menu. + None => menu, + } + } + _ => default_context_menu(menu, capabilities), + } + }, + ), + )) + .child( + h_flex() + .text_sm() + .text_color(cx.theme().muted_foreground) + .child(status), + ) + } +} + +fn main() { + gpui_kit::application().with_assets(Assets).run(move |cx| { + gpui_kit::init(cx); + gpui_kit::open_window( + WindowOptions { + window_bounds: Some(WindowBounds::centered(size(px(720.), px(520.)), cx)), + ..Default::default() + }, + cx, + |window, cx| cx.new(|cx| Example::new(window, cx)), + ) + .expect("Failed to open window"); + }); +} diff --git a/examples/editor_spacers/Cargo.toml b/examples/editor_spacers/Cargo.toml new file mode 100644 index 0000000000..bab9cd3151 --- /dev/null +++ b/examples/editor_spacers/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "example-editor-spacers" +description = "Two versions of a text side by side, wrapped and padded level with spacer rows." +version = "0.10.0" +publish = false +edition.workspace = true + +[dependencies] +gpui-kit.workspace = true + +[lints] +workspace = true diff --git a/examples/editor_spacers/src/main.rs b/examples/editor_spacers/src/main.rs new file mode 100644 index 0000000000..2535f63831 --- /dev/null +++ b/examples/editor_spacers/src/main.rs @@ -0,0 +1,303 @@ +//! Two versions of a text side by side, both soft-wrapped, padded level with +//! spacer rows: every paragraph starts beside the paragraph it is paired with, +//! however much taller either one wraps, and a paragraph only one version has +//! stands beside blank rows on the other. + +use std::{ops::Range, rc::Rc}; + +use gpui_kit::component::{ + ActiveTheme as _, Side, h_flex, + input::{Editor, EditorState, Spacer, SpacerProvider}, + scroll::ScrollbarPlacement, + switch::Switch, + v_flex, +}; +use gpui_kit::*; + +/// The paragraphs of the two versions, one line each, in reading order. +/// `None` is a paragraph the version does not have. +const PARAGRAPHS: &[(Option<&str>, Option<&str>)] = &[ + ( + Some("The harbour was quiet in the early hours."), + Some( + "The harbour was quiet in the early hours, before the first ferry \ + left and before the fish market opened its doors to the trade.", + ), + ), + ( + Some( + "Fishing boats came in one by one, their engines low, and tied up \ + along the old stone wall where the water was deepest at low tide.", + ), + Some("Fishing boats came in one by one and tied up along the old wall."), + ), + ( + Some("Nobody spoke much. The work was known, and the light was coming."), + Some("Nobody spoke much. The work was known, and the light was coming."), + ), + ( + None, + Some( + "A gull walked the length of the quay as if it owned it, stopping \ + at every crate to look inside, and nobody chased it away.", + ), + ), + ( + Some( + "By six the first crates were stacked on the quay, ice glittering \ + between them, and the auctioneer was clearing his throat for the \ + day's first lot while the buyers pretended not to be interested.", + ), + Some("By six the first crates were stacked on the quay."), + ), + ( + Some("Then the bell rang, and the harbour woke all at once."), + None, + ), + ( + Some("It was, everyone agreed later, a good morning."), + Some( + "It was, everyone agreed later, a good morning — the kind that \ + makes a whole season feel possible.", + ), + ), +]; + +/// Pads one side's paragraphs with the rows by which the other side's partner +/// wraps taller, and puts blank rows where the other side has a paragraph this +/// one does not. +struct Level { + this: WeakEntity, + other: WeakEntity, + /// Whether this side is the first of each pair. + first: bool, +} + +impl SpacerProvider for Level { + fn spacers(&self, lines: Range, cx: &App) -> Vec { + let (Some(this), Some(other)) = (self.this.upgrade(), self.other.upgrade()) else { + return Vec::new(); + }; + let (this, other) = (this.read(cx), other.read(cx)); + let rows = |state: &EditorState, line| { + state + .display_map() + .buffer_line_to_display_row_range(line) + .map_or(0, |rows| rows.len()) + }; + let mut spacers = Vec::new(); + let (mut own_line, mut their_line) = (0, 0); + let mut last: Option = None; + for &(first, second) in PARAGRAPHS { + let (own, theirs) = if self.first { + (first, second) + } else { + (second, first) + }; + let theirs = theirs.map(|_| { + their_line += 1; + rows(other, their_line - 1) + }); + match (own, theirs) { + (Some(_), theirs) => { + let own = rows(this, own_line); + let theirs = theirs.unwrap_or(0); + if theirs > own { + spacers.push(Spacer::below(own_line, theirs - own)); + } + last = Some(own_line); + own_line += 1; + } + (None, Some(theirs)) => { + let spacer = match last { + Some(line) => Spacer::below(line, theirs), + None => Spacer::above(0, theirs), + }; + spacers.push(spacer.with_background(cx.theme().muted)); + } + (None, None) => {} + } + } + spacers.retain(|spacer| lines.contains(&spacer.line())); + spacers + } +} + +pub struct Example { + original: Entity, + rewritten: Entity, + wrap: bool, + /// The rows each side's spacers were last asked against. + rows_versions: [usize; 2], + scroll_y: [Pixels; 2], + _subscriptions: Vec, +} + +impl Example { + fn new(window: &mut Window, cx: &mut Context) -> Self { + let text = |first: bool| { + PARAGRAPHS + .iter() + .filter_map(|&(a, b)| if first { a } else { b }) + .collect::>() + .join("\n") + }; + let original = cx.new(|cx| { + EditorState::new(window, cx) + .line_number(true) + .soft_wrap(true) + .gutter_side(Side::Right) + .scrollbar_placement(ScrollbarPlacement::BottomLeft) + .default_value(text(true)) + }); + let rewritten = cx.new(|cx| { + EditorState::new(window, cx) + .line_number(true) + .soft_wrap(true) + .default_value(text(false)) + }); + for (this, other, first) in [ + (&original, &rewritten, true), + (&rewritten, &original, false), + ] { + let level = Rc::new(Level { + this: this.downgrade(), + other: other.downgrade(), + first, + }); + this.update(cx, |state, cx| state.set_spacer_provider(Some(level), cx)); + } + let subscriptions = [&original, &rewritten] + .map(|editor| cx.observe(editor, |_, _, cx| cx.notify())) + .into(); + Self { + original, + rewritten, + wrap: true, + rows_versions: [0; 2], + scroll_y: [px(0.); 2], + _subscriptions: subscriptions, + } + } + + /// Each side is padded against the other, so a change in either side's + /// rows — a resize, the wrap turned off — asks both again. + fn keep_level(&mut self, cx: &mut Context) { + let versions = [ + self.original.read(cx).display_map().version(), + self.rewritten.read(cx).display_map().version(), + ]; + if versions != self.rows_versions { + self.rows_versions = versions; + for editor in [&self.original, &self.rewritten] { + editor.update(cx, |state, cx| state.refresh_spacers(cx)); + } + } + } + + /// Padded, both sides have the same rows, so they scroll at one offset. + fn scroll_together(&mut self, cx: &mut Context) { + let current = [ + self.original.read(cx).scroll_offset().y, + self.rewritten.read(cx).scroll_offset().y, + ]; + let moved = if current[0] != self.scroll_y[0] { + Some(0) + } else if current[1] != self.scroll_y[1] { + Some(1) + } else { + None + }; + if let Some(source) = moved { + let y = current[source]; + let target = if source == 0 { + &self.rewritten + } else { + &self.original + }; + target.update(cx, |state, cx| { + let mut offset = state.scroll_offset(); + offset.y = y; + state.set_scroll_offset(offset, cx); + }); + self.scroll_y = [y; 2]; + } + } + + fn set_wrap(&mut self, wrap: bool, window: &mut Window, cx: &mut Context) { + self.wrap = wrap; + for editor in [&self.original, &self.rewritten] { + editor.update(cx, |state, cx| state.set_soft_wrap(wrap, window, cx)); + } + cx.notify(); + } + + fn pane(label: &'static str, state: &Entity, cx: &App) -> impl IntoElement { + v_flex() + .flex_1() + .min_w_0() + .h_full() + .child( + div() + .px_3() + .py_2() + .text_sm() + .text_color(cx.theme().muted_foreground) + .border_b_1() + .border_color(cx.theme().border) + .child(label), + ) + .child( + div() + .flex_1() + .min_h_0() + .child(Editor::new(state).bordered(false).size_full()), + ) + } +} + +impl Render for Example { + fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { + self.keep_level(cx); + self.scroll_together(cx); + let view = cx.entity(); + v_flex() + .size_full() + .p_3() + .gap_3() + .child( + Switch::new("wrap") + .label("Wrap long lines") + .checked(self.wrap) + .on_click(move |wrap, window, cx| { + view.update(cx, |this, cx| this.set_wrap(*wrap, window, cx)); + }), + ) + .child( + h_flex() + .flex_1() + .min_h_0() + .w_full() + .border_1() + .border_color(cx.theme().border) + .child(Self::pane("Original", &self.original, cx)) + .child(div().w_px().h_full().bg(cx.theme().border)) + .child(Self::pane("Rewritten", &self.rewritten, cx)), + ) + } +} + +fn main() { + gpui_kit::application().run(move |cx| { + gpui_kit::init(cx); + gpui_kit::open_window( + WindowOptions { + window_bounds: Some(WindowBounds::centered(size(px(900.), px(560.)), cx)), + ..Default::default() + }, + cx, + |window, cx| cx.new(|cx| Example::new(window, cx)), + ) + .expect("Failed to open window"); + }); +} diff --git a/examples/js_story/fixtures/verify-coverage.mjs b/examples/js_story/fixtures/verify-coverage.mjs index 8b0970a948..12db78a846 100644 --- a/examples/js_story/fixtures/verify-coverage.mjs +++ b/examples/js_story/fixtures/verify-coverage.mjs @@ -87,6 +87,12 @@ const NOT_MIRRORED = new Map([ "Theme is not a component. Every route already renders through the " + "active theme, so a swatch board would restate what the gallery shows.", ], + [ + "editor_diff", + "EditorDiffStory lays out two Editors as a side-by-side diff. The " + + "editor route already mirrors the component, and the diff adds no " + + "constructor of its own.", + ], ]); const inventoryNameFor = (rustStory) => { const name = rustStory.replace(/Story$/, ""); diff --git a/website/base/primitives/editor.md b/website/base/primitives/editor.md index 6889837dbe..39ea4ff4da 100644 --- a/website/base/primitives/editor.md +++ b/website/base/primitives/editor.md @@ -107,6 +107,43 @@ on the vertical scrollbar track. Monaco calls this track the overview ruler. The collections keep empty ranges, which mark line boundaries. See [Gutter and overview ruler decorations](../../component/editor.md#gutter-and-overview-ruler-decorations). +`create_line_decorations_collection` attaches a `LineDecorationProvider`, which is +asked for whole-row backgrounds and gutter markers on every frame. Base paints the +backgrounds itself; markers are painted only through +`InputEditorStyle::gutter_marker_renderer()`, which the styled editor projects. See +[Line decorations](../../component/editor.md#line-decorations). + +`set_spacer_provider` attaches a `SpacerProvider`, which is asked for blank rows to +stand above or below lines when the rows move. Base lays the rows out and paints their +optional backgrounds. See [Spacers](../../component/editor.md#spacers). + +When using Base directly, the application supplies both the renderer and its +geometry through builders: + +```rust +let style = InputEditorStyle::default() + .with_gutter_marker_renderer(Some(renderer)) + .with_gutter_marker_size(gpui_kit::rems(0.75)) + .with_gutter_marker_gap(gpui_kit::rems(0.25)); +``` + +Marker size and gap default to zero. The renderer must respect the configured +square size; Base uses that same size for the gutter slot and vertical centering. +Rem-based values resolve against the window's current rem size on each layout. +Read the configuration with `gutter_marker_renderer()`, `gutter_marker_size()` +and `gutter_marker_gap()`. Pass `None` to `with_gutter_marker_renderer` to disable +markers. Existing style fields keep their direct-access API. + +## Display map + +`EditorState::display_map()` returns a read-only `&DisplayMap` for custom coordinate +queries across the whole prepared buffer. The editor owns updates; use +`DisplayMap::version()` to invalidate cached mappings after edits, rewrapping, or +fold changes. Import `DisplayMap`, `BufferPoint`, and `DisplayPoint` from +`gpui_kit::base::input`. See the [Editor](../../component/editor.md#line-decorations) +for query examples, layout timing, and the distinction between text projection +and painted geometry with inline completion ghost lines. + ## Highlighting and language features `InputHighlighterFactory`, `InputHighlighter`, diagnostic types, and the LSP diff --git a/website/base/primitives/scrollbar.md b/website/base/primitives/scrollbar.md index 655b6cdadc..532916082c 100644 --- a/website/base/primitives/scrollbar.md +++ b/website/base/primitives/scrollbar.md @@ -33,7 +33,7 @@ use std::time::Duration; use gpui_kit::{div, px, rgb, ScrollHandle, Styled as _}; use gpui_kit::base::{ Scrollbar, ScrollbarAxis, ScrollbarEntrance, ScrollbarMode, - ScrollbarMotion, ScrollbarStyles, ScrollbarTheme, Theme, + ScrollbarMotion, ScrollbarPlacement, ScrollbarStyles, ScrollbarTheme, Theme, }; ``` @@ -79,6 +79,24 @@ Scrollbar::horizontal(&scroll_handle); Scrollbar::new(&scroll_handle).axis(ScrollbarAxis::Vertical); ``` +Use `placement` to choose the edges the scrollbars sit on, for example to put +the vertical scrollbar on the left edge of the left pane in a side-by-side view: + +```rust +Scrollbar::new(&scroll_handle).placement(ScrollbarPlacement::BottomLeft); +``` + +| Placement | Vertical scrollbar | Horizontal scrollbar | +| ----------------------- | ------------------ | -------------------- | +| `BottomRight` (default) | Right | Bottom | +| `BottomLeft` | Left | Bottom | +| `TopRight` | Right | Top | +| `TopLeft` | Left | Top | + +A single-axis scrollbar uses only the part of the placement for its axis. When +both scrollbars are shown, the vertical track keeps the full height and the +horizontal track stops short of it on the vertical scrollbar's side. + The scrollbar is an absolute overlay. Its layout and hitboxes stay fixed while the painted track and thumb animate, so entrance motion does not move content or change the interaction geometry. @@ -182,8 +200,8 @@ The example theme above produces this choreography: | Thumb hover in `Hover` mode | `thumb_hover_entrance`: slide from the nearest edge while fading | | `Always` mode | Immediate; visibility motion is skipped | -For `SlideAndFade`, a vertical scrollbar enters from the right and a horizontal -scrollbar enters from the bottom. Opacity uses linear entrance progress; +For `SlideAndFade`, each scrollbar enters from the edge it sits on: the left or +right for a vertical scrollbar, the top or bottom for a horizontal one. Opacity uses linear entrance progress; position uses cubic ease-out. Exit opacity and position use cubic ease-in. An interrupted transition samples its current opacity and position before diff --git a/website/component/editor.md b/website/component/editor.md index 25c13997ca..0b1c6afe98 100644 --- a/website/component/editor.md +++ b/website/component/editor.md @@ -141,6 +141,44 @@ bottom and spring back with precise trackpad or Magic Mouse scrolling, as in the [Textarea](./textarea.md#scroll-bounce). The gutter moves with the code; the frame and scrollbar stay put. Ordinary mouse-wheel line scrolling does not bounce. +The scrollbars sit on the right and bottom edges by default. Use +`scrollbar_placement` to move them; a vertical scrollbar on the left sits on +the editor's left edge, over the line numbers, or clear of the text when the +gutter is on the right. Like the bottom scrollbar over the last line, a top +scrollbar overlays the first line rather than reserving space for itself. +`set_scrollbar_placement` replaces the placement at runtime. + +In a mirrored pane with a right gutter and left scrollbar, the horizontal track stops before the gutter while the vertical track stays at the outer edge. + +```rust +EditorState::new(window, cx).scrollbar_placement(ScrollbarPlacement::BottomLeft) +``` + +The gutter with the line numbers and fold icons sits on the left by default. +In a side-by-side diff, both gutters can face the center, so the line numbers +of corresponding lines sit next to each other across the divider. The left pane +puts its gutter on its right with `gutter_side` — mirrored, the fold icons next +to the text — and its scrollbar on its outer edge: + +```rust +EditorState::new(window, cx) + .scrollbar_placement(ScrollbarPlacement::BottomLeft) + .gutter_side(Side::Right) +``` + +On either side, the fold icons sit next to the text, then the line numbers, +then the gutter markers, then the strip of the +[gutter decorations](#gutter-and-overview-ruler-decorations). Use `gutter_order` +to list the columns from the text outward; a column left out follows the listed +ones. In a diff, this puts the change markers between the text and the line +numbers: + +```rust +EditorState::new(window, cx).gutter_order([GutterColumn::FoldIcons, GutterColumn::Markers]) +``` + +The Editor Diff story shows both layouts, with the two panes scrolling together. + ## Manual completions `ShowCompletions` requests suggestions without editing text. It has **no default @@ -361,7 +399,9 @@ The Editor showcase's **Decorations** tab demonstrates both collection types. Use these collections to mark whole lines outside the text, such as lines that a version-control diff added, modified, or deleted. A `GutterDecorationCollection` -draws in a strip before the line numbers. An `OverviewRulerDecorationCollection` +draws in a strip at the outer edge of the gutter, before the line numbers and +the line decoration markers; `gutter_order` can move it, as +`GutterColumn::Decorations`. An `OverviewRulerDecorationCollection` draws on the vertical scrollbar track. Monaco calls this track the overview ruler. Create one collection for each surface you want to use. @@ -420,12 +460,239 @@ let ruler = editor.update(cx, |state, cx| { in the document, and each mark is at least 6 px tall. Touching marks with the same color in the same lane merge. - The marks draw under the scrollbar, whether it is Base's scrollbar or one supplied with `set_scrollbar_renderer`. They remain visible while the thumb fades. + With `scrollbar_placement` on the left, the track and its marks move to the left + edge; a supplied scrollbar reads the placement from `EditorScrollbarContext::placement`. - Without `with_color`, both collections use the editor foreground color. For version-control colors, read the highlight theme's Zed status keys `created`, `modified`, and `deleted` with `status.created(cx)`, `status.modified(cx)`, and `status.deleted(cx)`. If a key is missing, these methods use `success`, `warning`, and `error`. +### Line decorations + +A `LineDecorationCollection` paints whole rows: a background band across a row, a +marker in its gutter, or both. Its entries come from a `LineDecorationProvider`, which +the editor asks about the visible buffer rows on every frame it paints. + +```rust +use std::{ops::Range, rc::Rc}; + +use gpui_kit::App; +use gpui_kit::component::{ + ActiveTheme as _, + input::{GutterMarker, LineDecoration, LineDecorationProvider}, +}; + +/// Zero-based buffer rows, sorted. +struct AddedRows(Vec); + +impl LineDecorationProvider for AddedRows { + fn line_decorations(&self, rows: Range, cx: &App) -> Vec { + let start = self.0.partition_point(|&row| row < rows.start); + let end = self.0.partition_point(|&row| row < rows.end); + self.0[start..end] + .iter() + .map(|&row| { + LineDecoration::new(row) + .with_background(cx.theme().success.opacity(0.16)) + .with_marker(GutterMarker::DiffAdded) + }) + .collect() + } +} + +let added = editor.update(cx, |state, cx| { + state.create_line_decorations_collection(Rc::new(AddedRows(vec![2, 3, 7])), cx) +}); + +added.set_provider(Rc::new(AddedRows(vec![4])), cx); // The next frame asks this one. +added.clear(cx); // Stop painting, keep the collection available for reuse. +added.dispose(cx); // Invalidate this handle and all its clones. +``` + +Because the provider is asked again on every frame, it owns its rows: the editor does +not move them across edits or clear them when the text is replaced, and it ignores +decorations outside the rows it asked about. Keep the answer cheap by indexing your +data by row, and read colors from `cx` when asked so they follow theme changes. +Collections are independent, like the other decoration collections; later ones paint +over earlier ones. + +A background spans the whole row, gutter included, across all of its soft-wrapped +lines, under the active line, indent guides, selection and text. A marker is painted +in a slot of its own, shown only while line numbers are. In the default order the +slot is on the outer side of the line numbers; `gutter_order` can move it nearer the +text, as IntelliJ IDEA places its markers. The gutter reserves the slot while any +collection has a provider, and keeps it as marked rows scroll in and out of view. +The styled editor sizes the marker at 90% of its effective font size and the gap at +30%. The icon, reserved slot and vertical centering share the same size, so markers +follow both interface zoom and an editor-specific `.text_size(...)` change. +`DiffAdded`, `DiffRemoved`, `DiffChanged`, `Conflict`, `Bookmark` and `Breakpoint` +take the theme's success, danger, warning and info colors; +`GutterMarker::Custom { icon, color }` paints an icon asset path as given. Neither +affects hit testing or focus, and neither has a pointer or keyboard action. + +`EditorState::row_bounds(row)` returns the band a row occupies in window coordinates, +where it is painted: below a multi-line inline completion, rows move down with the +text. It returns `None` while the row is not laid out. The **Decorations** tab of the Editor showcase +marks its last three rows with a provider. + +`EditorState::hit_test(position)` tells what a point in window coordinates is over, as +last painted: the text, at the offset a click there places the caret at, or the gutter, +in one of its `GutterColumn`s or in its margin. Either way it names the buffer row beside +the point, and whether the point is on one of that row's spacer rows. In the gutter the +row is `None` above the first row and below the last. `EditorState::gutter_bounds()` +returns the gutter's painted bounds. Both return `None` before the first paint; neither +changes what the editor does with a click. + +```rust +use gpui_kit::component::input::{GutterColumn, InputHitArea}; + +if let Some(hit) = editor.read(cx).hit_test(position) { + match hit.area() { + InputHitArea::Gutter { column: Some(GutterColumn::LineNumbers), .. } => { + // A line number: `hit.row()` is the buffer row. + } + InputHitArea::Text { offset, .. } => { /* the text, at `offset` */ } + _ => {} + } +} +``` + +`EditorState::display_map()` returns `&DisplayMap`, a read-only reference to the +editor-owned text projection. `DisplayMap`, `BufferPoint`, and `DisplayPoint` are +available from both `gpui_kit::base::input` and `gpui_kit::component::input`. +The editor state owns updates; applications can query the map to build custom +minimaps, synchronized views, or buffer/display coordinate conversions. + +```rust +use gpui_kit::base::input::BufferPoint; + +let state = editor.read(cx); +let map = state.display_map(); +let count = map.display_row_count(); +let rows = map.buffer_line_to_display_row_range(0); // None for a folded line +let display = map.buffer_pos_to_display_pos(BufferPoint::new(0, 0)); +let buffer = map.display_pos_to_buffer_pos(display); +let version = map.version(); +``` + +The map covers the whole prepared text, including lines outside the viewport. +Wrapping follows the latest prepared layout parameters; before text preparation, +the map has no display rows. `map.version()` changes on edits, rewrapping, +fold and spacer changes. Compare versions on the same map to invalidate cached queries; +scrolling does not change the version. + +The map excludes inline completion ghost lines. Display row indices multiplied +by the line height describe text projection positions, not necessarily painted +positions: multi-line inline completion shifts later text down without changing +the map or its version. Use `row_bounds` for actual geometry of visible lines. + +Buffer and display indices are zero-based. A buffer line hidden by a fold has +no display-row range (`None`); use the coordinate conversion methods for +buffer/display positions. + +### Spacers + +A `Spacer` is a run of blank rows above or below a buffer line. It holds no text: it has +no line number, the caret steps over it, a click on it lands on the row of text beside +it, and line decorations, selections, search matches and inline colors pass it by. Its +rows are display rows like any other, so the scroll height, scrolling to a line and +`row_bounds` count them. Two editors shown side by side pad their shorter lines with +spacers, so that lines paired across them start level however each one wraps, as a +side-by-side diff does. + +```rust +use std::{ops::Range, rc::Rc}; + +use gpui_kit::{App, WeakEntity}; +use gpui_kit::component::input::{EditorState, Spacer, SpacerProvider}; + +/// Pads each line with the rows by which the same line of `other` wraps taller. +struct Level { + this: WeakEntity, + other: WeakEntity, +} + +impl SpacerProvider for Level { + fn spacers(&self, lines: Range, cx: &App) -> Vec { + let (Some(this), Some(other)) = (self.this.upgrade(), self.other.upgrade()) else { + return Vec::new(); + }; + let rows = |editor: &EditorState, line| { + editor + .display_map() + .buffer_line_to_display_row_range(line) + .map_or(0, |rows| rows.len()) + }; + let (this, other) = (this.read(cx), other.read(cx)); + lines + .filter_map(|line| { + let (own, theirs) = (rows(this, line), rows(other, line)); + (theirs > own).then(|| Spacer::below(line, theirs - own)) + }) + .collect() + } +} + +let level = Rc::new(Level { + this: left.downgrade(), + other: right.downgrade(), +}); +left.update(cx, |state, cx| state.set_spacer_provider(Some(level), cx)); +``` + +Unlike line decorations, spacers move every row below them, so the editor asks for those +of every line at once and keeps the answer: when the provider is set, after an edit, +after the text is wrapped again or a fold changes, and when `refresh_spacers` is called. +It asks during layout, once the text is wrapped to the editor's width, and outside any +update of the editor, so the provider may read this editor and others. When the answer +depends on another editor's rows, call `refresh_spacers` when that editor's +`display_map().version()` changes. `Spacer::above(0, rows)` pads the top of the text, and +`with_background` fills the rows, gutter included. A spacer on a line hidden by a fold, +or past the last line, is not shown. The **Editor Diff** story wraps both sides and pads +them level. + +In the display map, spacer rows are display rows: `display_row_count()` counts them, +`buffer_line_to_display_row_range(line)` holds only the rows of the line's text, +`display_row_to_buffer_line(row)` reads a spacer row as the line it stands beside, and +`is_spacer_row(row)` tells a spacer row from a row of text. `version()` changes when the +spacers do, so a cache of rows stays valid; a provider answering with the spacers already +shown leaves it unchanged, so refreshing on a version change settles. + +## Gutter context menu + +`Editor::context_menu_with` builds the right-click menu knowing what it was opened on: +besides the capabilities, it is handed the [`hit_test`](#line-decorations) of the click, +so a menu can be about a row of the gutter and leave the text its usual one, which +`default_context_menu` builds. A right-click on the gutter moves the caret to the +row, as one on the text does; `gutter_context_menu_moves_cursor(false)` keeps the +selection instead while the gutter's menu is open. + +```rust +use gpui_kit::component::input::{Editor, EditorState, default_context_menu}; + +let editor = cx.new(|cx| { + EditorState::new(window, cx) + .line_number(true) + .gutter_context_menu_moves_cursor(false) +}); + +Editor::new(&editor).context_menu_with(|menu, capabilities, hit, _, _| { + match hit { + Some(hit) if hit.is_gutter() => match hit.row() { + Some(row) => menu + .menu(format!("Bookmark Line {}", row + 1), Box::new(ToggleBookmark)) + .menu(format!("Copy Line {}", row + 1), Box::new(CopyLine)), + None => menu, // below the last line: no menu + }, + _ => default_context_menu(menu, capabilities), + } +}) +``` + +The builder runs when the menu opens; remember the row there for the actions to read. +`examples/editor_gutter_menu` bookmarks, selects and copies the line clicked. + ## Value and events ```rust diff --git a/website/component/input.md b/website/component/input.md index 21973e214d..f85c56d856 100644 --- a/website/component/input.md +++ b/website/component/input.md @@ -231,6 +231,16 @@ Input::new(&input).context_menu(|menu, window, cx| { .menu("Copy", Box::new(input::Copy)) .menu("Paste", Box::new(input::Paste)) }) + +// Or decide by what the menu was opened on, keeping the built-in items for +// the rest. `hit` is the click's `hit_test`: the text, or a row of an +// editor's gutter. +Input::new(&input).context_menu_with(|menu, capabilities, hit, window, cx| { + match hit { + Some(hit) if hit.is_gutter() => menu.menu("Custom Action", Box::new(CustomAction)), + _ => input::default_context_menu(menu, capabilities), + } +}) ``` A right-click outside the selection moves the cursor to the click. A right-click inside the selection keeps the selection and the cursor, so read `context_menu_offset()` to act on the text under the pointer, as a spelling menu does: diff --git a/website/zh-CN/base/primitives/editor.md b/website/zh-CN/base/primitives/editor.md index 2dd51a80ff..b12a6ab94c 100644 --- a/website/zh-CN/base/primitives/editor.md +++ b/website/zh-CN/base/primitives/editor.md @@ -74,6 +74,35 @@ gutter 设置或字体后需重新渲染;不要为尚未布局的编辑器代 Monaco 将这条轨道称为概览标尺。这两个集合会保留表示行边界的空范围。 参见[行号槽与概览标尺装饰](../../component/editor.md#行号槽与概览标尺装饰)。 +`create_line_decorations_collection` 挂载一个 `LineDecorationProvider`,编辑器每一帧都会向它 +询问整行背景和行号槽标记。背景由 Base 直接绘制;标记只通过 `InputEditorStyle::gutter_marker_renderer()` +绘制,样式化编辑器会提供该渲染器。参见[行装饰](../../component/editor.md#行装饰)。 + +`set_spacer_provider` 挂载一个 `SpacerProvider`,每当行发生移动时,编辑器都会向它询问需要放在各行上方或下方的空白行。 +这些行由 Base 负责布局,并绘制其可选的背景色。参见[填充行](../../component/editor.md#填充行)。 + +直接使用 Base 时,应用通过 builder 同时提供渲染器和布局尺寸: + +```rust +let style = InputEditorStyle::default() + .with_gutter_marker_renderer(Some(renderer)) + .with_gutter_marker_size(gpui_kit::rems(0.75)) + .with_gutter_marker_gap(gpui_kit::rems(0.25)); +``` + +标记尺寸和间距默认为零。渲染器应遵守配置的正方形尺寸;Base 使用同一尺寸计算槽宽和垂直居中。 +使用 rem 值时,每次布局都会按窗口当前的 rem 大小换算。 +通过 `gutter_marker_renderer()`、`gutter_marker_size()` 和 `gutter_marker_gap()` 读取配置, +向 `with_gutter_marker_renderer` 传入 `None` 可停用标记。既有样式字段仍可直接读写。 + +## 显示映射 + +`EditorState::display_map()` 返回只读的 `&DisplayMap`,供应用查询整个已准备缓冲区的坐标映射。 +编辑器负责更新;使用 `DisplayMap::version()` 判断编辑、重新换行或折叠变化后是否需要重新查询。 +从 `gpui_kit::base::input` 导入 `DisplayMap`、`BufferPoint` 和 `DisplayPoint`。 +查询示例、布局时机,以及文本映射与包含内联补全额外行的实际绘制坐标之间的区别,参见 +[Editor](../../component/editor.md#行装饰)。 + ## 高亮与语言功能 `InputHighlighterFactory`、`InputHighlighter`、诊断类型和 LSP provider trait 是提供给设计系统作者的底层扩展点,作用于共享的 `InputBaseState`。样式组件的应用通常应通过编辑器集成配置它们,而不是普通文本框。 diff --git a/website/zh-CN/base/primitives/scrollbar.md b/website/zh-CN/base/primitives/scrollbar.md index 56e0a9bb6d..17cf2fd18a 100644 --- a/website/zh-CN/base/primitives/scrollbar.md +++ b/website/zh-CN/base/primitives/scrollbar.md @@ -20,6 +20,23 @@ cargo run -p gpui-base-examples -- scrollbar 把 `ScrollHandle` 保存在持久视图状态中,通过 `track_scroll` 连接可滚动内容,并在同一个 `relative()` 容器中叠加 `Scrollbar`。`Scrollbar::new` 启用双轴;单轴使用 `vertical`、`horizontal` 或 `.axis(...)`。滚动条是绝对定位覆盖层,进入动画不会移动内容或命中区域。 +## 位置 + +使用 `placement` 选择滚动条所在的边缘,例如在并排视图的左侧窗格中把纵向滚动条放到左边: + +```rust +Scrollbar::new(&scroll_handle).placement(ScrollbarPlacement::BottomLeft); +``` + +| 位置 | 纵向滚动条 | 横向滚动条 | +| ---------------------- | ---------- | ---------- | +| `BottomRight`(默认) | 右侧 | 底部 | +| `BottomLeft` | 左侧 | 底部 | +| `TopRight` | 右侧 | 顶部 | +| `TopLeft` | 左侧 | 顶部 | + +单轴滚动条只使用位置中对应其轴向的部分。两个滚动条同时显示时,纵向轨道保持完整高度,横向轨道在纵向滚动条一侧让出其宽度。 + ## 可见模式 - `Scrolling`:滚动或拖动后显示,离开悬停区域后重新计算空闲等待。 @@ -34,7 +51,7 @@ cargo run -p gpui-base-examples -- scrollbar ## 动画行为 -Base 不附带产品动画。默认仅有 2 秒行为性空闲等待,进入、退出和展开时长均为零。`Fade` 原地淡入;`SlideAndFade` 让纵向滚动条从右侧、横向滚动条从底部进入。被中断的过渡从当前视觉值反向;零时长立即采用目标值。GPUI 的减少动态效果偏好也会把可见性和宽度时长降为零。 +Base 不附带产品动画。默认仅有 2 秒行为性空闲等待,进入、退出和展开时长均为零。`Fade` 原地淡入;`SlideAndFade` 让滚动条从其所在的边缘进入:纵向滚动条从左侧或右侧,横向滚动条从顶部或底部。被中断的过渡从当前视觉值反向;零时长立即采用目标值。GPUI 的减少动态效果偏好也会把可见性和宽度时长降为零。 ## 自定义视口与句柄 diff --git a/website/zh-CN/component/editor.md b/website/zh-CN/component/editor.md index 663e5094bd..3547d8cd44 100644 --- a/website/zh-CN/component/editor.md +++ b/website/zh-CN/component/editor.md @@ -118,6 +118,30 @@ let editor = cx.new(|cx| { `scroll_bounce(true)` 让超出编辑器高度的代码在触控板或 Magic Mouse 的精细像素滚动到达顶部或底部时越过边缘并弹回,与 [Textarea](./textarea.md#滚动回弹) 相同。行号栏随代码移动,外框和滚动条保持不动;普通鼠标滚轮的按行滚动不触发回弹。 +滚动条默认位于右侧和底部。使用 `scrollbar_placement` 可调整其位置;放在左侧的纵向滚动条位于编辑器左边缘,覆盖在行号之上;若 gutter 位于右侧,文本会与滚动条保持间距。与覆盖最后一行的底部滚动条一样,顶部滚动条覆盖在第一行之上,不为自身预留空间。运行时可用 `set_scrollbar_placement` 替换位置。 + +在右侧 gutter、左侧滚动条的镜像窗格中,横向轨道会避开 gutter,纵向轨道仍位于窗格外侧边缘。 + +```rust +EditorState::new(window, cx).scrollbar_placement(ScrollbarPlacement::BottomLeft) +``` + +行号和折叠图标所在的 gutter 默认位于左侧。在并排 diff 中,两侧的 gutter 可以朝向中间,使对应行的行号隔着分隔线相邻。左侧窗格用 `gutter_side` 将 gutter 放到右侧(镜像排列,折叠图标紧邻文本),并把滚动条放到外侧边缘: + +```rust +EditorState::new(window, cx) + .scrollbar_placement(ScrollbarPlacement::BottomLeft) + .gutter_side(Side::Right) +``` + +无论 gutter 位于哪一侧,折叠图标默认紧邻文本,向外依次是行号、gutter 标记和[行号槽装饰](#行号槽与概览标尺装饰)的竖条。使用 `gutter_order` 可按从文本向外的顺序列出各列,未列出的列依次排在其后。在 diff 中,这样可以把变更标记放在文本与行号之间: + +```rust +EditorState::new(window, cx).gutter_order([GutterColumn::FoldIcons, GutterColumn::Markers]) +``` + +Editor Diff 示例展示了这两种布局,两个窗格同步滚动。 + ## 主动补全 `ShowCompletions` 可以在不修改文本的情况下请求补全,**没有默认快捷键**。应用应结合平台习惯选择绑定,避开 Ctrl+Space 等输入法快捷键。Editor 的绑定可以使用 `Input && mode == editor` 条件;现有 `Input` 绑定仍然有效。 @@ -296,7 +320,8 @@ Editor 展示页的 **Decorations** 标签演示了两种集合的组合使用 ### 行号槽与概览标尺装饰 需要在文本之外标记整行(例如版本控制 diff 中新增、修改或删除的行)时,使用这两个集合。 -`GutterDecorationCollection` 在行号之前的窄带中绘制标记。 +`GutterDecorationCollection` 在 gutter 外侧边缘、行号和行装饰标记之前的窄带中绘制标记; +可用 `gutter_order` 通过 `GutterColumn::Decorations` 调整其位置。 `OverviewRulerDecorationCollection` 在垂直滚动条轨道上绘制标记,Monaco 将这条轨道称为概览标尺。 要同时在两处显示标记,请分别创建两个集合。 @@ -345,12 +370,211 @@ let ruler = editor.update(cx, |state, cx| { 按惯例,版本控制使用 `Left`,搜索结果使用 `Center`,诊断使用 `Right`。每个标记按所在行占内容高度的比例定位, 高度至少为 6 px。同一分区中颜色相同且相互接触的标记会合并。 - 标记绘制在滚动条下方,无论滚动条是 Base 提供的还是由 `set_scrollbar_renderer` 提供的。 - 滑块淡出时,标记仍然可见。 + 滑块淡出时,标记仍然可见。`scrollbar_placement` 放在左侧时,轨道和标记随之移到左边缘; + 自定义滚动条通过 `EditorScrollbarContext::placement` 读取位置。 - 不调用 `with_color` 时,两个集合都使用编辑器前景色。版本控制的颜色可以读取高亮主题中 Zed 的状态键 `created`、`modified` 和 `deleted`,对应方法为 `status.created(cx)`、 `status.modified(cx)` 和 `status.deleted(cx)`。缺少对应键时,这些方法分别使用 `success`、 `warning` 和 `error`。 +### 行装饰 + +`LineDecorationCollection` 以整行为单位绘制:横跨该行的背景色带、行号槽中的标记,或两者兼有。 +条目由 `LineDecorationProvider` 提供:编辑器每绘制一帧,都会以当前可见的缓冲区行范围询问它。 + +```rust +use std::{ops::Range, rc::Rc}; + +use gpui_kit::App; +use gpui_kit::component::{ + ActiveTheme as _, + input::{GutterMarker, LineDecoration, LineDecorationProvider}, +}; + +/// 从零开始的缓冲区行,已排序。 +struct AddedRows(Vec); + +impl LineDecorationProvider for AddedRows { + fn line_decorations(&self, rows: Range, cx: &App) -> Vec { + let start = self.0.partition_point(|&row| row < rows.start); + let end = self.0.partition_point(|&row| row < rows.end); + self.0[start..end] + .iter() + .map(|&row| { + LineDecoration::new(row) + .with_background(cx.theme().success.opacity(0.16)) + .with_marker(GutterMarker::DiffAdded) + }) + .collect() + } +} + +let added = editor.update(cx, |state, cx| { + state.create_line_decorations_collection(Rc::new(AddedRows(vec![2, 3, 7])), cx) +}); + +added.set_provider(Rc::new(AddedRows(vec![4])), cx); // 下一帧改为询问它。 +added.clear(cx); // 停止绘制,但保留集合以便复用。 +added.dispose(cx); // 释放集合,使该句柄及其克隆全部失效。 +``` + +由于每一帧都会重新询问 provider,行由 provider 自己维护:编辑器不会随编辑移动这些行, +替换全文时也不会清空它们,并且会忽略询问范围之外的装饰。请按行为数据建立索引,让回答保持轻量; +在被询问时从 `cx` 读取颜色,使其跟随主题变化。与其他装饰集合一样,各集合相互独立; +后创建的集合绘制在先创建的集合之上。 + +背景横跨整行(包括行号槽),覆盖该行软换行后的全部显示行,位于当前行高亮、缩进参考线、 +选区和文字下方。标记绘制在独立槽位中,只在显示行号时出现。默认顺序下,该槽位位于行号与行号槽外缘之间; +使用 `gutter_order` 可将其移到更靠近文本的位置,与 IntelliJ IDEA 放置标记的方式一致。只要有集合设置了 +provider,行号槽就会保留该槽位,标记行滚入或滚出视图时宽度不变。 +样式化编辑器的标记尺寸为实际字号的 90%,间距为字号的 30%。图标、预留槽位和垂直居中使用同一尺寸, +因此标记既跟随界面缩放,也跟随编辑器单独设置的 `.text_size(...)` 变化。`DiffAdded`、`DiffRemoved`、 +`DiffChanged`、`Conflict`、`Bookmark` 和 `Breakpoint` 使用主题的 success、danger、warning 和 +info 颜色;`GutterMarker::Custom { icon, color }` 按原样绘制给定的图标资源路径。两者都不影响 +命中测试或焦点,也不提供鼠标或键盘操作。 + +`EditorState::row_bounds(row)` 返回某一行在窗口坐标中实际绘制的区域:多行内联补全下方的行会随 +文字一起下移。该行尚未布局时返回 `None`。 +Editor 展示页的 **Decorations** 标签用 provider 标记了最后三行。 + +`EditorState::hit_test(position)` 按最近一次绘制,返回窗口坐标中的某个点落在什么上:文本(附带在该处 +单击时光标所在的偏移量),或行号栏(附带所在的 `GutterColumn`,落在边距中时为 `None`)。两种情况都会 +给出该点旁边的缓冲区行,以及该点是否位于这一行的间隔行上。在行号栏中,第一行之上和最后一行之下的行为 +`None`。`EditorState::gutter_bounds()` 返回行号栏实际绘制的区域。首次绘制之前两者都返回 `None`; +它们都不会改变编辑器对单击的处理。 + +```rust +use gpui_kit::component::input::{GutterColumn, InputHitArea}; + +if let Some(hit) = editor.read(cx).hit_test(position) { + match hit.area() { + InputHitArea::Gutter { column: Some(GutterColumn::LineNumbers), .. } => { + // 行号:`hit.row()` 是缓冲区行。 + } + InputHitArea::Text { offset, .. } => { /* 文本,位于 `offset` */ } + _ => {} + } +} +``` + +`EditorState::display_map()` 返回 `&DisplayMap`,供应用只读查询编辑器拥有的文本映射。 +`DisplayMap`、`BufferPoint` 和 `DisplayPoint` 均可从 `gpui_kit::base::input` 或 +`gpui_kit::component::input` 导入。编辑器状态负责更新映射;应用可以用它实现自定义缩略图、 +同步视图,以及缓冲区坐标与显示坐标之间的转换。 + +```rust +use gpui_kit::base::input::BufferPoint; + +let state = editor.read(cx); +let map = state.display_map(); +let count = map.display_row_count(); +let rows = map.buffer_line_to_display_row_range(0); // 折叠隐藏的行返回 None +let display = map.buffer_pos_to_display_pos(BufferPoint::new(0, 0)); +let buffer = map.display_pos_to_buffer_pos(display); +let version = map.version(); +``` + +映射覆盖整个已准备的文本,包括视口外的行。软换行使用最近准备的布局参数;文本尚未准备时, +映射没有显示行。编辑、重新换行、折叠或填充行变化会改变 `map.version()`。比较同一映射的版本可以判断 +何时需要重新查询;滚动不会改变版本。 + +映射不包含内联补全的额外行。显示行序号乘以行高表示文本映射位置,不一定是实际绘制位置: +多行内联补全会把后续文本向下推,而映射和版本不变。可见行的实际几何信息应通过 `row_bounds` 获取。 + +缓冲区和显示坐标的序号均从零开始。被折叠隐藏的缓冲区行没有显示行范围(返回 `None`); +缓冲区位置与显示位置之间的转换使用映射的坐标转换方法。 + +### 填充行 + +`Spacer` 是位于某个缓冲区行上方或下方的一组空白行。它不包含文本:没有行号,光标会跳过它, +点击它会落到旁边的文本行上,行装饰、选区、搜索匹配和内联颜色都不会覆盖它。它的行与其他显示行一样, +因此滚动高度、滚动到某一行以及 `row_bounds` 都会把它计算在内。并排显示的两个编辑器可以用填充行补齐 +较矮的行,使两侧对应的行无论各自如何换行都从同一高度开始,就像并排 diff 那样。 + +```rust +use std::{ops::Range, rc::Rc}; + +use gpui_kit::{App, WeakEntity}; +use gpui_kit::component::input::{EditorState, Spacer, SpacerProvider}; + +/// 为每一行补上 `other` 中同一行因换行而多出的行数。 +struct Level { + this: WeakEntity, + other: WeakEntity, +} + +impl SpacerProvider for Level { + fn spacers(&self, lines: Range, cx: &App) -> Vec { + let (Some(this), Some(other)) = (self.this.upgrade(), self.other.upgrade()) else { + return Vec::new(); + }; + let rows = |editor: &EditorState, line| { + editor + .display_map() + .buffer_line_to_display_row_range(line) + .map_or(0, |rows| rows.len()) + }; + let (this, other) = (this.read(cx), other.read(cx)); + lines + .filter_map(|line| { + let (own, theirs) = (rows(this, line), rows(other, line)); + (theirs > own).then(|| Spacer::below(line, theirs - own)) + }) + .collect() + } +} + +let level = Rc::new(Level { + this: left.downgrade(), + other: right.downgrade(), +}); +left.update(cx, |state, cx| state.set_spacer_provider(Some(level), cx)); +``` + +与行装饰不同,填充行会推动其下方的所有行,因此编辑器一次性询问所有行的填充行并保留结果:设置 provider 时、 +编辑之后、文本重新换行或折叠变化之后,以及调用 `refresh_spacers` 时。询问发生在布局阶段,此时文本已按编辑器的 +宽度完成换行,并且不在编辑器的任何更新之内,因此 provider 可以读取本编辑器和其他编辑器。若结果依赖另一个 +编辑器的行,请在该编辑器的 `display_map().version()` 变化时调用 `refresh_spacers`。`Spacer::above(0, rows)` +在文本顶部补行,`with_background` 为这些行(包括行号槽)填充颜色。位于折叠隐藏的行或最后一行之后的填充行不会显示。 +**Editor Diff** 展示页对两侧都启用换行,并用填充行使它们对齐。 + +在显示映射中,填充行也是显示行:`display_row_count()` 会计入它们,`buffer_line_to_display_row_range(line)` +只包含该行文本所占的行,`display_row_to_buffer_line(row)` 把填充行视为它旁边的那一行,`is_spacer_row(row)` +用于区分填充行和文本行。填充行变化时 `version()` 也会变化,因此按版本缓存的行映射不会过期;provider 返回与当前相同的填充行时版本不变, +所以在版本变化时调用 `refresh_spacers` 最终会稳定下来。 + +## 行号栏右键菜单 + +`Editor::context_menu_with` 在构建右键菜单时知道它是在哪里打开的: +除了 capabilities,它还会收到这次单击的 `hit_test` 结果,因此菜单可以只针对行号栏 +中的某一行,而文本上仍保留通常的菜单(由 `default_context_menu` 构建)。在行号栏上右键单击会像在文本 +上一样把光标移到该行;`gutter_context_menu_moves_cursor(false)` 则在行号栏菜单打开期间保留当前选区。 + +```rust +use gpui_kit::component::input::{Editor, EditorState, default_context_menu}; + +let editor = cx.new(|cx| { + EditorState::new(window, cx) + .line_number(true) + .gutter_context_menu_moves_cursor(false) +}); + +Editor::new(&editor).context_menu_with(|menu, capabilities, hit, _, _| { + match hit { + Some(hit) if hit.is_gutter() => match hit.row() { + Some(row) => menu + .menu(format!("Bookmark Line {}", row + 1), Box::new(ToggleBookmark)) + .menu(format!("Copy Line {}", row + 1), Box::new(CopyLine)), + None => menu, // 最后一行之下:不显示菜单 + }, + _ => default_context_menu(menu, capabilities), + } +}) +``` + +构建函数在菜单打开时运行;可以在这里记下行号,供菜单操作读取。 +`examples/editor_gutter_menu` 演示了为单击的行添加书签、选中和复制。 + ## 值与事件 ```rust diff --git a/website/zh-CN/component/input.md b/website/zh-CN/component/input.md index 3111512526..c70e678eb1 100644 --- a/website/zh-CN/component/input.md +++ b/website/zh-CN/component/input.md @@ -215,6 +215,15 @@ Input::new(&input).context_menu(|menu, window, cx| { .menu("Copy", Box::new(input::Copy)) .menu("Paste", Box::new(input::Paste)) }) + +// 或者根据菜单打开的位置决定内容,其余情况保留内置菜单项。`hit` 是这次单击的 +// `hit_test` 结果:文本,或编辑器行号栏中的某一行。 +Input::new(&input).context_menu_with(|menu, capabilities, hit, window, cx| { + match hit { + Some(hit) if hit.is_gutter() => menu.menu("Custom Action", Box::new(CustomAction)), + _ => input::default_context_menu(menu, capabilities), + } +}) ``` 在选区外右键会把光标移到点击位置;在选区内右键会保留选区和光标。要处理指针下的文字(例如拼写建议菜单),读取 `context_menu_offset()`: