Skip to main content

gpui_base/input/editor/
line_decorations.rs

1use std::{collections::BTreeMap, ops::Range, rc::Rc};
2
3use gpui::{App, Context, Hsla, SharedString, WeakEntity};
4
5use super::{EditorMode, InputBaseState};
6
7/// A decoration of one whole buffer row: a background band, a gutter icon, or both.
8#[derive(Clone, Debug, PartialEq)]
9pub struct LineDecoration {
10    row: usize,
11    background: Option<Hsla>,
12    gutter_icon: Option<(SharedString, Hsla)>,
13}
14
15impl LineDecoration {
16    /// Create an empty decoration for a zero-based buffer row.
17    pub fn new(row: usize) -> Self {
18        Self {
19            row,
20            background: None,
21            gutter_icon: None,
22        }
23    }
24
25    /// The zero-based buffer row this decoration covers.
26    pub fn row(&self) -> usize {
27        self.row
28    }
29
30    /// The color of the background band, if any.
31    pub fn background(&self) -> Option<Hsla> {
32        self.background
33    }
34
35    /// The SVG asset path and color of the gutter icon, if any.
36    pub fn gutter_icon(&self) -> Option<(&SharedString, Hsla)> {
37        self.gutter_icon
38            .as_ref()
39            .map(|(icon, color)| (icon, *color))
40    }
41
42    /// Paint a band of `color` across the whole row.
43    pub fn with_background(mut self, color: Hsla) -> Self {
44        self.background = Some(color);
45        self
46    }
47
48    /// Paint the SVG asset at `icon`, for example `icons/plus.svg`, in `color`
49    /// in the row's gutter.
50    ///
51    /// The icon is painted only if the provider returns `true` from
52    /// [`LineDecorationProvider::has_gutter_icons`].
53    pub fn with_gutter_icon(mut self, icon: impl Into<SharedString>, color: Hsla) -> Self {
54        self.gutter_icon = Some((icon.into(), color));
55        self
56    }
57}
58
59/// Supplies the line decorations of the rows an editor paints.
60///
61/// The editor asks on every frame with the visible buffer rows and ignores
62/// decorations outside them, so an implementation must be cheap. Colors may be
63/// read from `cx`, so they follow theme changes.
64pub trait LineDecorationProvider {
65    /// Return the decorations for rows within `rows`.
66    fn line_decorations(&self, rows: Range<usize>, cx: &App) -> Vec<LineDecoration>;
67
68    /// Whether this provider's decorations have gutter icons. Default is false.
69    ///
70    /// While a provider says it has them and the line numbers are shown, the
71    /// gutter reserves the column of the gutter icons for every row, so the
72    /// gutter keeps its width as rows with an icon scroll in and out of view.
73    /// The gutter icons of other providers are not painted.
74    fn has_gutter_icons(&self) -> bool {
75        false
76    }
77}
78
79#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
80struct LineDecorationCollectionId(usize);
81
82/// An independently managed collection of line decorations, supplied by a
83/// [`LineDecorationProvider`].
84///
85/// Clones address the same collection. Dropping a handle does not clear it; use
86/// [`Self::clear`] to stop painting it or [`Self::dispose`] to release it permanently.
87/// Operations on a disposed collection or a dropped editor are harmless no-ops.
88#[derive(Clone, Debug)]
89pub struct LineDecorationCollection {
90    state: WeakEntity<InputBaseState<EditorMode>>,
91    id: LineDecorationCollectionId,
92}
93
94impl LineDecorationCollection {
95    /// Replace this collection's provider. The next frame asks the new one.
96    pub fn set_provider(&self, provider: Rc<dyn LineDecorationProvider>, cx: &mut App) {
97        self.update(Some(provider), cx);
98    }
99
100    /// Stop painting this collection without invalidating its handles.
101    pub fn clear(&self, cx: &mut App) {
102        self.update(None, cx);
103    }
104
105    /// Release this collection, invalidating all of its cloned handles.
106    pub fn dispose(&self, cx: &mut App) {
107        let _ = self.state.update(cx, |state, cx| {
108            if state.extras.line_decorations.remove(self.id) {
109                cx.notify();
110            }
111        });
112    }
113
114    /// Whether this collection has a provider; `false` once cleared, disposed or dropped.
115    pub fn has_provider(&self, cx: &App) -> bool {
116        self.state
117            .read_with(cx, |state, _| {
118                state.extras.line_decorations.has_provider(self.id)
119            })
120            .unwrap_or(false)
121    }
122
123    fn update(&self, provider: Option<Rc<dyn LineDecorationProvider>>, cx: &mut App) {
124        let _ = self.state.update(cx, |state, cx| {
125            if state.extras.line_decorations.set(self.id, provider) {
126                cx.notify();
127            }
128        });
129    }
130}
131
132/// The line decoration providers of one editor, in creation order.
133#[derive(Default)]
134pub(crate) struct LineDecorationProviders {
135    entries: BTreeMap<LineDecorationCollectionId, Option<Rc<dyn LineDecorationProvider>>>,
136    next_id: usize,
137}
138
139impl LineDecorationProviders {
140    fn create(&mut self, provider: Rc<dyn LineDecorationProvider>) -> LineDecorationCollectionId {
141        let id = LineDecorationCollectionId(self.next_id);
142        self.next_id += 1;
143        self.entries.insert(id, Some(provider));
144        id
145    }
146
147    fn set(
148        &mut self,
149        id: LineDecorationCollectionId,
150        provider: Option<Rc<dyn LineDecorationProvider>>,
151    ) -> bool {
152        let Some(entry) = self.entries.get_mut(&id) else {
153            return false;
154        };
155        *entry = provider;
156        true
157    }
158
159    fn remove(&mut self, id: LineDecorationCollectionId) -> bool {
160        self.entries.remove(&id).is_some()
161    }
162
163    fn has_provider(&self, id: LineDecorationCollectionId) -> bool {
164        self.entries.get(&id).is_some_and(Option::is_some)
165    }
166
167    pub(crate) fn has_any_provider(&self) -> bool {
168        self.entries.values().any(Option::is_some)
169    }
170
171    pub(crate) fn has_gutter_icons(&self) -> bool {
172        self.entries
173            .values()
174            .flatten()
175            .any(|provider| provider.has_gutter_icons())
176    }
177
178    /// Ask every provider about `rows`, in creation order, keeping only the
179    /// decorations that fall within `rows`, and their gutter icons only from a
180    /// provider that has gutter icons.
181    pub(crate) fn query(&self, rows: Range<usize>, cx: &App) -> Vec<LineDecoration> {
182        if rows.is_empty() {
183            return Vec::new();
184        }
185        let mut decorations = Vec::new();
186        for provider in self.entries.values().flatten() {
187            let gutter_icons = provider.has_gutter_icons();
188            decorations.extend(
189                provider
190                    .line_decorations(rows.clone(), cx)
191                    .into_iter()
192                    .filter(|decoration| rows.contains(&decoration.row))
193                    .map(|mut decoration| {
194                        if !gutter_icons {
195                            decoration.gutter_icon = None;
196                        }
197                        decoration
198                    }),
199            );
200        }
201        decorations
202    }
203}
204
205impl InputBaseState<EditorMode> {
206    /// Create an independently owned collection of line decorations, supplied by
207    /// `provider`.
208    ///
209    /// The provider is asked for the visible rows on every frame. Unlike text and
210    /// range decorations, rows are not tracked across edits: the provider answers
211    /// for the text as it is when asked.
212    ///
213    /// A background spans the whole row, gutter included, across its soft wraps,
214    /// under the active line, indent guides, selections and text. A gutter icon
215    /// is painted in a column of its own, [`GutterColumn::Icons`](crate::input::GutterColumn::Icons),
216    /// only while the line numbers are shown and its provider says it has
217    /// gutter icons: square, sized from the line height and centred on its row.
218    /// In the default order the column sits between the line numbers and the
219    /// outer edge of the gutter; [`InputBaseState::gutter_order`] can move it
220    /// nearer the text. Later collections paint over earlier ones. Neither
221    /// affects hit testing or focus. Collections live until explicitly disposed
222    /// or the editor is dropped.
223    pub fn create_line_decorations_collection(
224        &mut self,
225        provider: Rc<dyn LineDecorationProvider>,
226        cx: &mut Context<Self>,
227    ) -> LineDecorationCollection {
228        let id = self.extras.line_decorations.create(provider);
229        cx.notify();
230        LineDecorationCollection {
231            state: cx.entity().downgrade(),
232            id,
233        }
234    }
235}
236
237#[cfg(test)]
238mod tests {
239    use std::cell::RefCell;
240
241    use gpui::{AppContext as _, TestAppContext, hsla};
242
243    use super::*;
244    use crate::input::EditorState;
245
246    struct EveryNth {
247        every: usize,
248        color: Hsla,
249        asked: RefCell<Vec<Range<usize>>>,
250    }
251
252    impl EveryNth {
253        fn new(every: usize, color: Hsla) -> Rc<Self> {
254            Rc::new(Self {
255                every,
256                color,
257                asked: RefCell::default(),
258            })
259        }
260    }
261
262    impl LineDecorationProvider for EveryNth {
263        fn line_decorations(&self, rows: Range<usize>, _: &App) -> Vec<LineDecoration> {
264            self.asked.borrow_mut().push(rows.clone());
265            (rows.start.saturating_sub(1)..rows.end + 1)
266                .filter(|row| row % self.every == 0)
267                .map(|row| LineDecoration::new(row).with_background(self.color))
268                .collect()
269        }
270    }
271
272    fn editor(cx: &mut TestAppContext) -> gpui::Entity<EditorState> {
273        cx.update(crate::init);
274        let window = cx.add_empty_window();
275        window.update(|window, cx| cx.new(|cx| EditorState::new(window, cx)))
276    }
277
278    fn red() -> Hsla {
279        hsla(0., 0.5, 0.5, 0.2)
280    }
281
282    fn green() -> Hsla {
283        hsla(0.3, 0.5, 0.5, 0.2)
284    }
285
286    #[test]
287    fn a_decoration_is_built_from_its_parts() {
288        let color = hsla(0.3, 0.5, 0.5, 0.2);
289        let decoration = LineDecoration::new(7);
290        assert_eq!(decoration.row(), 7);
291        assert_eq!(decoration.background(), None);
292        assert_eq!(decoration.gutter_icon(), None);
293
294        let decoration = decoration
295            .with_background(color)
296            .with_gutter_icon("icons/plus.svg", red());
297        assert_eq!(decoration.background(), Some(color));
298        assert_eq!(
299            decoration.gutter_icon(),
300            Some((&SharedString::from("icons/plus.svg"), red()))
301        );
302    }
303
304    #[gpui::test]
305    fn line_decoration_collection_round_trips(cx: &mut TestAppContext) {
306        let editor = editor(cx);
307        let provider = EveryNth::new(1, green());
308
309        let collection = editor.update(cx, |state, cx| {
310            assert!(state.extras.line_decorations.entries.is_empty());
311            state.create_line_decorations_collection(provider.clone(), cx)
312        });
313        cx.read(|cx| assert!(collection.has_provider(cx)));
314
315        cx.update(|cx| collection.clear(cx));
316        cx.read(|cx| {
317            assert!(!collection.has_provider(cx));
318            let state = editor.read(cx);
319            assert!(state.extras.line_decorations.query(0..4, cx).is_empty());
320        });
321
322        cx.update(|cx| collection.clone().set_provider(provider.clone(), cx));
323        cx.read(|cx| {
324            assert!(collection.has_provider(cx));
325            let state = editor.read(cx);
326            assert_eq!(state.extras.line_decorations.query(0..2, cx).len(), 2);
327        });
328
329        cx.update(|cx| {
330            collection.dispose(cx);
331            collection.set_provider(provider.clone(), cx);
332        });
333        cx.read(|cx| {
334            assert!(!collection.has_provider(cx));
335            let state = editor.read(cx);
336            assert!(state.extras.line_decorations.query(0..4, cx).is_empty());
337        });
338    }
339
340    #[gpui::test]
341    fn collections_are_independent_and_asked_in_creation_order(cx: &mut TestAppContext) {
342        let editor = editor(cx);
343        let removed = EveryNth::new(2, red());
344        let added = EveryNth::new(3, green());
345
346        let (first, second) = editor.update(cx, |state, cx| {
347            (
348                state.create_line_decorations_collection(removed.clone(), cx),
349                state.create_line_decorations_collection(added.clone(), cx),
350            )
351        });
352
353        let query = |cx: &mut TestAppContext, rows: Range<usize>| {
354            cx.read(|cx| {
355                editor
356                    .read(cx)
357                    .extras
358                    .line_decorations
359                    .query(rows, cx)
360                    .into_iter()
361                    .map(|decoration| (decoration.row(), decoration.background().unwrap()))
362                    .collect::<Vec<_>>()
363            })
364        };
365
366        assert_eq!(
367            query(cx, 1..7),
368            vec![
369                (2, red()),
370                (4, red()),
371                (6, red()),
372                (3, green()),
373                (6, green()),
374            ]
375        );
376        assert_eq!(*removed.asked.borrow(), vec![1..7]);
377        assert_eq!(*added.asked.borrow(), vec![1..7]);
378
379        assert!(query(cx, 3..3).is_empty());
380        assert_eq!(removed.asked.borrow().len(), 1);
381
382        cx.update(|cx| first.dispose(cx));
383        assert_eq!(query(cx, 0..4), vec![(0, green()), (3, green())]);
384        cx.read(|cx| assert!(second.has_provider(cx)));
385
386        let third = editor.update(cx, |state, cx| {
387            state.create_line_decorations_collection(removed.clone(), cx)
388        });
389        assert_ne!(third.id, first.id);
390        cx.read(|cx| assert!(!first.has_provider(cx)));
391    }
392
393    #[gpui::test]
394    fn a_dropped_editor_makes_its_collections_no_ops(cx: &mut TestAppContext) {
395        let editor = editor(cx);
396        let collection = editor.update(cx, |state, cx| {
397            state.create_line_decorations_collection(EveryNth::new(1, red()), cx)
398        });
399        drop(editor);
400        cx.run_until_parked();
401
402        cx.update(|cx| {
403            collection.set_provider(EveryNth::new(1, green()), cx);
404            collection.clear(cx);
405            collection.dispose(cx);
406            assert!(!collection.has_provider(cx));
407        });
408    }
409}