From fab6557919ce24b8444acc66e47ce9b09e74b79d Mon Sep 17 00:00:00 2001 From: cc-glani Date: Wed, 7 Oct 2026 02:20:32 +0200 Subject: [PATCH 1/8] input: Add line decorations with row backgrounds and gutter markers (#3359) --- crates/base/examples/showcase/mod.rs | 75 +-- crates/base/src/input/base/element.rs | 572 +++++++++++++++++- crates/base/src/input/base/kind.rs | 21 +- crates/base/src/input/base/layout.rs | 27 + crates/base/src/input/base/state.rs | 17 + .../input/editor/display_map/text_wrapper.rs | 4 + crates/base/src/input/editor/highlighting.rs | 80 ++- .../base/src/input/editor/line_decorations.rs | 405 +++++++++++++ crates/base/src/input/editor/mod.rs | 12 + crates/base/src/input/mod.rs | 11 +- crates/component/src/input/editor.rs | 139 +++++ crates/component/src/input/input.rs | 117 ++-- crates/component/src/input/mod.rs | 25 +- crates/story/src/stories/editor_story.rs | 52 +- website/base/primitives/editor.md | 23 + website/component/editor.md | 67 ++ website/zh-CN/base/primitives/editor.md | 18 + website/zh-CN/component/editor.md | 59 ++ 18 files changed, 1611 insertions(+), 113 deletions(-) create mode 100644 crates/base/src/input/editor/line_decorations.rs diff --git a/crates/base/examples/showcase/mod.rs b/crates/base/examples/showcase/mod.rs index c0cbe92735..bebf113365 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")); @@ -229,13 +227,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) @@ -254,24 +246,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( @@ -438,26 +419,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 437ee38ee7..8f93423efb 100644 --- a/crates/base/src/input/base/element.rs +++ b/crates/base/src/input/base/element.rs @@ -770,6 +770,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, @@ -1499,7 +1508,9 @@ impl TextElement { None, ); - empty_line_number.width + LINE_NUMBER_RIGHT_MARGIN + Self::gutter_marker_width(state, window) + + empty_line_number.width + + LINE_NUMBER_RIGHT_MARGIN } else if state.is_code_editor() { LINE_NUMBER_RIGHT_MARGIN } else { @@ -1518,6 +1529,34 @@ impl TextElement { (line_number_width, line_number_len) } + /// Return the width reserved for gutter markers at the left of the line numbers. + /// + /// 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.) + } + } + /// Layout shaped lines for whitespace indicators (space and tab). /// /// Returns `WhitespaceIndicators` with shaped lines for space and tab characters. @@ -1986,6 +2025,76 @@ impl TextElement { folded_lines } + /// Layout line decoration backgrounds and gutter markers for the visible rows. + /// + /// Markers are only laid out while line numbers are shown, in the slot at + /// their left. + 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) = { + 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()), + ) + }; + if decorations.is_empty() { + return LineDecorationLayout::default(); + } + + let line_height = last_layout.line_height; + let rows: Vec<_> = last_layout.row_extents().collect(); + + 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( + origin_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: @@ -2948,6 +3057,8 @@ pub(super) struct PrepaintState { /// Fold icon layout data fold_icon_layout: FoldIconLayout, folded_lines: FoldedLines, + /// Line decoration layout data + line_decoration_layout: LineDecorationLayout, // Inline completion rendering data /// Shaped ghost lines to paint after cursor row (completion lines 2+) ghost_lines: Vec, @@ -3312,6 +3423,8 @@ impl Element for TextElement { wrap_width, wrapping_indent, line_number_width, + gutter_marker_width: Self::gutter_marker_width(state, window), + ghost_lines: None, space_width, lines: Rc::new(vec![]), cursor_bounds: None, @@ -3555,6 +3668,10 @@ impl Element for TextElement { let (cursor_infos, cursor_scroll_offset, current_row, resize_reveal_owned) = self.layout_cursors(&last_layout, &mut bounds, scroll_size, window, cx); + // Ghost lines are painted after the cursor row. + last_layout.ghost_lines = current_row + .filter(|_| ghost_line_count > 0) + .map(|row| (row, ghost_lines_height)); // Completion/code-action menus position at the active caret. last_layout.cursor_bounds = cursor_infos .iter() @@ -3702,6 +3819,14 @@ impl Element for TextElement { .extras .gutter_decorations_width() .map_or(px(0.), |width| width + GUTTER_DECORATION_GAP); + // Markers sit right of the gutter decoration strip, before the line numbers. + let line_decoration_layout = self.layout_line_decorations( + original_x + line_number_offset, + &bounds, + &last_layout, + window, + cx, + ); let hitbox = window.insert_hitbox(input_bounds, HitboxBehavior::Normal); self.request_reveal( input_bounds, @@ -3801,6 +3926,7 @@ impl Element for TextElement { indent_guides_path, fold_icon_layout, folded_lines, + line_decoration_layout, ghost_first_line, ghost_lines, ghost_lines_height, @@ -3863,6 +3989,29 @@ impl Element for TextElement { } else { editor_style.background }; + let line_backgrounds = prepaint + .line_decoration_layout + .backgrounds + .iter() + .map(|&(top, height, color)| { + ( + origin.y + top, + height, + if disabled { color.opacity(0.5) } else { color }, + ) + }) + .collect::>(); + + // 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); @@ -4085,13 +4234,26 @@ impl Element for TextElement { 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, + )); + } // Each item is the normal lines. for (lines, &buffer_line) in line_numbers .iter() .zip(prepaint.last_layout.visible_buffer_lines.iter()) { - let p = point(input_bounds.origin.x, origin.y + offset_y); + let p = point( + input_bounds.origin.x + prepaint.last_layout.gutter_marker_width, + origin.y + offset_y, + ); let is_active = prepaint.current_row == Some(buffer_line); let height = line_height * lines.len() as f32; @@ -4133,6 +4295,9 @@ impl Element for TextElement { cx, ); + for marker in &mut prepaint.line_decoration_layout.markers { + marker.paint(window, cx); + } if let Some(hitbox) = prepaint.hover_definition_hitbox.as_ref() && !window.modifiers().alt { @@ -4561,6 +4726,349 @@ mod tests { (editor.unwrap(), window) } + /// Answers every row it is asked about with a background band, and with a + /// marker when `marker` is set. Records each range it was asked for. + struct Bands { + marker: bool, + asked: std::cell::RefCell>>, + } + + 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 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(); + + // 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); + ( + 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 text_origin_offset_tracks_rendered_gutter_and_scrolling(cx: &mut TestAppContext) { let line = format!("{}\n", "source text ".repeat(20)); @@ -5481,6 +5989,66 @@ mod tests { }); } + #[gpui::test] + 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!( + unpainted.read(cx).row_bounds(0).is_none(), + "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 layout = state.last_layout.as_ref().unwrap(); + 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 editor_line_number_gutter_resizes_with_document_lines(cx: &mut TestAppContext) { let (editor, window) = decoration_editor(cx, &"x\n".repeat(8), false); diff --git a/crates/base/src/input/base/kind.rs b/crates/base/src/input/base/kind.rs index e7aea857c4..17298ce699 100644 --- a/crates/base/src/input/base/kind.rs +++ b/crates/base/src/input/base/kind.rs @@ -27,10 +27,11 @@ 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 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 +112,20 @@ 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 + } + /// Semantic-token styles for a visible range, when an LSP supplies them. fn semantic_token_styles( &self, @@ -380,6 +395,7 @@ 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) inline_completion: InlineCompletion, pub(crate) context_menu_content: ContextMenuContent, pub(crate) hover_popover: Option, @@ -396,6 +412,7 @@ impl Default for EditorExtras { gutter_decorations: DecorationCollections::default(), gutter_decorations_width: gpui::px(3.), overview_ruler_decorations: DecorationCollections::default(), + line_decorations: LineDecorationProviders::default(), 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 779b1f2cf9..d61cc22b21 100644 --- a/crates/base/src/input/base/layout.rs +++ b/crates/base/src/input/base/layout.rs @@ -22,6 +22,11 @@ pub(super) struct LastLayout { pub(super) wrap_width: Option, pub(super) wrapping_indent: WrappingIndent, pub(super) line_number_width: Pixels, + /// Width reserved at the left of the line numbers for gutter markers, zero + /// when none can be painted. Part of `line_number_width`. + pub(super) gutter_marker_width: Pixels, + /// The buffer row that inline completion ghost lines follow, and their height. + pub(super) ghost_lines: Option<(usize, 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 @@ -38,6 +43,28 @@ impl LastLayout { self.lines.get(pos) } + /// 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. + pub(super) fn row_extents(&self) -> impl Iterator + '_ { + let mut top = self.visible_top; + self.lines + .iter() + .zip(&self.visible_buffer_lines) + .map(move |(line, &row)| { + 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; + } + extent + }) + } + pub(super) fn alignment_offset(&self, line_width: Pixels) -> Pixels { match self.text_align { TextAlign::Left => px(0.), diff --git a/crates/base/src/input/base/state.rs b/crates/base/src/input/base/state.rs index 069fcd708c..caf68fdbb2 100644 --- a/crates/base/src/input/base/state.rs +++ b/crates/base/src/input/base/state.rs @@ -4336,6 +4336,23 @@ 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), + )) + } + /// Replace text in range in silent. /// /// This will not trigger any UI interaction, such as auto-completion. 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 c29b6cbff1..5699fe6e64 100644 --- a/crates/base/src/input/editor/display_map/text_wrapper.rs +++ b/crates/base/src/input/editor/display_map/text_wrapper.rs @@ -1826,6 +1826,8 @@ mod tests { wrap_width: None, wrapping_indent: WrappingIndent::default(), line_number_width: px(0.), + gutter_marker_width: px(0.), + ghost_lines: None, space_width: px(0.), cursor_bounds: None, text_align: TextAlign::Left, @@ -2133,6 +2135,8 @@ mod tests { wrap_width: Some(px(10.)), wrapping_indent: WrappingIndent::Same, line_number_width: px(0.), + gutter_marker_width: px(0.), + ghost_lines: None, 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..60f360d9ea 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.clone())) + .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.clone().resolved(&dark()); + assert!(Rc::ptr_eq( + resolved.gutter_marker_renderer().unwrap(), + &renderer + )); + 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/line_decorations.rs b/crates/base/src/input/editor/line_decorations.rs new file mode 100644 index 0000000000..26ff9520b2 --- /dev/null +++ b/crates/base/src/input/editor/line_decorations.rs @@ -0,0 +1,405 @@ +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 row from the gutter to the right edge, across its + /// soft wraps, under the active line, indent guides, selections and text. A + /// marker is painted in a slot at the left of the line numbers, only while + /// they are shown; 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 581550091a..cf27a98bb4 100644 --- a/crates/base/src/input/editor/mod.rs +++ b/crates/base/src/input/editor/mod.rs @@ -271,6 +271,18 @@ 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 semantic_token_styles( &self, text: &ropey::Rope, diff --git a/crates/base/src/input/mod.rs b/crates/base/src/input/mod.rs index c7cd16d074..bd7b62eddf 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"] @@ -101,9 +103,9 @@ pub use diagnostics::{ pub use display_map::{BufferPoint, DisplayMap, DisplayPoint, FoldRange, WrappingIndent}; pub use editor::{Editor, 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}; @@ -114,6 +116,9 @@ 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 line_decorations::{ + GutterMarker, LineDecoration, LineDecorationCollection, LineDecorationProvider, +}; pub use lsp::{ CodeActionItem, CodeActionMenuState, CodeActionProvider, CompletionHighlighter, CompletionMenuOptions, CompletionMenuState, CompletionProvider, DefinitionProvider, diff --git a/crates/component/src/input/editor.rs b/crates/component/src/input/editor.rs index f69d6deee4..ab84d7a84b 100644 --- a/crates/component/src/input/editor.rs +++ b/crates/component/src/input/editor.rs @@ -470,6 +470,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}; diff --git a/crates/component/src/input/input.rs b/crates/component/src/input/input.rs index dcb56f4868..a03e30f0bb 100644 --- a/crates/component/src/input/input.rs +++ b/crates/component/src/input/input.rs @@ -13,7 +13,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; @@ -532,6 +532,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 @@ -573,41 +643,6 @@ 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, - ); state.set_editor_paddings( if state.presentation(cx).is_multi_line() { Edges { @@ -820,6 +855,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 cec772a444..c9c7de8ef3 100644 --- a/crates/component/src/input/mod.rs +++ b/crates/component/src/input/mod.rs @@ -29,18 +29,19 @@ pub use gpui_base::input::{ 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, + GutterDecorationCollection, GutterMarker, HighlightStyleResolver, HoverPopoverState, + HoverProvider, Indent, IndentInline, InputEdit, InputEditsEvent, InputEvent, InputHighlighter, + InputHighlighterFactory, 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, TabSize, TextDecoration, TextDecorationCollection, + TextareaState, ToggleCodeActions, Undo, WrappingIndent, highlight_characters, + highlight_contains, highlight_prefix, }; pub use gpui_base::input::{EditorMode, InputMode, InputModeKind, TextareaMode}; #[doc(hidden)] diff --git a/crates/story/src/stories/editor_story.rs b/crates/story/src/stories/editor_story.rs index aee6d383e0..96a55bc929 100644 --- a/crates/story/src/stories/editor_story.rs +++ b/crates/story/src/stories/editor_story.rs @@ -1,8 +1,8 @@ -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, + Render, SharedString, Styled, Task, WeakEntity, Window, div, prelude::FluentBuilder as _, px, }; use gpui_kit::component::{ @@ -105,6 +105,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 +163,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 +278,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 +305,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 +315,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/website/base/primitives/editor.md b/website/base/primitives/editor.md index 6889837dbe..92ded0ebe7 100644 --- a/website/base/primitives/editor.md +++ b/website/base/primitives/editor.md @@ -107,6 +107,29 @@ 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). + +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. + ## Highlighting and language features `InputHighlighterFactory`, `InputHighlighter`, diagnostic types, and the LSP diff --git a/website/component/editor.md b/website/component/editor.md index c2f62aee1c..ecd6587975 100644 --- a/website/component/editor.md +++ b/website/component/editor.md @@ -426,6 +426,73 @@ let ruler = editor.update(cx, |state, cx| { `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 row from the gutter to the right edge, 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 at the left of the line numbers, so it is shown only +while line numbers are. 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. + ## Value and events ```rust diff --git a/website/zh-CN/base/primitives/editor.md b/website/zh-CN/base/primitives/editor.md index 2dd51a80ff..d1d54531c6 100644 --- a/website/zh-CN/base/primitives/editor.md +++ b/website/zh-CN/base/primitives/editor.md @@ -74,6 +74,24 @@ gutter 设置或字体后需重新渲染;不要为尚未布局的编辑器代 Monaco 将这条轨道称为概览标尺。这两个集合会保留表示行边界的空范围。 参见[行号槽与概览标尺装饰](../../component/editor.md#行号槽与概览标尺装饰)。 +`create_line_decorations_collection` 挂载一个 `LineDecorationProvider`,编辑器每一帧都会向它 +询问整行背景和行号槽标记。背景由 Base 直接绘制;标记只通过 `InputEditorStyle::gutter_marker_renderer()` +绘制,样式化编辑器会提供该渲染器。参见[行装饰](../../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` 可停用标记。既有样式字段仍可直接读写。 + ## 高亮与语言功能 `InputHighlighterFactory`、`InputHighlighter`、诊断类型和 LSP provider trait 是提供给设计系统作者的底层扩展点,作用于共享的 `InputBaseState`。样式组件的应用通常应通过编辑器集成配置它们,而不是普通文本框。 diff --git a/website/zh-CN/component/editor.md b/website/zh-CN/component/editor.md index 03e164e1a8..a45e733bca 100644 --- a/website/zh-CN/component/editor.md +++ b/website/zh-CN/component/editor.md @@ -351,6 +351,65 @@ let ruler = editor.update(cx, |state, 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` 读取颜色,使其跟随主题变化。与其他装饰集合一样,各集合相互独立; +后创建的集合绘制在先创建的集合之上。 + +背景从行号槽一直延伸到右边缘,覆盖该行软换行后的全部显示行,位于当前行高亮、缩进参考线、 +选区和文字下方。标记绘制在行号左侧的独立槽位中,因此只在显示行号时出现。只要有集合设置了 +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 标记了最后三行。 + ## 值与事件 ```rust From b566c45b6c3d8f0decfeb41e3db9a429b0372222 Mon Sep 17 00:00:00 2001 From: cc-glani Date: Fri, 9 Oct 2026 16:14:44 +0200 Subject: [PATCH 2/8] scrollbar: Let the vertical scrollbar sit on the left side (#3416) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The vertical scrollbar is hard-coded to the right edge and the horizontal one to the bottom. In a side-by-side diff the left pane's scrollbar belongs on its outer (left) edge, so the two panes mirror each other. This adds `ScrollbarPlacement`, one value for both axes, set with one call — `Scrollbar::placement`, and `scrollbar_placement` / `set_scrollbar_placement` on the editor state: | | vertical | horizontal | | --- | --- | --- | | `BottomRight` (default, unchanged) | right | bottom | | `BottomLeft` | left | bottom | | `TopRight` | right | top | | `TopLeft` | left | top | Each axis follows its half of the placement: the track sits on that edge, the thumb and its hit area are anchored to it, and the bar slides in from that edge. When both bars show, the vertical one keeps its full height and the horizontal one stops short of it — at its start when the vertical bar is on the left, at its end when it is on the right. A single-axis scrollbar uses only its own half. The editor reserves no room for its horizontal bar at the bottom today, so at the top it overlays the first line the same way. Nothing changes by default. Targets `next`: it is the first half of a mirrored side-by-side diff whose second half, #3417, builds on #3359's gutter markers, which are on `next`. | Before | After | | ------ | ----- | | before | scrollbar-left | The four placements (`ScrollbarMode::Always`); the story switches Dataset and Placement from one Options menu (`d8057f92`): scrollbar placements, light scrollbar placements, dark `gpui_base` (re-exported by `gpui_component`, also from `gpui_component::scroll`): - `ScrollbarPlacement { BottomRight, BottomLeft, TopRight, TopLeft }` — default `BottomRight`; `is_left()` (vertical bar on the left), `is_top()` (horizontal bar at the top). - `Scrollbar::placement(mut self, placement: ScrollbarPlacement) -> Self`. - `InputBaseState::scrollbar_placement(mut self, placement: ScrollbarPlacement) -> Self` — builder for the editor's scrollbars. - `InputBaseState::set_scrollbar_placement(&mut self, placement: ScrollbarPlacement, cx: &mut Context)` — replaces the whole placement at runtime. - `cargo test -p gpui-base --lib scrollbar`: the `Scrollbar` harness clicks and drags on each placement — the vertical track and thumb on the left, the horizontal track and thumb at the top, the horizontal track starting after a left bar and ending before a right one with both bars at the top, a thumb drag and a track click moving the offset the right way — and `visibility_translation_moves_toward_the_nearest_edge` covers all four placements on both axes; an editor layout test for `TopLeft`. Each fails with its code reverted. - `cargo run -p gpui-component-story -- scrollbar`, then Options → Placement. - [x] I have read the [CONTRIBUTING](../CONTRIBUTING.md) document and followed the guidelines. - [x] Reviewed the changes in this PR and confirmed AI generated code (If any) is accurate. - [x] Passed `cargo run` for story tests related to the changes. - [x] Tested macOS, Windows and Linux platforms performance (if the change is platform-specific) --------- Co-authored-by: Jason Lee --- crates/base/src/input/base/element.rs | 113 +++++- crates/base/src/input/base/state.rs | 23 ++ .../base/src/input/scrollbar_presentation.rs | 9 +- crates/base/src/lib.rs | 2 +- crates/base/src/scrollbar.rs | 339 +++++++++++++++--- crates/component/src/scroll/mod.rs | 2 +- crates/story/src/stories/scrollbar_story.rs | 77 +++- website/base/primitives/scrollbar.md | 24 +- website/component/editor.md | 12 + website/zh-CN/base/primitives/scrollbar.md | 19 +- website/zh-CN/component/editor.md | 9 +- 11 files changed, 548 insertions(+), 81 deletions(-) diff --git a/crates/base/src/input/base/element.rs b/crates/base/src/input/base/element.rs index 8f93423efb..50a1390efd 100644 --- a/crates/base/src/input/base/element.rs +++ b/crates/base/src/input/base/element.rs @@ -17,7 +17,7 @@ use smallvec::SmallVec; use std::{collections::BTreeSet, ops::Range, rc::Rc}; use crate::{ - Scrollbar, + Scrollbar, ScrollbarPlacement, input::{RopeExt as _, blink_cursor::CURSOR_WIDTH, display_map::LineLayout}, }; @@ -197,6 +197,7 @@ pub(super) struct EditorScrollbarSnapshot { line_height: Pixels, padding_top: Pixels, wrap_width: Option, + placement: ScrollbarPlacement, } impl EditorScrollbarSnapshot { @@ -213,12 +214,14 @@ impl EditorScrollbarSnapshot { last_layout.line_number_width, scroll_size, state.editor_paddings, + state.scrollbar_placement, ), cursor_scroll_offset, soft_wrap: state.soft_wrap, line_height: last_layout.line_height, padding_top: state.editor_paddings.top, wrap_width: last_layout.wrap_width, + placement: state.scrollbar_placement, } } } @@ -229,8 +232,11 @@ impl EditorScrollbarLayout { line_number_width: 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 line_number_width == px(0.) { px(0.) } else { paddings.left + line_number_width - LINE_NUMBER_RIGHT_MARGIN @@ -336,6 +342,7 @@ impl Element for EditorScrollbar { } else { crate::ScrollbarAxis::Both }, + placement: snapshot.placement, }; renderer(presentation, window, cx) } else { @@ -344,6 +351,7 @@ impl Element for EditorScrollbar { } else { Scrollbar::vertical(&scroll_handle) } + .placement(snapshot.placement) .viewport_bounds(snapshot.layout.bounds) .scroll_viewport_size(snapshot.layout.scroll_viewport_size) .scroll_size(snapshot.layout.scroll_size) @@ -580,8 +588,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 scale = track.size.height / content_height; @@ -6604,6 +6618,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"; @@ -7008,8 +7062,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, @@ -7018,8 +7077,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, @@ -7032,6 +7096,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.))); diff --git a/crates/base/src/input/base/state.rs b/crates/base/src/input/base/state.rs index caf68fdbb2..19b3e9505e 100644 --- a/crates/base/src/input/base/state.rs +++ b/crates/base/src/input/base/state.rs @@ -37,6 +37,7 @@ use super::{ mode::LayoutMode, undo_manager::{EditIntent, UndoManager}, }; +use crate::ScrollbarPlacement; use crate::actions::{SelectDown, SelectLeft, SelectRight, SelectUp}; use crate::input::blink_cursor::CURSOR_WIDTH; use crate::input::movement::MoveDirection; @@ -542,6 +543,7 @@ 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, /// The widest measured unwrapped line width and what it was measured for. pub(super) longest_line_width: Cell>, pub(super) editor_paddings: Edges, @@ -1038,6 +1040,7 @@ impl InputBaseState { scroll_size: gpui::size(px(0.), px(0.)), editor_scrollbar_snapshot: Cell::new(None), overview_ruler_rows: Default::default(), + scrollbar_placement: ScrollbarPlacement::default(), longest_line_width: Cell::new(None), editor_paddings: Edges::default(), deferred_scroll_offset: None, @@ -13144,6 +13147,26 @@ 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 line numbers. 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(); + } + /// Set the soft wrap mode, default is true. #[doc(hidden)] pub fn soft_wrap(mut self, wrap: bool) -> Self { diff --git a/crates/base/src/input/scrollbar_presentation.rs b/crates/base/src/input/scrollbar_presentation.rs index 4eca2ddbec..f5bd882371 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; @@ -14,6 +14,7 @@ pub struct EditorScrollbarContext { pub(crate) scroll_viewport: Size, pub(crate) content: Size, pub(crate) axis: ScrollbarAxis, + pub(crate) placement: ScrollbarPlacement, } impl EditorScrollbarContext { @@ -21,6 +22,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 + } + /// The editor's viewport without padding, for consumers that need its /// text layout size. Scrollbars should use [`ScrollbarHandle::content_size`] /// and [`ScrollbarHandle::viewport_bounds`] to calculate the scroll range; 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 e647a7ca62..210e4fade4 100644 --- a/crates/base/src/scrollbar.rs +++ b/crates/base/src/scrollbar.rs @@ -474,10 +474,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) } @@ -636,6 +647,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 { @@ -815,6 +856,7 @@ impl ScrollbarAxis { pub struct Scrollbar { pub(crate) id: ElementId, axis: ScrollbarAxis, + placement: ScrollbarPlacement, mode: Option, scroll_handle: Rc, scroll_size: Option>, @@ -840,6 +882,7 @@ 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, @@ -929,6 +972,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 @@ -1412,7 +1464,7 @@ impl Element for Scrollbar { }; // 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,10 +1478,16 @@ 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() { + hitbox.origin + } else { + point( + hitbox.origin.x + hitbox.size.width - track_width, + hitbox.origin.y, + ) + } + } else if self.placement.is_top() { + hitbox.origin } else { point( hitbox.origin.x, @@ -1499,57 +1557,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 +1682,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); @@ -2028,7 +2098,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() ); @@ -2098,18 +2173,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] @@ -2281,13 +2367,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 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); } @@ -2301,6 +2391,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({ @@ -2308,6 +2408,7 @@ mod tests { move |_, _| ScrollbarHarness { handle, axis, + placement, mode, scroll_viewport_size: None, } @@ -2324,6 +2425,7 @@ mod tests { move |_, _| ScrollbarHarness { handle, axis: ScrollbarAxis::Vertical, + placement: ScrollbarPlacement::default(), mode: ScrollbarMode::Always, scroll_viewport_size: Some(size(px(100.), px(80.))), } @@ -2518,6 +2620,144 @@ mod tests { assert_eq!(vertical.offset().x, px(0.)); } + #[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( @@ -2680,6 +2920,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/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/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/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 ecd6587975..32418d9429 100644 --- a/website/component/editor.md +++ b/website/component/editor.md @@ -141,6 +141,16 @@ 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. 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. + +```rust +EditorState::new(window, cx).scrollbar_placement(ScrollbarPlacement::BottomLeft) +``` + ## Manual completions `ShowCompletions` requests suggestions without editing text. It has **no default @@ -420,6 +430,8 @@ 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 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 a45e733bca..27bcab50ad 100644 --- a/website/zh-CN/component/editor.md +++ b/website/zh-CN/component/editor.md @@ -118,6 +118,12 @@ let editor = cx.new(|cx| { `scroll_bounce(true)` 让超出编辑器高度的代码在触控板或 Magic Mouse 的精细像素滚动到达顶部或底部时越过边缘并弹回,与 [Textarea](./textarea.md#滚动回弹) 相同。行号栏随代码移动,外框和滚动条保持不动;普通鼠标滚轮的按行滚动不触发回弹。 +滚动条默认位于右侧和底部。使用 `scrollbar_placement` 可调整其位置;放在左侧的纵向滚动条位于编辑器左边缘,覆盖在行号之上。与覆盖最后一行的底部滚动条一样,顶部滚动条覆盖在第一行之上,不为自身预留空间。运行时可用 `set_scrollbar_placement` 替换位置。 + +```rust +EditorState::new(window, cx).scrollbar_placement(ScrollbarPlacement::BottomLeft) +``` + ## 主动补全 `ShowCompletions` 可以在不修改文本的情况下请求补全,**没有默认快捷键**。应用应结合平台习惯选择绑定,避开 Ctrl+Space 等输入法快捷键。Editor 的绑定可以使用 `Input && mode == editor` 条件;现有 `Input` 绑定仍然有效。 @@ -345,7 +351,8 @@ 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`、 From 76ce735f2ec6276c25a229d4e01cb4af963c3e91 Mon Sep 17 00:00:00 2001 From: cc-glani Date: Fri, 9 Oct 2026 17:32:09 +0200 Subject: [PATCH 3/8] editor: Support mirrored gutters for side-by-side diffs (#3417) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Builds on #3416 (`ScrollbarPlacement`, merged into `next`) and #3359's gutter markers. 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 and can be compared directly. The editor's gutter is always on the left of the text today, so the left pane cannot do that. This adds `gutter_side(Side)` / `set_gutter_side` to the editor state for the left pane of such a diff, default `Side::Left` (unchanged). On the right the gutter is mirrored: the same columns, in the same order counted from the text, with the line numbers aligned toward it. The text and gutter x offsets are computed once per layout and used for painting, hit testing, IME bounds and scroll-into-view. A scrollbar on the gutter's side stays outermost. With the gutter on the right and the scrollbar on the left — the left pane's outer edge — the text keeps clear of the scrollbar's whole track: its effective width, the active thumb included, less the editor's left padding, at least the usual 10 px margin; that one reservation sets the text origin, width, wrap width and scroll size. Line numbers are placed by their shaped width rather than padded with spaces: in a proportional font a space is about a third of a digit, so the default left gutter left right-aligned numbers ragged and 6–11 px short of the text; they now line up against it on either side. `Editor` puts its narrow padding on the gutter's side. `gutter_order([GutterColumn])` orders the gutter's columns from the text outward, on either side: the default is `[FoldIcons, LineNumbers, Markers]` (unchanged); `[FoldIcons, Markers, LineNumbers]` puts a diff's change markers between the text and the line numbers, as IntelliJ's diff does. A column left out follows the listed ones in its default order. The **Editor Diff** story (`70b271ad`, @huacnlee) shows original and modified source with change markers; its Options menu switches between both gutters on the left and center-facing gutters, and optionally puts the markers before the line numbers. The two panes scroll together, by wheel and by dragging either scrollbar. The ordinary Editor story is unchanged. | Before | After | | ------ | ----- | | scrollbar-left | mirrored | A side-by-side diff with changed lines marked; the left pane uses `.scrollbar_placement(ScrollbarPlacement::BottomLeft).gutter_side(Side::Right)`, mirrored: | Both gutters on the left | Mirrored | | ------------------------ | -------- | | both gutters on the left | mirrored | The columns in IntelliJ's order, `.gutter_order([GutterColumn::FoldIcons, GutterColumn::Markers, GutterColumn::LineNumbers])` on both panes — without and with folding (an empty fold column here): | IntelliJ's order | With folding | | ---------------- | ------------ | | IntelliJ's order | IntelliJ's order with folding | `gpui_base` (re-exported by `gpui_component`): - `InputBaseState::gutter_side(mut self, side: Side) -> Self` — builder: which side of the text the gutter is drawn on; default `Side::Left`, `Side::Right` for the left pane of a side-by-side diff. - `InputBaseState::set_gutter_side(&mut self, side: Side, cx: &mut Context)` — the same, at runtime. - `InputPresentation::gutter_side(&self) -> Side` — the side the editor's gutter sits on. - `GutterColumn { FoldIcons, LineNumbers, Markers }` — a column of the gutter. - `InputBaseState::gutter_order(mut self, columns: impl IntoIterator) -> Self` / `set_gutter_order(&mut self, columns, cx: &mut Context)` — the columns from the text outward; default `[FoldIcons, LineNumbers, Markers]`; a column left out follows in its default order, a repeat is ignored. - `cargo test -p gpui-base --lib`: new tests for the text and gutter origins with an unchanged wrap width, the mirrored fold icons and columns, the scrollbar staying outermost (left/left, right/left, right/right), clicks in the text and in the gutter on both sides, caret / IME / `range_to_bounds` / selection-path x including a long line scrolled clear of the gutter, a right-side case in the existing gutter-bounds test, every gutter column — markers included — mirrored to 0.01 px for all six orders with folding on and off, the order normalised and counted from the text on both sides, clicks on the fold icon and the line number in every side/order combination, `Editor` keeping its gutter-side padding, and the text clear of the whole track of a left scrollbar with zero padding and with a wider themed track. Each fails with its code reverted. - `cargo test -p gpui-component-story --lib editor_diff`: layout switching keeps both sources, and the panes stay aligned on wheel input and while either scrollbar is dragged. - `cargo run -p gpui-component-story -- 'Editor Diff'`, then Options. - [x] I have read the [CONTRIBUTING](../CONTRIBUTING.md) document and followed the guidelines. - [x] Reviewed the changes in this PR and confirmed AI generated code (If any) is accurate. - [x] Passed `cargo run` for story tests related to the changes. - [x] Tested macOS, Windows and Linux platforms performance (if the change is platform-specific) --------- Co-authored-by: Jason Lee --- crates/base/src/input/base/element.rs | 1094 +++++++++++++++-- crates/base/src/input/base/layout.rs | 65 +- crates/base/src/input/base/state.rs | 92 +- .../input/editor/display_map/text_wrapper.rs | 12 + crates/base/src/input/editor/indent.rs | 2 +- .../base/src/input/editor/line_decorations.rs | 10 +- crates/base/src/input/mod.rs | 1 + crates/base/src/scrollbar.rs | 121 +- crates/component/src/input/editor.rs | 29 + crates/component/src/input/input.rs | 21 +- crates/component/src/input/mod.rs | 2 +- crates/shell/component-inventory.json | 6 + crates/story/src/gallery.rs | 1 + crates/story/src/stories/editor_diff_story.rs | 417 +++++++ crates/story/src/stories/mod.rs | 2 + .../js_story/fixtures/verify-coverage.mjs | 6 + website/component/editor.md | 63 +- website/zh-CN/component/editor.md | 28 +- 18 files changed, 1800 insertions(+), 172 deletions(-) create mode 100644 crates/story/src/stories/editor_diff_story.rs diff --git a/crates/base/src/input/base/element.rs b/crates/base/src/input/base/element.rs index 50a1390efd..8a3dd26ea1 100644 --- a/crates/base/src/input/base/element.rs +++ b/crates/base/src/input/base/element.rs @@ -1,6 +1,7 @@ use crate::input::{DisplayMap, FoldRange, InputExtras as _, InputModeKind, OverviewRulerLane}; use gpui::Corners; use gpui::Half; +use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, App, Bounds, Edges, Element, ElementId, ElementInputHandler, Entity, GlobalElementId, @@ -17,12 +18,12 @@ use smallvec::SmallVec; use std::{collections::BTreeSet, ops::Range, rc::Rc}; use crate::{ - Scrollbar, ScrollbarPlacement, + 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}, @@ -198,6 +199,7 @@ pub(super) struct EditorScrollbarSnapshot { padding_top: Pixels, wrap_width: Option, placement: ScrollbarPlacement, + horizontal_bounds: Option>, } impl EditorScrollbarSnapshot { @@ -208,14 +210,33 @@ impl EditorScrollbarSnapshot { cursor_scroll_offset: Point, state: &InputBaseState, ) -> Self { + let layout = EditorScrollbarLayout::new( + input_bounds, + last_layout.text_origin_x, + scroll_size, + state.editor_paddings, + state.scrollbar_placement, + ); + 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 + - LINE_NUMBER_RIGHT_MARGIN) + .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, - state.scrollbar_placement, - ), + layout, + horizontal_bounds, cursor_scroll_offset, soft_wrap: state.soft_wrap, line_height: last_layout.line_height, @@ -229,17 +250,17 @@ impl EditorScrollbarSnapshot { 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 placement.is_left() { -paddings.left - } else if line_number_width == px(0.) { + } 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( @@ -353,6 +374,9 @@ impl Element for EditorScrollbar { } .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() @@ -417,14 +441,17 @@ fn editor_gutter_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, ), } @@ -637,6 +664,118 @@ fn layout_overview_ruler( .collect() } +/// 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. +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(LINE_NUMBER_RIGHT_MARGIN, |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 + - LINE_NUMBER_RIGHT_MARGIN + - 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. @@ -911,7 +1050,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(); @@ -1036,9 +1174,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 { @@ -1086,7 +1224,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( @@ -1136,7 +1274,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) { @@ -1244,7 +1382,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() @@ -1494,14 +1632,14 @@ impl TextElement { (visible_range, visible_buffer_lines, visible_top) } - /// Return (line_number_width, line_number_len) + /// Return the width of the gutter. fn layout_line_numbers( state: &InputBaseState, text: &Rope, font_size: Pixels, style: &TextStyle, window: &mut Window, - ) -> (Pixels, usize) { + ) -> Pixels { let total_lines = text.lines_len(); // Reserve three digits for small documents, then follow the actual // line count up to seven digits. @@ -1536,14 +1674,10 @@ 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, line_number_len) + line_number_width + Self::gutter_decorations_width(state) } - /// Return the width reserved for gutter markers at the left of the line numbers. + /// 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 @@ -1571,6 +1705,15 @@ impl TextElement { } } + /// 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). /// /// Returns `WhitespaceIndicators` with shaped lines for space and tab characters. @@ -1714,7 +1857,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 @@ -1814,7 +1957,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, @@ -1857,19 +2003,18 @@ impl TextElement { // Second pass: create and prepaint icons let line_height = last_layout.line_height; - let line_number_width = - last_layout.line_number_width - LINE_NUMBER_RIGHT_MARGIN - FOLD_ICON_HITBOX_WIDTH; + 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_width, + 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), @@ -1994,7 +2139,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( @@ -2041,8 +2186,8 @@ impl TextElement { /// Layout line decoration backgrounds and gutter markers for the visible rows. /// - /// Markers are only laid out while line numbers are shown, in the slot at - /// their left. + /// Markers are only laid out while line numbers are shown, in their column + /// of the gutter. fn layout_line_decorations( &self, origin_x: Pixels, @@ -2057,7 +2202,7 @@ impl TextElement { ) else { return LineDecorationLayout::default(); }; - let (decorations, renderer, marker_size) = { + let (decorations, renderer, marker_size, folding) = { let state = self.state.read(cx); let renderer = state .mode @@ -2071,6 +2216,7 @@ impl TextElement { .editor_style .gutter_marker_size() .to_pixels(window.rem_size()), + state.mode.is_folding(), ) }; if decorations.is_empty() { @@ -2079,6 +2225,7 @@ impl TextElement { 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 { @@ -2098,7 +2245,7 @@ impl TextElement { && marker_size > Pixels::ZERO { let origin = point( - origin_x, + marker_x, bounds.origin.y + top + (line_height - marker_size).half(), ); let mut element = render(marker); @@ -2706,7 +2853,7 @@ 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), )); } } @@ -3061,8 +3208,6 @@ pub(super) struct PrepaintState { range_decoration_fills: Vec<(Path, Hsla)>, range_decoration_frames: Vec<(Path, Hsla)>, gutter_decorations: Vec, - /// How far the gutter decoration strip pushes the line numbers right. - line_number_offset: Pixels, hover_definition_hitbox: Option, indent_guides_path: Option>, /// The whole input, for deciding whether a long press started in it. @@ -3349,12 +3494,32 @@ impl Element for TextElement { }; // Calculate the width of the line numbers - let (line_number_width, line_number_len) = + let line_number_width = Self::layout_line_numbers(&state, &text, text_size, &text_style, window); + let gutter_side = state.gutter_side; + let (mut text_origin_x, gutter_origin_x) = if gutter_side.is_left() { + (line_number_width, px(0.)) + } else { + (px(0.), bounds.size.width - line_number_width) + }; + // The text keeps clear of a scrollbar on the left, and at least the margin it keeps + // from the right edge. + let mut reserved_width = line_number_width; + if state.scrollbar_placement.is_left() { + let clearance = (Scrollbar::vertical(&state.scroll_handle).full_width(cx) + - state.editor_paddings.left) + .max(RIGHT_MARGIN); + if text_origin_x < clearance { + reserved_width += clearance - text_origin_x; + text_origin_x = clearance; + } + } + let text_width = bounds.size.width - reserved_width; + let mut bounds = bounds; let wrap_width = if multi_line && state.soft_wrap { - Some(bounds.size.width - line_number_width - RIGHT_MARGIN) + Some(text_width - RIGHT_MARGIN) } else { None }; @@ -3381,7 +3546,7 @@ impl Element for TextElement { let line_height = window.line_height(); let token_elements = self.measure_tokens( - (bounds.size.width - line_number_width - RIGHT_MARGIN).max(px(1.)), + (text_width - RIGHT_MARGIN).max(px(1.)), line_height, bounds.size.height, window, @@ -3438,7 +3603,13 @@ impl Element for TextElement { wrapping_indent, line_number_width, gutter_marker_width: Self::gutter_marker_width(state, window), + gutter_decorations_width: Self::gutter_decorations_width(state), ghost_lines: None, + gutter_side, + gutter_order: state.gutter_order, + text_origin_x, + gutter_origin_x, + text_width, space_width, lines: Rc::new(vec![]), cursor_bounds: None, @@ -3614,8 +3785,8 @@ impl Element for TextElement { // last content row, so take the max rather than summing — summing // left a band of empty space the cursor could never reach. let mut scroll_size = size( - if longest_line_width + line_number_width + RIGHT_MARGIN > 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 }, @@ -3630,7 +3801,7 @@ impl Element for TextElement { // TODO: should be add some gap to right, to convenient to focus on boundary position if last_layout.text_align == TextAlign::Right || last_layout.text_align == TextAlign::Center { - scroll_size.width = longest_line_width + line_number_width; + scroll_size.width = longest_line_width + reserved_width; } // `position_for_index` for example @@ -3738,22 +3909,22 @@ impl Element for TextElement { let state = self.state.read(cx); let line_numbers = if state.mode.line_number() { let mut line_numbers = Vec::with_capacity(last_layout.visible_buffer_lines.len()); - let other_line_runs = vec![TextRun { - len: line_number_len, + let other_line_run = TextRun { + len: 0, font: style.font(), color: state.editor_style.muted_foreground, background_color: None, underline: None, strikethrough: None, - }]; - let current_line_runs = vec![TextRun { - len: line_number_len, + }; + let current_line_run = TextRun { + len: 0, font: style.font(), color: state.editor_style.foreground, background_color: None, underline: None, strikethrough: None, - }]; + }; // build line numbers for (line, &buffer_line) in last_layout @@ -3761,18 +3932,20 @@ impl Element for TextElement { .iter() .zip(last_layout.visible_buffer_lines.iter()) { - let line_no: SharedString = format!( - "{:>width$}", - displayed_line_number(buffer_line + 1), - width = line_number_len - ) - .into(); + // Aligned when painted, as padding with spaces only lines up in a + // monospace font. + let line_no: SharedString = + displayed_line_number(buffer_line + 1).to_string().into(); - let runs = if current_row == Some(buffer_line) { - ¤t_line_runs + let run = if current_row == Some(buffer_line) { + ¤t_line_run } else { - &other_line_runs + &other_line_run }; + let runs = [TextRun { + len: line_no.len(), + ..run.clone() + }]; let mut sub_lines: SmallVec<[ShapedLine; 1]> = SmallVec::new(); sub_lines.push( @@ -3819,28 +3992,24 @@ impl Element for TextElement { .unwrap_or_default(); (rows.end.saturating_sub(1), ghost_lines_height) }); + let gutter_decorations_x = { + let state = self.state.read(cx); + gutter_decorations_x( + &last_layout, + state.mode.is_folding(), + state.extras.gutter_decorations_width().unwrap_or_default(), + ) + }; let gutter_decorations = self.layout_gutter_decorations( - original_x, + original_x + gutter_decorations_x, &bounds, &input_bounds, &last_layout, ghost_rows, cx, ); - let line_number_offset = self - .state - .read(cx) - .extras - .gutter_decorations_width() - .map_or(px(0.), |width| width + GUTTER_DECORATION_GAP); - // Markers sit right of the gutter decoration strip, before the line numbers. - let line_decoration_layout = self.layout_line_decorations( - original_x + line_number_offset, - &bounds, - &last_layout, - window, - cx, - ); + let line_decoration_layout = + self.layout_line_decorations(original_x, &bounds, &last_layout, window, cx); let hitbox = window.insert_hitbox(input_bounds, HitboxBehavior::Normal); self.request_reveal( input_bounds, @@ -3936,7 +4105,6 @@ impl Element for TextElement { range_decoration_fills, range_decoration_frames, gutter_decorations, - line_number_offset, indent_guides_path, fold_icon_layout, folded_lines, @@ -4081,7 +4249,7 @@ impl Element for TextElement { .zip(prepaint.last_layout.visible_buffer_lines.iter()) { let p = point( - origin.x + prepaint.last_layout.line_number_width + scroll_offset, + origin.x + prepaint.last_layout.text_origin_x + scroll_offset, origin.y + offset_y, ); @@ -4162,7 +4330,7 @@ impl Element for TextElement { let row = buffer_line; let line_y = origin.y + offset_y; let p = point( - origin.x + prepaint.last_layout.line_number_width + (scroll_offset), + origin.x + prepaint.last_layout.text_origin_x + (scroll_offset), line_y, ); @@ -4183,19 +4351,14 @@ impl Element for TextElement { // 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_x = origin.x + prepaint.last_layout.text_origin_x; for ghost_line in ghost_lines { let ghost_p = point(ghost_x, origin.y + offset_y); // Paint semi-transparent background for ghost line - let ghost_bounds = Bounds::new( - ghost_p, - size( - bounds.size.width - prepaint.last_layout.line_number_width, - line_height, - ), - ); + let ghost_bounds = + Bounds::new(ghost_p, size(prepaint.last_layout.text_width, line_height)); window.paint_quad(fill(ghost_bounds, editor_background)); // Paint ghost line text @@ -4246,6 +4409,7 @@ impl Element for TextElement { prepaint.last_layout.line_number_width, prepaint.ghost_lines_height, editor_paddings, + prepaint.last_layout.gutter_side, ); window.paint_quad(fill(gutter_bounds, gutter_bg)); // Repaint line decoration backgrounds over the gutter background. @@ -4258,16 +4422,14 @@ impl Element for TextElement { color, )); } + let folding = self.state.read(cx).mode.is_folding(); // Each item is the normal lines. for (lines, &buffer_line) in line_numbers .iter() .zip(prepaint.last_layout.visible_buffer_lines.iter()) { - let p = point( - input_bounds.origin.x + prepaint.last_layout.gutter_marker_width, - origin.y + offset_y, - ); + let y = origin.y + offset_y; let is_active = prepaint.current_row == Some(buffer_line); let height = line_height * lines.len() as f32; @@ -4276,7 +4438,7 @@ impl Element for TextElement { if let Some(bg_color) = active_line_color { window.paint_quad(fill( Bounds::new( - point(gutter_bounds.origin.x, p.y), + point(gutter_bounds.origin.x, y), size(gutter_bounds.size.width, height), ), bg_color, @@ -4284,8 +4446,9 @@ impl Element for TextElement { } } - let p = point(p.x + prepaint.line_number_offset, p.y); for line in lines { + let x = line_number_x(&prepaint.last_layout, folding, line.width); + let p = point(input_bounds.origin.x + x, y); _ = line.paint(p, line_height, TextAlign::Left, None, window, cx); offset_y += line_height; } @@ -4586,9 +4749,10 @@ mod tests { GutterDecorationCollection, OverviewRulerDecoration, OverviewRulerDecorationCollection, RangeDecoration, Redo, Undo, }; + use crate::{ScrollbarMode, ScrollbarStyles, ScrollbarTheme, Theme}; use gpui::{ AppContext as _, Context, EntityInputHandler as _, ListAlignment, ListOffset, ListState, - Render, TestAppContext, VisualTestContext, div, list, prelude::FluentBuilder as _, + Render, TestAppContext, VisualTestContext, div, list, }; #[test] @@ -5024,6 +5188,55 @@ mod tests { } } + #[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); @@ -6108,6 +6321,673 @@ mod tests { }); } + #[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 + ); + 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:?}"); + } + } + } + }); + } + + /// 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) + }; + + 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(); + ( + point(center(numbers_inset, numbers_width), y), + point(center(fold_inset, FOLD_ICON_HITBOX_WIDTH), y), + ) + }); + + // 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_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(in_text, gpui::Modifiers::default()); + editor.read_with(&cx, |state, _| { + assert_eq!(state.selected_range(), 0..0, "{track_width:?} track"); + }); + } + } + + #[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() + .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 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| { + editor.update(cx, |state, 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 (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() + .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); + + // The caret at the end of a long line scrolls into view, left of the gutter. + editor.update(cx, |state, cx| { + let end = state.text.len(); + state.set_selected_range(end..end, cx); + }); + window.draw(cx).clear(cx); + 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!( + caret.left() > input_bounds.left() + layout.gutter_origin_x - RIGHT_MARGIN * 2. + ); + }); + } + #[gpui::test] fn geometric_decorations_clip_scrolled_viewport_and_cull_offscreen_ranges( cx: &mut TestAppContext, @@ -7146,9 +8026,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] diff --git a/crates/base/src/input/base/layout.rs b/crates/base/src/input/base/layout.rs index d61cc22b21..48b0579af1 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, Half, Pixels, ShapedLine, TextAlign, px}; +use crate::Side; + use super::{WrappingIndent, display_map::LineLayout}; #[derive(Clone, Default)] @@ -10,6 +12,51 @@ 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 + } +} + #[derive(Clone)] pub(super) struct LastLayout { pub(super) visible_range: Range, @@ -22,11 +69,25 @@ pub(super) struct LastLayout { pub(super) wrap_width: Option, pub(super) wrapping_indent: WrappingIndent, pub(super) line_number_width: Pixels, - /// Width reserved at the left of the line numbers for gutter markers, zero - /// when none can be painted. Part of `line_number_width`. + /// 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)>, + 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 diff --git a/crates/base/src/input/base/state.rs b/crates/base/src/input/base/state.rs index 19b3e9505e..b169418746 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, @@ -38,6 +38,7 @@ use super::{ 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; @@ -544,6 +545,8 @@ pub struct InputBaseState { /// 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, @@ -693,6 +696,7 @@ pub struct InputPresentation { masked: bool, multi_line: bool, code_editor: bool, + gutter_side: Side, text_align: TextAlign, placeholder: SharedString, mask_placeholder: Option, @@ -734,6 +738,10 @@ impl InputPresentation { self.code_editor } + pub fn gutter_side(&self) -> Side { + self.gutter_side + } + pub fn text_align(&self) -> TextAlign { self.text_align } @@ -833,6 +841,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(), @@ -1041,6 +1050,8 @@ impl InputBaseState { 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, @@ -1272,7 +1283,7 @@ impl InputBaseState { .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)); } @@ -3167,7 +3178,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 @@ -3760,7 +3771,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 // @@ -3772,7 +3783,7 @@ 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 y_offset = last_layout.visible_top; // Position relative to the last line walked, kept for a pointer that ends up @@ -5127,12 +5138,11 @@ 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 text_origin = point(last_layout.text_origin_x, px(0.)); let mut y_offset = last_layout.visible_top; let start_row = self @@ -5174,7 +5184,7 @@ impl EntityInputHandler for InputBaseState { 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. @@ -5184,9 +5194,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), )) } @@ -5200,7 +5210,7 @@ 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 line_top = px(0.); for (vi, line) in last_layout.lines.iter().enumerate() { @@ -13150,8 +13160,9 @@ impl InputBaseState { /// The placement of the scrollbars, default is [`ScrollbarPlacement::BottomRight`]. /// /// On the left, the vertical scrollbar sits on the input's left edge, over - /// the line numbers. At the top, the horizontal scrollbar overlays the - /// first line, as at the bottom it overlays the last. + /// 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 @@ -13167,6 +13178,47 @@ impl InputBaseState { 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 { @@ -13383,18 +13435,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/text_wrapper.rs b/crates/base/src/input/editor/display_map/text_wrapper.rs index 5699fe6e64..8a97d41936 100644 --- a/crates/base/src/input/editor/display_map/text_wrapper.rs +++ b/crates/base/src/input/editor/display_map/text_wrapper.rs @@ -1827,7 +1827,13 @@ mod tests { wrapping_indent: WrappingIndent::default(), line_number_width: px(0.), gutter_marker_width: px(0.), + gutter_decorations_width: px(0.), ghost_lines: None, + 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, @@ -2136,7 +2142,13 @@ mod tests { wrapping_indent: WrappingIndent::Same, line_number_width: px(0.), gutter_marker_width: px(0.), + gutter_decorations_width: px(0.), ghost_lines: None, + 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/indent.rs b/crates/base/src/input/editor/indent.rs index 08ccd11fc9..6ef1561b53 100644 --- a/crates/base/src/input/editor/indent.rs +++ b/crates/base/src/input/editor/indent.rs @@ -142,7 +142,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)); diff --git a/crates/base/src/input/editor/line_decorations.rs b/crates/base/src/input/editor/line_decorations.rs index 26ff9520b2..2ffb9af18e 100644 --- a/crates/base/src/input/editor/line_decorations.rs +++ b/crates/base/src/input/editor/line_decorations.rs @@ -207,10 +207,12 @@ impl InputBaseState { /// range decorations, rows are not tracked across edits: the provider answers /// for the text as it is when asked. /// - /// A background spans the row from the gutter to the right edge, across its - /// soft wraps, under the active line, indent guides, selections and text. A - /// marker is painted in a slot at the left of the line numbers, only while - /// they are shown; the gutter reserves the slot while any collection has a + /// 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. diff --git a/crates/base/src/input/mod.rs b/crates/base/src/input/mod.rs index bd7b62eddf..236e167bbc 100644 --- a/crates/base/src/input/mod.rs +++ b/crates/base/src/input/mod.rs @@ -116,6 +116,7 @@ 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; pub use line_decorations::{ GutterMarker, LineDecoration, LineDecorationCollection, LineDecorationProvider, }; diff --git a/crates/base/src/scrollbar.rs b/crates/base/src/scrollbar.rs index 210e4fade4..a80a7540e3 100644 --- a/crates/base/src/scrollbar.rs +++ b/crates/base/src/scrollbar.rs @@ -863,6 +863,7 @@ pub struct Scrollbar { 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. /// @@ -889,6 +890,7 @@ impl Scrollbar { scroll_size: None, viewport_bounds: None, scroll_viewport_size: None, + horizontal_viewport_bounds: None, use_layout_bounds: false, styles: ScrollbarStyles::default(), } @@ -914,6 +916,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. @@ -1008,6 +1017,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, @@ -1440,25 +1464,28 @@ 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, ) }; @@ -1479,29 +1506,29 @@ impl Element for Scrollbar { let bounds = Bounds { origin: if is_vertical { if self.placement.is_left() { - hitbox.origin + viewport.origin } else { point( - hitbox.origin.x + hitbox.size.width - track_width, - hitbox.origin.y, + viewport.origin.x + viewport.size.width - track_width, + viewport.origin.y, ) } } else if self.placement.is_top() { - hitbox.origin + 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 }, @@ -2578,6 +2605,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| { @@ -2620,6 +2664,47 @@ 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 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( diff --git a/crates/component/src/input/editor.rs b/crates/component/src/input/editor.rs index ab84d7a84b..95f06e67ac 100644 --- a/crates/component/src/input/editor.rs +++ b/crates/component/src/input/editor.rs @@ -287,6 +287,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}; diff --git a/crates/component/src/input/input.rs b/crates/component/src/input/input.rs index a03e30f0bb..11ff69c288 100644 --- a/crates/component/src/input/input.rs +++ b/crates/component/src/input/input.rs @@ -643,17 +643,24 @@ impl RenderOnce for Input { sync_focused_input_registry(&state, window, cx); state.ensure_highlighter_factory(crate::highlighter::input_highlighter_factory(), 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() diff --git a/crates/component/src/input/mod.rs b/crates/component/src/input/mod.rs index c9c7de8ef3..0b3a332d57 100644 --- a/crates/component/src/input/mod.rs +++ b/crates/component/src/input/mod.rs @@ -28,7 +28,7 @@ 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, + EditorState, Enter, Escape, FoldRange, GoToDefinition, GutterColumn, GutterDecoration, GutterDecorationCollection, GutterMarker, HighlightStyleResolver, HoverPopoverState, HoverProvider, Indent, IndentInline, InputEdit, InputEditsEvent, InputEvent, InputHighlighter, InputHighlighterFactory, InputState, LineDecoration, LineDecorationCollection, 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..95319613a0 --- /dev/null +++ b/crates/story/src/stories/editor_diff_story.rs @@ -0,0 +1,417 @@ +use std::{ops::Range, rc::Rc}; + +use gpui_kit::component::{ + ActiveTheme, Side, + button::Button, + h_flex, + input::{ + Editor, EditorState, GutterColumn, GutterMarker, LineDecoration, LineDecorationCollection, + LineDecorationProvider, + }, + menu::PopupMenuItem, + scroll::ScrollbarPlacement, + v_flex, +}; +use gpui_kit::{ + App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Pixels, Render, + Styled as _, Subscription, 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() + } +} + +pub struct EditorDiffStory { + original: Entity, + modified: Entity, + mirrored: bool, + markers_before_numbers: bool, + 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." + } + 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.", + ) + .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, + ) + }) + }); + let subscriptions = + [&original, &modified].map(|editor| cx.observe(editor, |_, _, cx| cx.notify())); + Self { + original, + modified, + mirrored: true, + markers_before_numbers: false, + 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]; + } + } + + 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; + 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(); + })), + ) + }, + ) + } + + 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. + 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 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/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/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/component/editor.md b/website/component/editor.md index 32418d9429..9af6a25df4 100644 --- a/website/component/editor.md +++ b/website/component/editor.md @@ -143,14 +143,42 @@ frame and scrollbar stay put. Ordinary mouse-wheel line scrolling does not bounc 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. 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. +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 @@ -371,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. @@ -487,18 +517,19 @@ 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 row from the gutter to the right edge, 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 at the left of the line numbers, so it is shown only -while line numbers are. 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. +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 diff --git a/website/zh-CN/component/editor.md b/website/zh-CN/component/editor.md index 27bcab50ad..6e149a6a0d 100644 --- a/website/zh-CN/component/editor.md +++ b/website/zh-CN/component/editor.md @@ -118,12 +118,30 @@ let editor = cx.new(|cx| { `scroll_bounce(true)` 让超出编辑器高度的代码在触控板或 Magic Mouse 的精细像素滚动到达顶部或底部时越过边缘并弹回,与 [Textarea](./textarea.md#滚动回弹) 相同。行号栏随代码移动,外框和滚动条保持不动;普通鼠标滚轮的按行滚动不触发回弹。 -滚动条默认位于右侧和底部。使用 `scrollbar_placement` 可调整其位置;放在左侧的纵向滚动条位于编辑器左边缘,覆盖在行号之上。与覆盖最后一行的底部滚动条一样,顶部滚动条覆盖在第一行之上,不为自身预留空间。运行时可用 `set_scrollbar_placement` 替换位置。 +滚动条默认位于右侧和底部。使用 `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` 绑定仍然有效。 @@ -302,7 +320,8 @@ Editor 展示页的 **Decorations** 标签演示了两种集合的组合使用 ### 行号槽与概览标尺装饰 需要在文本之外标记整行(例如版本控制 diff 中新增、修改或删除的行)时,使用这两个集合。 -`GutterDecorationCollection` 在行号之前的窄带中绘制标记。 +`GutterDecorationCollection` 在 gutter 外侧边缘、行号和行装饰标记之前的窄带中绘制标记; +可用 `gutter_order` 通过 `GutterColumn::Decorations` 调整其位置。 `OverviewRulerDecorationCollection` 在垂直滚动条轨道上绘制标记,Monaco 将这条轨道称为概览标尺。 要同时在两处显示标记,请分别创建两个集合。 @@ -404,8 +423,9 @@ added.dispose(cx); // 释放集合,使该句柄及其克隆全部失效。 在被询问时从 `cx` 读取颜色,使其跟随主题变化。与其他装饰集合一样,各集合相互独立; 后创建的集合绘制在先创建的集合之上。 -背景从行号槽一直延伸到右边缘,覆盖该行软换行后的全部显示行,位于当前行高亮、缩进参考线、 -选区和文字下方。标记绘制在行号左侧的独立槽位中,因此只在显示行号时出现。只要有集合设置了 +背景横跨整行(包括行号槽),覆盖该行软换行后的全部显示行,位于当前行高亮、缩进参考线、 +选区和文字下方。标记绘制在独立槽位中,只在显示行号时出现。默认顺序下,该槽位位于行号与行号槽外缘之间; +使用 `gutter_order` 可将其移到更靠近文本的位置,与 IntelliJ IDEA 放置标记的方式一致。只要有集合设置了 provider,行号槽就会保留该槽位,标记行滚入或滚出视图时宽度不变。 样式化编辑器的标记尺寸为实际字号的 90%,间距为字号的 30%。图标、预留槽位和垂直居中使用同一尺寸, 因此标记既跟随界面缩放,也跟随编辑器单独设置的 `.text_size(...)` 变化。`DiffAdded`、`DiffRemoved`、 From c39b0dd5b9126319da6f4b85357a00f0bf5dcc85 Mon Sep 17 00:00:00 2001 From: cc-glani Date: Sun, 11 Oct 2026 06:25:01 +0200 Subject: [PATCH 4/8] editor: Clip the text to its own side of the gutter (#3426) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The editor's gutter is painted over the horizontally scrolling text, and its background is what hides the text underneath. That background is not always opaque: a disabled editor paints the editor background at half opacity, and a theme may give `editor.background` or `editor.gutter.background` an alpha. The text then shows through the gutter, under the line numbers. With the gutter on the right (#3417) every line longer than the pane runs under the gutter, so in a side-by-side diff it shows on most rows. With a gutter on the left it shows once the text is scrolled horizontally. This clips what belongs to the text area to its own side of the gutter — glyph backgrounds, indent guides, range decorations, selections and search matches, the hover highlight, document colors, the text and its ghost lines, inline elements, the carets and the inline completion suffix — instead of relying on the gutter's background to cover it. Only the edge facing the gutter moves; the other edges stay those of the current content mask. Line decoration backgrounds and the active line keep spanning the gutter, and the gutter keeps its background. Nothing changes for an editor without line numbers. A side-by-side diff in a dark theme, the left pane with `.gutter_side(Side::Right)`: | Before | After | | ------ | ----- | | before: the text shows through the gutter | after: the text ends at the gutter | - `cargo test -p gpui-base --lib the_text_is_clipped_to_its_side_of_the_gutter`: a decorated text scrolled under the gutter, for a gutter on the left and on the right with either scrollbar placement; it reads what was painted (`painted_quads`, `painted_underlines`) and fails without the clip. - In an editor with `.gutter_side(Side::Right)` whose editor background is not opaque (for example a disabled one), type a line longer than the pane: the line numbers sit on the gutter's background, not over the text. - [x] I have read the [CONTRIBUTING](../CONTRIBUTING.md) document and followed the guidelines. - [x] Reviewed the changes in this PR and confirmed AI generated code (If any) is accurate. - [x] Passed `cargo run` for story tests related to the changes. - [x] Tested macOS, Windows and Linux platforms performance (if the change is platform-specific) --------- Co-authored-by: Jason Lee --- crates/base/src/input/base/element.rs | 439 +++++++++++++++++--------- 1 file changed, 281 insertions(+), 158 deletions(-) diff --git a/crates/base/src/input/base/element.rs b/crates/base/src/input/base/element.rs index 8a3dd26ea1..9448da3c55 100644 --- a/crates/base/src/input/base/element.rs +++ b/crates/base/src/input/base/element.rs @@ -3,7 +3,7 @@ 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::{ @@ -664,6 +664,23 @@ 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 @@ -4236,181 +4253,196 @@ impl Element for TextElement { px(0.) }; - // 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. - let mut offset_y = invisible_top_padding; - for (line, &buffer_line) in prepaint - .last_layout - .lines - .iter() - .zip(prepaint.last_layout.visible_buffer_lines.iter()) - { - let p = point( - origin.x + prepaint.last_layout.text_origin_x + scroll_offset, - origin.y + offset_y, - ); + // The gutter paints over horizontally scrolling text, so the text is + // clipped to its own side of the gutter. A gutter without line numbers + // still holds the fold icons and the margin, so it clips the text too. + let gutter_bounds = editor_gutter_bounds( + input_bounds, + prepaint.last_layout.line_number_width, + prepaint.ghost_lines_height, + editor_paddings, + prepaint.last_layout.gutter_side, + ); + let text_mask = (prepaint.last_layout.line_number_width > 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, - text_align, - Some(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. + let mut offset_y = invisible_top_padding; + for (line, &buffer_line) in prepaint + .last_layout + .lines + .iter() + .zip(prepaint.last_layout.visible_buffer_lines.iter()) + { + let p = point( + origin.x + prepaint.last_layout.text_origin_x + scroll_offset, + origin.y + offset_y, + ); + + line.paint_background( + p, + line_height, + text_align, + Some(prepaint.last_layout.content_width), + window, + cx, + ); - offset_y += line.size(line_height).height; + offset_y += line.size(line_height).height; - // Ghost lines shift every later line down. - if Some(buffer_line) == prepaint.current_row { - offset_y += prepaint.ghost_lines_height; + // Ghost lines shift every later line down. + if Some(buffer_line) == prepaint.current_row { + offset_y += 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 offset_y = invisible_top_padding; - let ghost_lines = &prepaint.ghost_lines; - let has_ghost_lines = !ghost_lines.is_empty(); + // Paint text with inline completion ghost line support + let mut offset_y = invisible_top_padding; + 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 + offset_y; - let p = point( - origin.x + prepaint.last_layout.text_origin_x + (scroll_offset), - line_y, - ); + 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 + offset_y; + let p = point( + origin.x + prepaint.last_layout.text_origin_x + (scroll_offset), + line_y, + ); - // Paint the actual line - _ = line.paint( - p, - line_height, - text_align, - Some(prepaint.last_layout.content_width), - window, - cx, - ); - offset_y += line.size(line_height).height; + // Paint the actual line + _ = line.paint( + p, + line_height, + text_align, + Some(prepaint.last_layout.content_width), + window, + cx, + ); + offset_y += line.size(line_height).height; - 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; + // 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; - for ghost_line in ghost_lines { - let ghost_p = point(ghost_x, origin.y + offset_y); + for ghost_line in ghost_lines { + let ghost_p = point(ghost_x, origin.y + offset_y); - // 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(prepaint.last_layout.text_width, line_height), + ); + window.paint_quad(fill(ghost_bounds, editor_background)); - // Paint ghost line text - _ = ghost_line.paint( - ghost_p, - line_height, - text_align, - Some(prepaint.last_layout.content_width), - window, - cx, - ); - offset_y += line_height; + // Paint ghost line text + _ = ghost_line.paint( + ghost_p, + line_height, + text_align, + Some(prepaint.last_layout.content_width), + window, + cx, + ); + offset_y += line_height; + } } } - } - 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 let mut offset_y = px(0.); if let Some(line_numbers) = prepaint.line_numbers.as_ref() { offset_y += invisible_top_padding; - // 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, - prepaint.last_layout.gutter_side, - ); window.paint_quad(fill(gutter_bounds, gutter_bg)); // Repaint line decoration backgrounds over the gutter background. for &(y, height, color) in &line_backgrounds { @@ -4482,26 +4514,32 @@ impl Element for TextElement { } // Paint inline completion first line suffix (after cursor on same line) - if focused { - if let Some(first_line) = &prepaint.ghost_first_line { - let active_cursor = prepaint - .cursor_infos_with_scroll() - .into_iter() - .find(|info| info.is_active); - if let (Some(cursor_info), Some(cursor_row_y)) = (active_cursor, cursor_row_y) { - let cursor_bounds = cursor_info.bounds; - let first_line_x = cursor_bounds.origin.x + cursor_bounds.size.width; - let p = point(first_line_x, cursor_row_y); - - // Paint background to cover any existing text - let bg_bounds = Bounds::new(p, size(first_line.width + px(4.), line_height)); - window.paint_quad(fill(bg_bounds, editor_background)); - - // Paint first line completion text - _ = first_line.paint(p, line_height, text_align, None, window, cx); + // + // It paints after the gutter and the fold icons so its background covers + // the text it overlaps, and so it stays in its own mask. + window.with_content_mask(text_mask, |window| { + if focused { + if let Some(first_line) = &prepaint.ghost_first_line { + let active_cursor = prepaint + .cursor_infos_with_scroll() + .into_iter() + .find(|info| info.is_active); + if let (Some(cursor_info), Some(cursor_row_y)) = (active_cursor, cursor_row_y) { + let cursor_bounds = cursor_info.bounds; + let first_line_x = cursor_bounds.origin.x + cursor_bounds.size.width; + let p = point(first_line_x, cursor_row_y); + + // Paint background to cover any existing text + let bg_bounds = + Bounds::new(p, size(first_line.width + px(4.), line_height)); + window.paint_quad(fill(bg_bounds, editor_background)); + + // Paint first line completion text + _ = first_line.paint(p, line_height, text_align, None, window, cx); + } } } - } + }); self.paint_mouse_listeners(&prepaint.hitbox, window, cx); } @@ -6843,6 +6881,91 @@ mod tests { }); } + #[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); From 21284df2ab75dbc1ec0e1dad345849046bf999d5 Mon Sep 17 00:00:00 2001 From: cc-glani Date: Wed, 14 Oct 2026 07:33:41 +0200 Subject: [PATCH 5/8] editor: Expose read-only access to the display map (#3465) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Applications building synchronized editors, minimaps, or custom coordinate-based views need access to the editor's complete text projection, including lines outside the viewport. `InputBaseState::display_map()` now returns a shared reference to the editor-owned `DisplayMap`, exposing its existing public buffer/display coordinate and row queries while the state owns all updates. `DisplayMap::version()` changes on edits, rewrapping, and fold changes. Consumers can compare versions on the same map to invalidate cached queries without adding an `InputEvent` variant. Queries stay on `DisplayMap`; the four proposed state-level forwarding methods are omitted. The map reflects the whole prepared buffer using the latest prepared layout parameters. It excludes inline completion ghost lines: multi-line inline completion shifts painted rows without changing the text map or its version. Use `row_bounds` for the actual geometry of visible lines. Base and Component documentation explain these semantics in English and Chinese. Both types are already re-exported through `gpui_kit::base::input` and `gpui_kit::component::input`. - `InputBaseState::display_map(&self) -> &DisplayMap` — read-only access to the state-owned map for row queries and buffer/display coordinate conversions. - `DisplayMap::version(&self) -> usize` — an equality-comparable invalidation version for the same map; it may wrap. ```sh cargo test -p gpui-base --lib the_display_row_map_is_what_the_layout_draws cargo test -p gpui-base --lib rows_below_a_multiline_inline_completion_are_bounded_where_painted cargo fmt -p gpui-base --check ``` All three commands passed locally, along with `git diff --check`. The mapping test exercises the public accessor, coordinate round trips, wrapped and folded lines, offscreen queries, and version changes on rewrapping, folding, and edits while staying stable on scroll. The inline completion test verifies that ghost lines move painted row bounds while the text map and its version remain unchanged. AI-assisted: follow-up API, documentation, and test changes made with Codex. --------- Co-authored-by: Jason Lee --- crates/base/src/input/base/element.rs | 141 ++++++++++++++++++ crates/base/src/input/base/state.rs | 8 + .../input/editor/display_map/display_map.rs | 21 ++- .../src/input/editor/display_map/fold_map.rs | 25 +++- .../input/editor/display_map/text_wrapper.rs | 10 ++ website/base/primitives/editor.md | 10 ++ website/component/editor.md | 33 ++++ website/zh-CN/base/primitives/editor.md | 8 + website/zh-CN/component/editor.md | 27 ++++ 9 files changed, 281 insertions(+), 2 deletions(-) diff --git a/crates/base/src/input/base/element.rs b/crates/base/src/input/base/element.rs index 9448da3c55..3f9968a64a 100644 --- a/crates/base/src/input/base/element.rs +++ b/crates/base/src/input/base/element.rs @@ -5288,6 +5288,7 @@ mod tests { 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| { @@ -5304,6 +5305,10 @@ mod tests { 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(), @@ -6314,6 +6319,142 @@ mod tests { }); } + #[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, + 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); + }); + } + #[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); diff --git a/crates/base/src/input/base/state.rs b/crates/base/src/input/base/state.rs index b169418746..590d8b9987 100644 --- a/crates/base/src/input/base/state.rs +++ b/crates/base/src/input/base/state.rs @@ -793,6 +793,14 @@ 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. 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 } 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 5617e03c83..2d097ad6eb 100644 --- a/crates/base/src/input/editor/display_map/display_map.rs +++ b/crates/base/src/input/editor/display_map/display_map.rs @@ -25,7 +25,12 @@ use crate::input::rope_ext::RopeExt as _; /// 1. Buffer → Wrap (soft-wrapping) /// 2. Wrap → Display (folding) /// -/// 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, @@ -66,6 +71,20 @@ impl DisplayMap { self.wrap_map.wrap_pos_to_buffer_pos(wrap_pos) } + /// A number that changes whenever a buffer line may have taken different + /// display rows: an edit, a rewrap or a change of folds. + /// + /// 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. + #[inline] + pub fn version(&self) -> usize { + self.wrap_map + .wrapper() + .version() + .wrapping_add(self.fold_map.version()) + } + /// Get total number of visible display rows #[inline] pub fn display_row_count(&self) -> usize { 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/text_wrapper.rs b/crates/base/src/input/editor/display_map/text_wrapper.rs index 8a97d41936..e0da6d4644 100644 --- a/crates/base/src/input/editor/display_map/text_wrapper.rs +++ b/crates/base/src/input/editor/display_map/text_wrapper.rs @@ -356,6 +356,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, _initialized: bool, } @@ -372,6 +374,7 @@ impl TextWrapper { lines: SumTree::new(&()), inline_metrics: Rc::from([]), width_measurements: Rc::default(), + version: 0, _initialized: false, } } @@ -399,6 +402,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 { @@ -827,6 +836,7 @@ impl TextWrapper { } self.text = changed_text.clone(); + self.version = self.version.wrapping_add(1); } /// Update the text wrapper and recalculate the wrapped lines. diff --git a/website/base/primitives/editor.md b/website/base/primitives/editor.md index 92ded0ebe7..c8eb2e5602 100644 --- a/website/base/primitives/editor.md +++ b/website/base/primitives/editor.md @@ -130,6 +130,16 @@ 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/component/editor.md b/website/component/editor.md index 9af6a25df4..e8d9d5d666 100644 --- a/website/component/editor.md +++ b/website/component/editor.md @@ -536,6 +536,39 @@ where it is painted: below a multi-line inline completion, rows move down with t 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::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, and +fold 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. + ## Value and events ```rust diff --git a/website/zh-CN/base/primitives/editor.md b/website/zh-CN/base/primitives/editor.md index d1d54531c6..45b27889a8 100644 --- a/website/zh-CN/base/primitives/editor.md +++ b/website/zh-CN/base/primitives/editor.md @@ -92,6 +92,14 @@ let style = InputEditorStyle::default() 通过 `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/component/editor.md b/website/zh-CN/component/editor.md index 6e149a6a0d..13e747579e 100644 --- a/website/zh-CN/component/editor.md +++ b/website/zh-CN/component/editor.md @@ -437,6 +437,33 @@ info 颜色;`GutterMarker::Custom { icon, color }` 按原样绘制给定的图 文字一起下移。该行尚未布局时返回 `None`。 Editor 展示页的 **Decorations** 标签用 provider 标记了最后三行。 +`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`); +缓冲区位置与显示位置之间的转换使用映射的坐标转换方法。 + ## 值与事件 ```rust From 5d250a80d904965a6add64208d792dcec2396bdc Mon Sep 17 00:00:00 2001 From: cc-glani Date: Thu, 15 Oct 2026 05:36:26 +0200 Subject: [PATCH 6/8] editor: Add spacer rows to the display map (#3466) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two editors shown side by side stay level only while no line wraps: with soft wrap on, the same paragraph takes more rows on one side than on the other, and every pair below it drifts. This adds **spacer rows** to the display map — blank rows above or below a buffer line, with no line number, no caret and no decoration, as Zed's side-by-side diff has them (`Block::Spacer`) — and a provider to say where they go. Builds on #3465 (`display_map() -> &DisplayMap`, a public `DisplayMap::version()`), now in `next`; the spacer rows are read through that map. They are a layer of the display map above folding, its inverse, so every row keeps one line height and the scroll height, `scroll_to` and `row_bounds` count them. Selections, search matches, document colours, range decorations, line decoration bands and markers, fold icons, indent guides and inline tokens pass them by; the caret steps over them; a click on one lands on the row of text beside it; a block selection skips them. The text, the glyph backgrounds, the line numbers and the active line are now painted at `row_extents()`, the one place spacers and ghost lines are accounted for, instead of each keeping a running sum — the same tops when there are no spacers. Ghost lines of an inline completion stand right below the cursor row's text, before the spacers below it, and the spacer backgrounds move down with them. On that public `DisplayMap`, 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)` and `display_pos_to_buffer_pos` read a spacer row as the line it stands beside, and `is_spacer_row(row)` tells the two apart. `version()` moves when the spacers change, so a cache of rows keyed on it stays valid; an answer equal to the spacers already shown leaves it as it was. The editor asks the provider again by the rows alone (an edit, a rewrap, a fold, or `refresh_spacers`), so an answer never asks anew, and refreshing whenever the other side's version changes settles. The Editor Diff story gains a "Wrap long lines" option that pads both sides level, and `examples/editor_spacers` shows two versions of a prose text padded level, a paragraph only one has standing beside a filled block. This changes Base: the display map and the editor's layout live there. The Editor Diff story with Options › Wrap long lines: line 38 wraps to three rows on the left and seven on the right. | Soft wrap alone | With spacer rows | | --------------- | ---------------- | | soft wrap alone: below line 38 the right side
runs four rows lower | with spacer rows: every line starts level on
both sides | `examples/editor_spacers`, at 900 and at 640 pixels wide: | 900 px | 640 px | | ------ | ------ | | the example at 900 pixels: paragraphs padded
level | the example at 640 pixels: rewrapped and
still level | `gpui_kit::component::input`) - `Spacer::below(line: usize, rows: usize) -> Spacer` / `Spacer::above(line: usize, rows: usize) -> Spacer` — blank rows below or above a zero-based buffer line. - `Spacer::with_background(self, color: Hsla) -> Spacer` — fill the rows, gutter included; `Spacer::line`, `rows`, `is_above`, `background` read them back. - `trait SpacerProvider { fn spacers(&self, lines: Range, cx: &App) -> Vec; }` — asked for every line when the rows move and on `refresh_spacers`. - `InputBaseState::set_spacer_provider(&mut self, provider: Option>, cx: &mut Context)`. - `InputBaseState::refresh_spacers(&mut self, cx: &mut Context)` — ask again at the next layout, when something the answer depends on changed elsewhere (another editor's rows). - `DisplayMap::is_spacer_row(&self, row: usize) -> bool` — on the map `InputBaseState::display_map()` returns. - `cargo test -p gpui-base --lib spacer` (`spacers_are_asked_for_when_the_rows_move` also covers the version) and the four tests named for the caret, bands, ranges and gutters (`the_caret_and_a_click_never_stand_on_a_spacer_row`, `bands_markers_and_fold_icons_stand_on_text_rows_only`, `ranges_are_laid_out_on_text_rows_only`, `spacers_beside_a_right_gutter_and_a_left_scroll_bar`), each with soft wrap on and off; `cargo test -p gpui-component-story --lib wrapped_sides_are_padded_level`. - `cargo run`, Editor Diff, Options › Wrap long lines: narrow the window; every pair of lines starts level, the line numbers only beside text. - `cargo run -p example-editor-spacers`. - [x] I have read the [CONTRIBUTING](../CONTRIBUTING.md) document and followed the guidelines. - [x] Reviewed the changes in this PR and confirmed AI generated code (If any) is accurate. - [ ] Passed `cargo run` for story tests related to the changes. - [ ] Tested macOS, Windows and Linux platforms performance (if the change is platform-specific) --------- Co-authored-by: Jason Lee --- Cargo.lock | 7 + Cargo.toml | 1 + crates/base/src/input/base/element.rs | 623 ++++++++++++++++-- crates/base/src/input/base/kind.rs | 8 + crates/base/src/input/base/layout.rs | 22 +- crates/base/src/input/base/movement.rs | 10 +- crates/base/src/input/base/state.rs | 39 +- .../input/editor/display_map/display_map.rs | 200 +++++- .../base/src/input/editor/display_map/mod.rs | 4 +- .../input/editor/display_map/spacer_map.rs | 266 ++++++++ .../input/editor/display_map/text_wrapper.rs | 2 + crates/base/src/input/editor/indent.rs | 7 +- crates/base/src/input/editor/mod.rs | 4 + crates/base/src/input/editor/spacers.rs | 107 +++ crates/base/src/input/mod.rs | 3 + crates/component/src/input/mod.rs | 6 +- crates/story/src/stories/editor_diff_story.rs | 161 ++++- examples/README.md | 1 + examples/editor_spacers/Cargo.toml | 12 + examples/editor_spacers/src/main.rs | 303 +++++++++ website/base/primitives/editor.md | 4 + website/component/editor.md | 72 +- website/zh-CN/base/primitives/editor.md | 3 + website/zh-CN/component/editor.md | 61 +- 24 files changed, 1830 insertions(+), 96 deletions(-) create mode 100644 crates/base/src/input/editor/display_map/spacer_map.rs create mode 100644 crates/base/src/input/editor/spacers.rs create mode 100644 examples/editor_spacers/Cargo.toml create mode 100644 examples/editor_spacers/src/main.rs diff --git a/Cargo.lock b/Cargo.lock index 060df60505..ad0aa4feee 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2873,6 +2873,13 @@ dependencies = [ "tree-sitter-navi", ] +[[package]] +name = "example-editor-spacers" +version = "0.9.1" +dependencies = [ + "gpui-kit", +] + [[package]] name = "example-html" version = "0.9.1" diff --git a/Cargo.toml b/Cargo.toml index 06a8cd8ad4..c821d2785e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,6 +17,7 @@ members = [ "examples/hello_world", "examples/input", "examples/editor", + "examples/editor_spacers", "examples/syntect", "examples/tig", "examples/brush", diff --git a/crates/base/src/input/base/element.rs b/crates/base/src/input/base/element.rs index 3f9968a64a..ec507d98dc 100644 --- a/crates/base/src/input/base/element.rs +++ b/crates/base/src/input/base/element.rs @@ -1316,11 +1316,14 @@ impl TextElement { 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; let alignment = last_layout.alignment_offset(line.longest_width); for (row, shaped) in line.wrapped_lines.iter().enumerate() { @@ -1351,6 +1354,7 @@ impl TextElement { offset = end; y += last_layout.line_height; } + y += spacer_below; } (!corners.is_empty()).then_some(corners) } @@ -1627,12 +1631,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); - // y of the top of the first visible buffer line (in content space). + // y of the top of the first visible buffer line (in content space), + // above the spacers standing above it. let visible_top = match state .display_map .buffer_line_to_display_row_range(start_line) { - Some(range) => line_height * range.start, + Some(range) => { + let (above, _) = state.display_map.spacer_rows_beside(start_line); + line_height * (range.start - above) + } None => line_height * first_display, }; @@ -1997,11 +2005,14 @@ impl TextElement { let mut infos = Vec::with_capacity(last_layout.visible_buffer_lines.len()); 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 { @@ -2012,7 +2023,7 @@ impl TextElement { }); } - offset_y += line.wrapped_lines.len() * last_layout.line_height; + offset_y += line.wrapped_lines.len() * last_layout.line_height + spacer_below; } infos @@ -2128,11 +2139,14 @@ impl TextElement { // rows it wraps to, and where its text ends. let mut folded = Vec::new(); 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; let rows = line.wrapped_lines.len(); if state.display_map.is_folded_at(buffer_line) && let Some(last) = line.wrapped_lines.last() @@ -2148,6 +2162,7 @@ impl TextElement { { offset_y += height; } + offset_y += spacer_below; } ( state.fold_background, @@ -2201,6 +2216,33 @@ 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 @@ -2860,6 +2902,8 @@ impl TextElement { let mut placements = Vec::new(); let mut y = layout.visible_top; for (ix, &row) in layout.visible_buffer_lines.iter().enumerate() { + 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(); @@ -2874,7 +2918,7 @@ impl TextElement { )); } } - y += layout.lines[ix].size(layout.line_height).height; + y += layout.lines[ix].size(layout.line_height).height + spacer_below; } let mut out = Vec::new(); let mut token_bounds = std::collections::HashMap::new(); @@ -3235,6 +3279,9 @@ pub(super) struct PrepaintState { 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, @@ -3569,10 +3616,32 @@ impl Element for TextElement { window, cx, ); + // Spacers move every row below them, so they are placed once the text + // is wrapped to this width and before anything is laid out by row. + self.ask_for_spacers(cx); let state = self.state.read(cx); let (visible_range, visible_buffer_lines, visible_top) = self.calculate_visible_range(&state, line_height, bounds.size.height); + let spacer_rows = if state.display_map.spacer_row_count() > 0 { + visible_buffer_lines + .iter() + .map(|&line| state.display_map.spacer_rows_beside(line)) + .collect() + } else { + Vec::new() + }; + let mut spacer_backgrounds: Vec<(Pixels, Pixels, Hsla)> = + match (visible_buffer_lines.first(), visible_buffer_lines.last()) { + (Some(&first), Some(&last)) => state + .display_map + .spacer_backgrounds(first..last + 1) + .map(|(rows, color)| { + (line_height * rows.start, line_height * rows.len(), color) + }) + .collect(), + _ => Vec::new(), + }; let visible_start_offset = state.text.line_start_offset(visible_range.start); let visible_end_offset = state .text @@ -3622,6 +3691,7 @@ impl Element for TextElement { gutter_marker_width: Self::gutter_marker_width(state, window), gutter_decorations_width: Self::gutter_decorations_width(state), ghost_lines: None, + spacer_rows, gutter_side, gutter_order: state.gutter_order, text_origin_x, @@ -3790,7 +3860,8 @@ impl Element for TextElement { let ghost_line_count = ghost_lines.len(); let ghost_lines_height = ghost_line_count as f32 * 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_height = empty_bottom_height( state.is_code_editor(), state.scroll_beyond_last_line, @@ -3874,6 +3945,22 @@ impl Element for TextElement { last_layout.ghost_lines = current_row .filter(|_| ghost_line_count > 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. + if let Some(ghost_top) = last_layout.ghost_lines.and_then(|(row, _)| { + let rows = self + .state + .read(cx) + .display_map + .buffer_line_to_display_row_range(row)?; + Some(line_height * rows.end) + }) { + for (top, _, _) in &mut spacer_backgrounds { + if *top >= ghost_top { + *top += ghost_lines_height; + } + } + } // Completion/code-action menus position at the active caret. last_layout.cursor_bounds = cursor_infos .iter() @@ -4126,6 +4213,7 @@ impl Element for TextElement { fold_icon_layout, folded_lines, line_decoration_layout, + spacer_backgrounds, ghost_first_line, ghost_lines, ghost_lines_height, @@ -4179,7 +4267,6 @@ impl Element for TextElement { let line_height = window.line_height(); let origin = bounds.origin; - let invisible_top_padding = prepaint.last_layout.visible_top; let active_line_color = editor_style .editor_active_line .map(|color| if disabled { color.opacity(0.5) } else { color }); @@ -4192,6 +4279,7 @@ impl Element for TextElement { .line_decoration_layout .backgrounds .iter() + .chain(&prepaint.spacer_backgrounds) .map(|&(top, height, color)| { ( origin.y + top, @@ -4217,17 +4305,15 @@ impl Element for TextElement { } // Paint active line - let mut offset_y = px(0.); if let Some(line_numbers) = prepaint.line_numbers.as_ref() { - offset_y += invisible_top_padding; - - // Each item is the normal lines. - for (lines, &buffer_line) in line_numbers + // Each item is the normal lines, painted where its row is laid out. + for ((lines, &buffer_line), (top, _)) in line_numbers .iter() .zip(prepaint.last_layout.visible_buffer_lines.iter()) + .zip(prepaint.last_layout.row_extents()) { let is_active = prepaint.current_row == Some(buffer_line); - let p = point(input_bounds.origin.x, origin.y + offset_y); + let p = point(input_bounds.origin.x, origin.y + top); let height = line_height * lines.len() as f32; // Paint the current line background if is_active { @@ -4238,7 +4324,6 @@ impl Element for TextElement { )); } } - offset_y += height; } } @@ -4277,16 +4362,18 @@ impl Element for TextElement { // 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. - let mut offset_y = invisible_top_padding; - for (line, &buffer_line) in prepaint + // + // 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.visible_buffer_lines.iter()) + .zip(prepaint.last_layout.row_extents()) { let p = point( origin.x + prepaint.last_layout.text_origin_x + scroll_offset, - origin.y + offset_y, + origin.y + top, ); line.paint_background( @@ -4297,13 +4384,6 @@ impl Element for TextElement { window, cx, ); - - offset_y += line.size(line_height).height; - - // Ghost lines shift every later line down. - if Some(buffer_line) == prepaint.current_row { - offset_y += prepaint.ghost_lines_height; - } } // Paint indent guides @@ -4350,21 +4430,21 @@ impl Element for TextElement { } // Paint text with inline completion ghost line support - let mut offset_y = invisible_top_padding; 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; - for (line, &buffer_line) in prepaint + 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 + offset_y; + let line_y = origin.y + top; let p = point( origin.x + prepaint.last_layout.text_origin_x + (scroll_offset), line_y, @@ -4379,8 +4459,6 @@ impl Element for TextElement { window, cx, ); - offset_y += line.size(line_height).height; - if Some(row) == prepaint.current_row { cursor_row_y = Some(line_y); } @@ -4388,9 +4466,10 @@ impl Element for TextElement { // 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; for ghost_line in ghost_lines { - let ghost_p = point(ghost_x, origin.y + offset_y); + let ghost_p = point(ghost_x, ghost_y); // Paint semi-transparent background for ghost line let ghost_bounds = Bounds::new( @@ -4408,7 +4487,7 @@ impl Element for TextElement { window, cx, ); - offset_y += line_height; + ghost_y += line_height; } } } @@ -4434,10 +4513,7 @@ impl Element for TextElement { }); // Paint line numbers - let mut offset_y = px(0.); if let Some(line_numbers) = prepaint.line_numbers.as_ref() { - offset_y += invisible_top_padding; - // 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 @@ -4456,12 +4532,14 @@ impl Element for TextElement { } let folding = self.state.read(cx).mode.is_folding(); - // Each item is the normal lines. - for (lines, &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 ((lines, &buffer_line), (top, _)) in line_numbers .iter() .zip(prepaint.last_layout.visible_buffer_lines.iter()) + .zip(prepaint.last_layout.row_extents()) { - let y = origin.y + offset_y; + let y = origin.y + top; let is_active = prepaint.current_row == Some(buffer_line); let height = line_height * lines.len() as f32; @@ -4482,12 +4560,6 @@ impl Element for TextElement { let x = line_number_x(&prepaint.last_layout, folding, line.width); let p = point(input_bounds.origin.x + x, y); _ = line.paint(p, line_height, TextAlign::Left, None, window, cx); - offset_y += line_height; - } - - // Add ghost line height after cursor row for line numbers alignment - if !prepaint.ghost_lines.is_empty() && prepaint.current_row == Some(buffer_line) { - offset_y += prepaint.ghost_lines_height; } } } @@ -4785,7 +4857,7 @@ mod tests { use crate::input::{ EditorMode, EditorState, FoldPlaceholderRenderer, FoldRange, GutterDecoration, GutterDecorationCollection, OverviewRulerDecoration, OverviewRulerDecorationCollection, - RangeDecoration, Redo, Undo, + Position, RangeDecoration, Redo, Undo, }; use crate::{ScrollbarMode, ScrollbarStyles, ScrollbarTheme, Theme}; use gpui::{ @@ -6455,6 +6527,463 @@ mod tests { }); } + /// 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(); + ((y - state.last_bounds.unwrap().origin.y) / 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 unscrolled, and painted scrolled. + let state = editor.read(cx); + let caret = state.last_layout.as_ref().unwrap().cursor_bounds.unwrap(); + let shown = caret.center() + point(px(0.), state.scroll_offset().y); + 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 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 editor_line_number_gutter_resizes_with_document_lines(cx: &mut TestAppContext) { let (editor, window) = decoration_editor(cx, &"x\n".repeat(8), false); diff --git a/crates/base/src/input/base/kind.rs b/crates/base/src/input/base/kind.rs index 17298ce699..1b7b728cdb 100644 --- a/crates/base/src/input/base/kind.rs +++ b/crates/base/src/input/base/kind.rs @@ -29,6 +29,7 @@ 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, LineDecoration, OverviewRulerDecoration, RangeDecoration, SyntaxContext, TextDecoration, @@ -126,6 +127,11 @@ pub trait InputExtras: Default + 'static { 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, @@ -396,6 +402,7 @@ pub struct EditorExtras { 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, @@ -413,6 +420,7 @@ impl Default for EditorExtras { 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 48b0579af1..e4d51f6b44 100644 --- a/crates/base/src/input/base/layout.rs +++ b/crates/base/src/input/base/layout.rs @@ -79,6 +79,9 @@ pub(super) struct LastLayout { 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. @@ -104,16 +107,30 @@ 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. + /// 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) - .map(move |(line, &row)| { + .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; @@ -122,6 +139,7 @@ impl LastLayout { { top += ghost_height; } + top += below; extent }) } 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 590d8b9987..6ad7391866 100644 --- a/crates/base/src/input/base/state.rs +++ b/crates/base/src/input/base/state.rs @@ -444,6 +444,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, @@ -798,9 +801,10 @@ impl InputBaseState { /// 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. They do - /// not include inline completion ghost lines; use [`Self::row_bounds`] for - /// the actual painted geometry of a visible buffer line. + /// 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 } @@ -997,6 +1001,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, @@ -1283,6 +1288,8 @@ impl InputBaseState { 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 prev_lines_offset = last_layout.visible_line_byte_offsets[vi]; @@ -1295,7 +1302,7 @@ impl InputBaseState { return (vi, sub_line_index, Some(adjusted_pos)); } - y_offset += line.size(line_height).height; + y_offset += line.size(line_height).height + spacer_below; } (0, 0, None) } @@ -2778,6 +2785,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); @@ -3806,10 +3816,19 @@ impl InputBaseState { .enumerate() { let line_start_offset = last_layout.visible_line_byte_offsets[vi]; + let (spacer_above, spacer_below) = last_layout.spacers(vi); + y_offset += spacer_above; + let height = line_layout.size(line_height).height; // 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 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 + 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() { @@ -3836,7 +3855,7 @@ impl InputBaseState { return (self.resolve_index(line_start_offset), false, 0); } - y_offset += line_layout.size(line_height).height; + y_offset += height + spacer_below; last_line_pos = Some(pos); } @@ -5167,6 +5186,8 @@ impl EntityInputHandler for InputBaseState { break; } + 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]; @@ -5186,7 +5207,7 @@ impl EntityInputHandler for InputBaseState { end_origin = Some(p + point(px(0.), y_offset)); } - y_offset += line.size(line_height).height; + y_offset += line.size(line_height).height + spacer_below; } let start_origin = start_origin.or_else(|| { @@ -5222,12 +5243,14 @@ impl EntityInputHandler for InputBaseState { 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_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))); } - line_top += line.size(last_layout.line_height).height; + line_top += line.size(last_layout.line_height).height + spacer_below; } None 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 2d097ad6eb..a80f29d20c 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,19 +11,22 @@ 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) /// /// [`crate::input::InputBaseState::display_map`] exposes the editor-owned map /// through a shared reference for application coordinate queries. Text edits, @@ -34,6 +37,15 @@ use crate::input::rope_ext::RopeExt as _; 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 { @@ -41,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, } } @@ -51,20 +67,28 @@ 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); @@ -72,32 +96,45 @@ impl DisplayMap { } /// A number that changes whenever a buffer line may have taken different - /// display rows: an edit, a rewrap or a change of folds. + /// 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. + /// 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 + /// 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) @@ -105,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); @@ -142,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); @@ -305,6 +451,7 @@ impl DisplayMap { self.fold_map .mark_dirty_with_wrap_count(self.wrap_map.wrap_row_count()); } + self.project_spacers(); } // ==================== Wrap Display Point Operations ==================== @@ -351,25 +498,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/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 e0da6d4644..42c4624d1f 100644 --- a/crates/base/src/input/editor/display_map/text_wrapper.rs +++ b/crates/base/src/input/editor/display_map/text_wrapper.rs @@ -1839,6 +1839,7 @@ mod tests { 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.), @@ -2154,6 +2155,7 @@ mod tests { 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.), diff --git a/crates/base/src/input/editor/indent.rs b/crates/base/src/input/editor/indent.rs index 6ef1561b53..d29db8221c 100644 --- a/crates/base/src/input/editor/indent.rs +++ b/crates/base/src/input/editor/indent.rs @@ -126,11 +126,14 @@ impl TextElement { 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 (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 { @@ -157,7 +160,7 @@ impl TextElement { current_indents = last_indents.clone(); } - offset_y += line_layout.wrapped_lines.len() * line_height; + offset_y += line_layout.wrapped_lines.len() * line_height + spacer_below; last_indents = current_indents; } diff --git a/crates/base/src/input/editor/mod.rs b/crates/base/src/input/editor/mod.rs index cf27a98bb4..a52c62e9d0 100644 --- a/crates/base/src/input/editor/mod.rs +++ b/crates/base/src/input/editor/mod.rs @@ -283,6 +283,10 @@ impl crate::input::InputExtras for super::EditorExtras { 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 236e167bbc..13e4c5c726 100644 --- a/crates/base/src/input/mod.rs +++ b/crates/base/src/input/mod.rs @@ -72,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"] @@ -136,5 +138,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/component/src/input/mod.rs b/crates/component/src/input/mod.rs index 0b3a332d57..8d86e7218a 100644 --- a/crates/component/src/input/mod.rs +++ b/crates/component/src/input/mod.rs @@ -39,9 +39,9 @@ pub use gpui_base::input::{ 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, + 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}; #[doc(hidden)] diff --git a/crates/story/src/stories/editor_diff_story.rs b/crates/story/src/stories/editor_diff_story.rs index 95319613a0..747fb29130 100644 --- a/crates/story/src/stories/editor_diff_story.rs +++ b/crates/story/src/stories/editor_diff_story.rs @@ -6,7 +6,7 @@ use gpui_kit::component::{ h_flex, input::{ Editor, EditorState, GutterColumn, GutterMarker, LineDecoration, LineDecorationCollection, - LineDecorationProvider, + LineDecorationProvider, Spacer, SpacerProvider, }, menu::PopupMenuItem, scroll::ScrollbarPlacement, @@ -14,7 +14,7 @@ use gpui_kit::component::{ }; use gpui_kit::{ App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Pixels, Render, - Styled as _, Subscription, Window, div, px, + Styled as _, Subscription, WeakEntity, Window, div, px, }; use crate::story_toolbar_group; @@ -46,11 +46,45 @@ impl LineDecorationProvider for ChangedLines { } } +/// 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, @@ -61,7 +95,7 @@ impl super::Story for EditorDiffStory { "Editor Diff" } fn description() -> &'static str { - "Compare two source versions with ordinary or center-facing gutters." + "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)) @@ -74,7 +108,8 @@ impl EditorDiffStory { .replace("progress: 72.", "progress: 84.") .replace( "Everything is moving on schedule.", - "One milestone needs attention.", + "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( @@ -112,6 +147,13 @@ impl EditorDiffStory { ) }) }); + 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 { @@ -119,6 +161,8 @@ impl EditorDiffStory { modified, mirrored: true, markers_before_numbers: false, + wrap: false, + rows_versions: [0; 2], scroll_y: [px(0.); 2], _decorations: decorations, _subscriptions: subscriptions.into(), @@ -155,6 +199,29 @@ impl EditorDiffStory { } } + /// 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| { @@ -175,6 +242,7 @@ impl EditorDiffStory { 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, _| { @@ -223,6 +291,13 @@ impl EditorDiffStory { 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); + })), + ) }, ) } @@ -262,6 +337,8 @@ 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() @@ -289,6 +366,82 @@ mod tests { 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); diff --git a/examples/README.md b/examples/README.md index 22927598a4..de5beace92 100644 --- a/examples/README.md +++ b/examples/README.md @@ -9,6 +9,7 @@ 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 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_spacers/Cargo.toml b/examples/editor_spacers/Cargo.toml new file mode 100644 index 0000000000..15bc5c6264 --- /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.9.1" +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/website/base/primitives/editor.md b/website/base/primitives/editor.md index c8eb2e5602..39ea4ff4da 100644 --- a/website/base/primitives/editor.md +++ b/website/base/primitives/editor.md @@ -113,6 +113,10 @@ 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: diff --git a/website/component/editor.md b/website/component/editor.md index e8d9d5d666..13367234ff 100644 --- a/website/component/editor.md +++ b/website/component/editor.md @@ -556,8 +556,8 @@ 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, and -fold changes. Compare versions on the same map to invalidate cached queries; +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 @@ -569,6 +569,74 @@ 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. + ## Value and events ```rust diff --git a/website/zh-CN/base/primitives/editor.md b/website/zh-CN/base/primitives/editor.md index 45b27889a8..b12a6ab94c 100644 --- a/website/zh-CN/base/primitives/editor.md +++ b/website/zh-CN/base/primitives/editor.md @@ -78,6 +78,9 @@ Monaco 将这条轨道称为概览标尺。这两个集合会保留表示行边 询问整行背景和行号槽标记。背景由 Base 直接绘制;标记只通过 `InputEditorStyle::gutter_marker_renderer()` 绘制,样式化编辑器会提供该渲染器。参见[行装饰](../../component/editor.md#行装饰)。 +`set_spacer_provider` 挂载一个 `SpacerProvider`,每当行发生移动时,编辑器都会向它询问需要放在各行上方或下方的空白行。 +这些行由 Base 负责布局,并绘制其可选的背景色。参见[填充行](../../component/editor.md#填充行)。 + 直接使用 Base 时,应用通过 builder 同时提供渲染器和布局尺寸: ```rust diff --git a/website/zh-CN/component/editor.md b/website/zh-CN/component/editor.md index 13e747579e..00754f748e 100644 --- a/website/zh-CN/component/editor.md +++ b/website/zh-CN/component/editor.md @@ -455,7 +455,7 @@ let version = map.version(); ``` 映射覆盖整个已准备的文本,包括视口外的行。软换行使用最近准备的布局参数;文本尚未准备时, -映射没有显示行。编辑、重新换行或折叠变化会改变 `map.version()`。比较同一映射的版本可以判断 +映射没有显示行。编辑、重新换行、折叠或填充行变化会改变 `map.version()`。比较同一映射的版本可以判断 何时需要重新查询;滚动不会改变版本。 映射不包含内联补全的额外行。显示行序号乘以行高表示文本映射位置,不一定是实际绘制位置: @@ -464,6 +464,65 @@ let version = map.version(); 缓冲区和显示坐标的序号均从零开始。被折叠隐藏的缓冲区行没有显示行范围(返回 `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` 最终会稳定下来。 + ## 值与事件 ```rust From 18f898c0c2aa9cd4a8293dda2bd7a43df3ddaeed Mon Sep 17 00:00:00 2001 From: cc-glani Date: Fri, 16 Oct 2026 12:39:17 +0200 Subject: [PATCH 7/8] editor: Add hit_test and gutter_bounds to the input state (#3520) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An application that puts something of its own in the editor's gutter — a menu for a line, a bookmark or breakpoint toggle, a tooltip over a marker — has to know what a point is over: the gutter or the text, which column of the gutter, and which buffer row. Today it can only re-derive the gutter's layout. This adds two read-only queries on the input state, `hit_test` and `gutter_bounds`. `InputHit` keeps its fields private, as `InputContextMenuCapabilities` does, so more can be told about a point later without breaking its readers. Nothing an input does changes: no handler reads them. It follows the shape `row_bounds` and `display_map()` set — the state answers, the application decides. Both are exported from `gpui_kit::base::input` and `gpui_kit::component::input`; the editor page has a paragraph and an example, in English and Chinese. `row()` and `is_spacer()` follow the spacer rows of #3466, now in `next`; in the gutter, the ghost lines of an inline completion, which stand between a row's text and the spacers below it, are beside no row. `gpui_kit::component::input`) - `InputBaseState::hit_test(&self, position: Point) -> Option` — what a point in window coordinates is over, as last painted; `None` before the first paint and outside the input. On every input state (`InputState`, `TextareaState`, `EditorState`). - `InputBaseState::gutter_bounds(&self) -> Option>` — the gutter's painted bounds, from the text's margin to the outer edge of the padding; `None` before the first paint and without a gutter. - `pub struct InputHit` (`Clone, Copy, Debug, PartialEq, Eq`; fields private) — what a point is over, read through: - `InputHit::area(&self) -> InputHitArea` — the text or the gutter, below; - `InputHit::row(&self) -> Option` — the buffer row beside the point; in the gutter `None` above the first row and below the last; - `InputHit::is_spacer(&self) -> bool` — the point is on one of that row's spacer rows (#3466), read as a click reads it; - `InputHit::offset(&self) -> Option`, `InputHit::is_gutter(&self) -> bool`, `InputHit::gutter_column(&self) -> Option` — shorthands. - `#[non_exhaustive] pub enum InputHitArea { Text { offset: usize }, Gutter { column: Option } }` — `Text { offset }`, the offset a click there places the caret at, or `Gutter { column }`, `None` in the margin or padding. - `hit_test_tells_the_gutter_from_the_text` — each column of the gutter on either side (#3417), the margin, below the last row, the text at the caret's offset, outside the input, before the first paint. - `hit_test_puts_a_spacer_row_beside_its_line` — above and below a row, in the gutter and in the text, and below the ghost lines of an inline completion. Each goes red with its protection removed: the gutter bounds not stored (both), the spacer rows, or the ghost lines, left out of `row_at` (the second), no column found (the first). - `cargo test -p gpui-base --lib -- input::` (361 passed) - `cargo clippy -p gpui-base --lib --tests -- -D warnings`, nothing in the files touched - [x] I have read the [CONTRIBUTING](../CONTRIBUTING.md) document and followed the guidelines. - [x] Reviewed the changes in this PR and confirmed AI generated code (If any) is accurate. - [ ] Passed `cargo run` for story tests related to the changes. - [x] Tested macOS, Windows and Linux platforms performance (if the change is platform-specific) --------- Co-authored-by: Jason Lee --- crates/base/src/input/base/element.rs | 174 +++++++++++++++++++++++++- crates/base/src/input/base/layout.rs | 88 +++++++++++++ crates/base/src/input/base/state.rs | 76 ++++++++++- crates/base/src/input/mod.rs | 2 +- crates/component/src/input/mod.rs | 23 ++-- website/component/editor.md | 22 ++++ website/zh-CN/component/editor.md | 20 +++ 7 files changed, 387 insertions(+), 18 deletions(-) diff --git a/crates/base/src/input/base/element.rs b/crates/base/src/input/base/element.rs index ec507d98dc..cba9d6a369 100644 --- a/crates/base/src/input/base/element.rs +++ b/crates/base/src/input/base/element.rs @@ -686,7 +686,7 @@ fn editor_text_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. -fn gutter_column( +pub(super) fn gutter_column( last_layout: &LastLayout, folding: bool, column: GutterColumn, @@ -4175,6 +4175,15 @@ impl Element for TextElement { }); caret_moved || layout.line_height != last_layout.line_height }); + state.last_gutter_bounds = (last_layout.line_number_width > 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()); @@ -4854,6 +4863,7 @@ fn split_runs_by_bg_segments( #[cfg(test)] mod tests { use super::*; + use crate::input::InputHitArea; use crate::input::{ EditorMode, EditorState, FoldPlaceholderRenderer, FoldRange, GutterDecoration, GutterDecorationCollection, OverviewRulerDecoration, OverviewRulerDecorationCollection, @@ -9249,4 +9259,166 @@ mod tests { offset ); } + + /// 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)); + } + }); + } } diff --git a/crates/base/src/input/base/layout.rs b/crates/base/src/input/base/layout.rs index e4d51f6b44..de2519e0ce 100644 --- a/crates/base/src/input/base/layout.rs +++ b/crates/base/src/input/base/layout.rs @@ -57,6 +57,74 @@ impl GutterColumn { } } +/// 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, @@ -144,6 +212,26 @@ impl LastLayout { }) } + /// 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)) + }) + } + pub(super) fn alignment_offset(&self, line_width: Pixels) -> Pixels { match self.text_align { TextAlign::Left => px(0.), diff --git a/crates/base/src/input/base/state.rs b/crates/base/src/input/base/state.rs index 6ad7391866..4971fdcdc2 100644 --- a/crates/base/src/input/base/state.rs +++ b/crates/base/src/input/base/state.rs @@ -44,7 +44,9 @@ 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::{ - InputEdit, InputExtras as _, Position, RopeExt as _, element::RIGHT_MARGIN, layout::LastLayout, + InputEdit, InputExtras as _, Position, RopeExt as _, + element::RIGHT_MARGIN, + layout::{InputHit, InputHitArea, LastLayout}, }; use crate::overscroll::Overscroll; use crate::{AutoScroll, StepAction, TestSupportExt as _}; @@ -505,6 +507,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)>, @@ -1051,6 +1055,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, @@ -3809,7 +3814,7 @@ impl InputBaseState { 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()) @@ -3819,14 +3824,21 @@ impl InputBaseState { 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 mut pos = inner_position - line_origin; - // A pointer on a spacer row is on the row of text it stands beside. + // 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 + spacer_below { + } else if pos.y >= height && pos.y < height + ghost_height + spacer_below { pos.y = height - line_height; } @@ -3855,7 +3867,7 @@ impl InputBaseState { return (self.resolve_index(line_start_offset), false, 0); } - y_offset += height + spacer_below; + y_offset += height + ghost_height + spacer_below; last_line_pos = Some(pos); } @@ -4394,6 +4406,60 @@ impl InputBaseState { )) } + /// 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. diff --git a/crates/base/src/input/mod.rs b/crates/base/src/input/mod.rs index 13e4c5c726..e6f5a086cb 100644 --- a/crates/base/src/input/mod.rs +++ b/crates/base/src/input/mod.rs @@ -118,7 +118,7 @@ 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; +pub use layout::{GutterColumn, InputHit, InputHitArea}; pub use line_decorations::{ GutterMarker, LineDecoration, LineDecorationCollection, LineDecorationProvider, }; diff --git a/crates/component/src/input/mod.rs b/crates/component/src/input/mod.rs index 8d86e7218a..b7b34359aa 100644 --- a/crates/component/src/input/mod.rs +++ b/crates/component/src/input/mod.rs @@ -31,17 +31,18 @@ pub use gpui_base::input::{ EditorState, Enter, Escape, FoldRange, GoToDefinition, GutterColumn, GutterDecoration, GutterDecorationCollection, GutterMarker, HighlightStyleResolver, HoverPopoverState, HoverProvider, Indent, IndentInline, InputEdit, InputEditsEvent, InputEvent, InputHighlighter, - InputHighlighterFactory, 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, + 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}; #[doc(hidden)] diff --git a/website/component/editor.md b/website/component/editor.md index 13367234ff..572da31270 100644 --- a/website/component/editor.md +++ b/website/component/editor.md @@ -536,6 +536,28 @@ where it is painted: below a multi-line inline completion, rows move down with t 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`. diff --git a/website/zh-CN/component/editor.md b/website/zh-CN/component/editor.md index 00754f748e..a0e0bc539d 100644 --- a/website/zh-CN/component/editor.md +++ b/website/zh-CN/component/editor.md @@ -437,6 +437,26 @@ info 颜色;`GutterMarker::Custom { icon, color }` 按原样绘制给定的图 文字一起下移。该行尚未布局时返回 `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` 导入。编辑器状态负责更新映射;应用可以用它实现自定义缩略图、 From d5da0f664ae2fbb6ba4be215bfcee5be8aa7579d Mon Sep 17 00:00:00 2001 From: cc-glani Date: Mon, 19 Oct 2026 13:31:37 +0200 Subject: [PATCH 8/8] editor: Tell a custom context menu whether it was opened on the gutter (#3521) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A right-click on a line number opens the text's menu today — Cut, Copy, Paste — and moves the caret there. An editor that wants a menu about the line clicked — bookmark it, toggle a breakpoint, accept a change in a diff — has no way to tell that the click was on the gutter, nor which row. This tells the menu, and keeps every existing builder working as it does. `examples/editor_gutter_menu` shows it: a line number's menu bookmarks (a `GutterMarker::Bookmark` through a line decoration provider), selects or copies the line, and the text keeps the usual menu. The input page and the editor page describe it, in English and Chinese. Stacked on #3520 (`hit_test`), whose two commits the diff here still shows; the diff to review is the last three commits. Once #3520 lands it will be rebased onto `next`. | a line number's menu, the selection kept | after Bookmark Line 6 | the text's menu | |---|---|---| | a line number's menu, the selection kept | a bookmark beside line 6 after Bookmark Line
6 | the text's usual menu | Drawn headless on Linux, where the native menu falls back to the drawn popup. - `Input::context_menu_with(self, f: impl Fn(NativeMenu, InputContextMenuCapabilities, Option, &mut Window, &mut App) -> NativeMenu + 'static) -> Self` and `Editor::context_menu_with`, the same — a builder that receives the capabilities and what the right-click was over, from `hit_test` (#3520): the text at an offset, or a row of the gutter in a column. `context_menu` keeps its signature and is now the builder that ignores them. - `default_context_menu(menu: NativeMenu, capabilities: InputContextMenuCapabilities) -> NativeMenu` — the built-in items, public, for the clicks a custom builder leaves alone. - `InputContextMenuCapabilities` — re-exported from `gpui-base`, for the two signatures above. `gpui_kit::component::input`) - `InputBaseState::gutter_context_menu_moves_cursor(self, moves: bool) -> Self` / `InputBaseState::set_gutter_context_menu_moves_cursor(&mut self, moves: bool)` — `true` by default, as now; `false` keeps the selection while the gutter's menu is open (and skips the hover-definition lookup for it). - `#[doc(hidden)] InputBaseState::on_context_menu_with_hit(&mut self, handler: Rc, Point, &mut Window, &mut App)>)` — how `Input` hands the hit to its builder, as `set_editor_paddings` hands over the paddings; `on_context_menu` keeps its signature. - `a_right_click_on_the_gutter_tells_the_menu_its_row` (base) — the gutter's row and column reach the menu; by default the caret moves to the row, with the flag off the selection stays, and the text moves the caret either way. - `a_menu_built_with_its_target_knows_the_row_of_the_gutter` (component) — through `Editor::context_menu_with` the builder sees the gutter's row and the text's, and `context_menu` still opens. Each goes red with its protection removed: the hit left out of the menu's handler, the flag ignored, the hit dropped between `Input` and the builder. - `cargo test -p gpui-base --lib -- input::` (362 passed), `cargo test -p gpui-component --lib -- input::` (45 passed) - `cargo run -p example-editor-gutter-menu` — drawn headless, screenshots above - [x] I have read the [CONTRIBUTING](../CONTRIBUTING.md) document and followed the guidelines. - [x] Reviewed the changes in this PR and confirmed AI generated code (If any) is accurate. - [ ] Passed `cargo run` for story tests related to the changes. - [x] Tested macOS, Windows and Linux platforms performance (if the change is platform-specific) --------- Co-authored-by: Jason Lee --- Cargo.lock | 7 + Cargo.toml | 1 + crates/base/src/input/base/element.rs | 63 ++++++- crates/base/src/input/base/state.rs | 87 ++++++++-- crates/component/src/input/editor.rs | 102 ++++++++++- crates/component/src/input/input.rs | 144 ++++++++++----- crates/component/src/input/mod.rs | 8 +- crates/component/src/input/state.rs | 5 +- examples/README.md | 1 + examples/editor_gutter_menu/Cargo.toml | 12 ++ examples/editor_gutter_menu/src/main.rs | 221 ++++++++++++++++++++++++ website/component/editor.md | 34 ++++ website/component/input.md | 10 ++ website/zh-CN/component/editor.md | 32 ++++ website/zh-CN/component/input.md | 9 + 15 files changed, 665 insertions(+), 71 deletions(-) create mode 100644 examples/editor_gutter_menu/Cargo.toml create mode 100644 examples/editor_gutter_menu/src/main.rs diff --git a/Cargo.lock b/Cargo.lock index ad0aa4feee..2a42a71fa4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2873,6 +2873,13 @@ dependencies = [ "tree-sitter-navi", ] +[[package]] +name = "example-editor-gutter-menu" +version = "0.9.1" +dependencies = [ + "gpui-kit", +] + [[package]] name = "example-editor-spacers" version = "0.9.1" diff --git a/Cargo.toml b/Cargo.toml index c821d2785e..c37b1527e9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,6 +17,7 @@ members = [ "examples/hello_world", "examples/input", "examples/editor", + "examples/editor_gutter_menu", "examples/editor_spacers", "examples/syntect", "examples/tig", diff --git a/crates/base/src/input/base/element.rs b/crates/base/src/input/base/element.rs index cba9d6a369..ebb60184fc 100644 --- a/crates/base/src/input/base/element.rs +++ b/crates/base/src/input/base/element.rs @@ -4863,12 +4863,12 @@ fn split_runs_by_bg_segments( #[cfg(test)] mod tests { use super::*; - use crate::input::InputHitArea; use crate::input::{ EditorMode, EditorState, FoldPlaceholderRenderer, FoldRange, GutterDecoration, GutterDecorationCollection, OverviewRulerDecoration, OverviewRulerDecorationCollection, Position, RangeDecoration, Redo, Undo, }; + use crate::input::{InputHit, InputHitArea}; use crate::{ScrollbarMode, ScrollbarStyles, ScrollbarTheme, Theme}; use gpui::{ AppContext as _, Context, EntityInputHandler as _, ListAlignment, ListOffset, ListState, @@ -9421,4 +9421,65 @@ mod tests { } }); } + + #[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); + } } diff --git a/crates/base/src/input/base/state.rs b/crates/base/src/input/base/state.rs index 4971fdcdc2..22d1d458c4 100644 --- a/crates/base/src/input/base/state.rs +++ b/crates/base/src/input/base/state.rs @@ -586,10 +586,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. /// @@ -939,6 +951,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); } @@ -1086,6 +1120,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, @@ -1109,6 +1144,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; } @@ -2621,6 +2675,7 @@ impl InputBaseState { &mut self, position: Point, offset: usize, + hit: Option, window: &mut Window, cx: &mut Context, ) { @@ -2632,11 +2687,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); } @@ -2650,7 +2706,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 @@ -2903,10 +2959,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; } @@ -2945,8 +3004,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() { @@ -7437,7 +7496,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); @@ -7457,7 +7516,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); @@ -7468,7 +7527,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); @@ -7491,7 +7550,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)); @@ -7520,7 +7579,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)))); diff --git a/crates/component/src/input/editor.rs b/crates/component/src/input/editor.rs index 95f06e67ac..84e35544aa 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, Input}; +use super::input::ContextMenuBuilder; +use super::{EditorState, Input, InputContextMenuCapabilities, InputHit}; use crate::native_menu::NativeMenu; use crate::{ActiveTheme as _, RoleOverride, Sizable, Size, StyledExt as _}; @@ -31,7 +32,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>>, } @@ -109,6 +110,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 @@ -166,7 +188,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)) @@ -658,4 +682,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 11ff69c288..4026fba0d1 100644 --- a/crates/component/src/input/input.rs +++ b/crates/component/src/input/input.rs @@ -21,7 +21,9 @@ use gpui_base::{LayoutDirection, LogicalStyledExt as _}; use rust_i18n::t; use super::state::{TextInputState, sync_focused_input_registry}; -use super::{InputContentType, InputState, sync_native_content_type}; +use super::{ + 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. @@ -128,6 +130,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 { @@ -158,7 +171,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. @@ -393,6 +406,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 @@ -617,6 +655,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(self, window: &mut Window, cx: &mut App) -> impl IntoElement { const LINE_HEIGHT: Rems = Rems(1.25); @@ -671,53 +762,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); }), diff --git a/crates/component/src/input/mod.rs b/crates/component/src/input/mod.rs index b7b34359aa..a1e80e2436 100644 --- a/crates/component/src/input/mod.rs +++ b/crates/component/src/input/mod.rs @@ -30,10 +30,10 @@ pub use gpui_base::input::{ DisplayMap, DisplayPoint, DocumentColorProvider, DocumentRangeSemanticTokensProvider, EditorState, Enter, Escape, FoldRange, GoToDefinition, GutterColumn, GutterDecoration, GutterDecorationCollection, GutterMarker, HighlightStyleResolver, HoverPopoverState, - HoverProvider, Indent, IndentInline, InputEdit, InputEditsEvent, InputEvent, InputHighlighter, - InputHighlighterFactory, InputHit, InputHitArea, InputState, LineDecoration, - LineDecorationCollection, LineDecorationProvider, Lsp, MaskPattern, MoveDown, MoveEnd, - MoveHome, MoveLeft, MovePageDown, MovePageUp, MoveRight, MoveToEnd, MoveToEndOfLine, + 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, 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/examples/README.md b/examples/README.md index de5beace92..75166365de 100644 --- a/examples/README.md +++ b/examples/README.md @@ -10,6 +10,7 @@ not enable the gallery's test-support development dependency. | --- | --- | | 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..71b4cadcf9 --- /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.9.1" +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/website/component/editor.md b/website/component/editor.md index 572da31270..bd1827365e 100644 --- a/website/component/editor.md +++ b/website/component/editor.md @@ -659,6 +659,40 @@ In the display map, spacer rows are display rows: `display_row_count()` counts t 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 43bd503211..e2d7d4a0c2 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/component/editor.md b/website/zh-CN/component/editor.md index a0e0bc539d..7e6ab9e14e 100644 --- a/website/zh-CN/component/editor.md +++ b/website/zh-CN/component/editor.md @@ -543,6 +543,38 @@ left.update(cx, |state, cx| state.set_spacer_provider(Some(level), cx)); 用于区分填充行和文本行。填充行变化时 `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 4331824c9c..6b9f1194f1 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()`: