1use std::{collections::BTreeMap, ops::Range, rc::Rc};
2
3use gpui::{App, Context, Hsla, SharedString, WeakEntity};
4
5use super::{EditorMode, InputBaseState};
6
7#[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 pub fn new(row: usize) -> Self {
18 Self {
19 row,
20 background: None,
21 gutter_icon: None,
22 }
23 }
24
25 pub fn row(&self) -> usize {
27 self.row
28 }
29
30 pub fn background(&self) -> Option<Hsla> {
32 self.background
33 }
34
35 pub fn gutter_icon(&self) -> Option<(&SharedString, Hsla)> {
37 self.gutter_icon
38 .as_ref()
39 .map(|(icon, color)| (icon, *color))
40 }
41
42 pub fn with_background(mut self, color: Hsla) -> Self {
44 self.background = Some(color);
45 self
46 }
47
48 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
59pub trait LineDecorationProvider {
65 fn line_decorations(&self, rows: Range<usize>, cx: &App) -> Vec<LineDecoration>;
67
68 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#[derive(Clone, Debug)]
89pub struct LineDecorationCollection {
90 state: WeakEntity<InputBaseState<EditorMode>>,
91 id: LineDecorationCollectionId,
92}
93
94impl LineDecorationCollection {
95 pub fn set_provider(&self, provider: Rc<dyn LineDecorationProvider>, cx: &mut App) {
97 self.update(Some(provider), cx);
98 }
99
100 pub fn clear(&self, cx: &mut App) {
102 self.update(None, cx);
103 }
104
105 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 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#[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 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 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}