indent_guides.rs

  1use std::{cmp::Ordering, ops::Range, rc::Rc};
  2
  3use gpui::{
  4    AnyElement, App, Bounds, Entity, Hsla, Point, UniformListDecoration, fill, point, size,
  5};
  6use smallvec::SmallVec;
  7
  8use crate::prelude::*;
  9
 10/// Represents the colors used for different states of indent guides.
 11#[derive(Debug, Clone)]
 12pub struct IndentGuideColors {
 13    /// The color of the indent guide when it's neither active nor hovered.
 14    pub default: Hsla,
 15    /// The color of the indent guide when it's hovered.
 16    pub hover: Hsla,
 17    /// The color of the indent guide when it's active.
 18    pub active: Hsla,
 19}
 20
 21impl IndentGuideColors {
 22    /// Returns the indent guide colors that should be used for panels.
 23    pub fn panel(cx: &App) -> Self {
 24        Self {
 25            default: cx.theme().colors().panel_indent_guide,
 26            hover: cx.theme().colors().panel_indent_guide_hover,
 27            active: cx.theme().colors().panel_indent_guide_active,
 28        }
 29    }
 30}
 31
 32pub struct IndentGuides {
 33    colors: IndentGuideColors,
 34    indent_size: Pixels,
 35    compute_indents_fn: Box<dyn Fn(Range<usize>, &mut Window, &mut App) -> SmallVec<[usize; 64]>>,
 36    render_fn: Option<
 37        Box<
 38            dyn Fn(
 39                RenderIndentGuideParams,
 40                &mut Window,
 41                &mut App,
 42            ) -> SmallVec<[RenderedIndentGuide; 12]>,
 43        >,
 44    >,
 45    on_click: Option<Rc<dyn Fn(&IndentGuideLayout, &mut Window, &mut App)>>,
 46}
 47
 48pub fn indent_guides<V: Render>(
 49    entity: Entity<V>,
 50    indent_size: Pixels,
 51    colors: IndentGuideColors,
 52    compute_indents_fn: impl Fn(
 53        &mut V,
 54        Range<usize>,
 55        &mut Window,
 56        &mut Context<V>,
 57    ) -> SmallVec<[usize; 64]>
 58    + 'static,
 59) -> IndentGuides {
 60    let compute_indents_fn = Box::new(move |range, window: &mut Window, cx: &mut App| {
 61        entity.update(cx, |this, cx| compute_indents_fn(this, range, window, cx))
 62    });
 63    IndentGuides {
 64        colors,
 65        indent_size,
 66        compute_indents_fn,
 67        render_fn: None,
 68        on_click: None,
 69    }
 70}
 71
 72impl IndentGuides {
 73    /// Sets the callback that will be called when the user clicks on an indent guide.
 74    pub fn on_click(
 75        mut self,
 76        on_click: impl Fn(&IndentGuideLayout, &mut Window, &mut App) + 'static,
 77    ) -> Self {
 78        self.on_click = Some(Rc::new(on_click));
 79        self
 80    }
 81
 82    /// Sets a custom callback that will be called when the indent guides need to be rendered.
 83    pub fn with_render_fn<V: Render>(
 84        mut self,
 85        entity: Entity<V>,
 86        render_fn: impl Fn(
 87            &mut V,
 88            RenderIndentGuideParams,
 89            &mut Window,
 90            &mut App,
 91        ) -> SmallVec<[RenderedIndentGuide; 12]>
 92        + 'static,
 93    ) -> Self {
 94        let render_fn = move |params, window: &mut Window, cx: &mut App| {
 95            entity.update(cx, |this, cx| render_fn(this, params, window, cx))
 96        };
 97        self.render_fn = Some(Box::new(render_fn));
 98        self
 99    }
100}
101
102/// Parameters for rendering indent guides.
103pub struct RenderIndentGuideParams {
104    /// The calculated layouts for the indent guides to be rendered.
105    pub indent_guides: SmallVec<[IndentGuideLayout; 12]>,
106    /// The size of each indentation level in pixels.
107    pub indent_size: Pixels,
108    /// The height of each item in pixels.
109    pub item_height: Pixels,
110}
111
112/// Represents a rendered indent guide with its visual properties and interaction areas.
113pub struct RenderedIndentGuide {
114    /// The bounds of the rendered indent guide in pixels.
115    pub bounds: Bounds<Pixels>,
116    /// The layout information for the indent guide.
117    pub layout: IndentGuideLayout,
118    /// Indicates whether the indent guide is currently active.
119    pub is_active: bool,
120    /// Can be used to customize the hitbox of the indent guide,
121    /// if this is set to `None`, the bounds of the indent guide will be used.
122    pub hitbox: Option<Bounds<Pixels>>,
123}
124
125/// Represents the layout information for an indent guide.
126#[derive(Debug, PartialEq, Eq, Hash)]
127pub struct IndentGuideLayout {
128    /// The starting position of the indent guide, where x is the indentation level
129    /// and y is the starting row.
130    pub offset: Point<usize>,
131    /// The length of the indent guide in rows.
132    pub length: usize,
133    /// Indicates whether the indent guide continues beyond the visible bounds.
134    pub continues_offscreen: bool,
135}
136
137/// Implements the necessary functionality for rendering indent guides inside a uniform list.
138mod uniform_list {
139    use gpui::{DispatchPhase, Hitbox, MouseButton, MouseDownEvent, MouseMoveEvent};
140
141    use super::*;
142
143    impl UniformListDecoration for IndentGuides {
144        fn compute(
145            &self,
146            visible_range: Range<usize>,
147            bounds: Bounds<Pixels>,
148            item_height: Pixels,
149            item_count: usize,
150            window: &mut Window,
151            cx: &mut App,
152        ) -> AnyElement {
153            let mut visible_range = visible_range.clone();
154            let includes_trailing_indent = visible_range.end < item_count;
155            // Check if we have entries after the visible range,
156            // if so extend the visible range so we can fetch a trailing indent,
157            // which is needed to compute indent guides correctly.
158            if includes_trailing_indent {
159                visible_range.end += 1;
160            }
161            let visible_entries = &(self.compute_indents_fn)(visible_range.clone(), window, cx);
162            let indent_guides = compute_indent_guides(
163                &visible_entries,
164                visible_range.start,
165                includes_trailing_indent,
166            );
167            let mut indent_guides = if let Some(ref custom_render) = self.render_fn {
168                let params = RenderIndentGuideParams {
169                    indent_guides,
170                    indent_size: self.indent_size,
171                    item_height,
172                };
173                custom_render(params, window, cx)
174            } else {
175                indent_guides
176                    .into_iter()
177                    .map(|layout| RenderedIndentGuide {
178                        bounds: Bounds::new(
179                            point(
180                                layout.offset.x * self.indent_size,
181                                layout.offset.y * item_height,
182                            ),
183                            size(px(1.), layout.length * item_height),
184                        ),
185                        layout,
186                        is_active: false,
187                        hitbox: None,
188                    })
189                    .collect()
190            };
191            for guide in &mut indent_guides {
192                guide.bounds.origin += bounds.origin;
193                if let Some(hitbox) = guide.hitbox.as_mut() {
194                    hitbox.origin += bounds.origin;
195                }
196            }
197
198            let indent_guides = IndentGuidesElement {
199                indent_guides: Rc::new(indent_guides),
200                colors: self.colors.clone(),
201                on_hovered_indent_guide_click: self.on_click.clone(),
202            };
203            indent_guides.into_any_element()
204        }
205    }
206
207    struct IndentGuidesElement {
208        colors: IndentGuideColors,
209        indent_guides: Rc<SmallVec<[RenderedIndentGuide; 12]>>,
210        on_hovered_indent_guide_click:
211            Option<Rc<dyn Fn(&IndentGuideLayout, &mut Window, &mut App)>>,
212    }
213
214    enum IndentGuidesElementPrepaintState {
215        Static,
216        Interactive {
217            hitboxes: Rc<SmallVec<[Hitbox; 12]>>,
218            on_hovered_indent_guide_click: Rc<dyn Fn(&IndentGuideLayout, &mut Window, &mut App)>,
219        },
220    }
221
222    impl Element for IndentGuidesElement {
223        type RequestLayoutState = ();
224        type PrepaintState = IndentGuidesElementPrepaintState;
225
226        fn id(&self) -> Option<ElementId> {
227            None
228        }
229
230        fn request_layout(
231            &mut self,
232            _id: Option<&gpui::GlobalElementId>,
233            window: &mut Window,
234            cx: &mut App,
235        ) -> (gpui::LayoutId, Self::RequestLayoutState) {
236            (window.request_layout(gpui::Style::default(), [], cx), ())
237        }
238
239        fn prepaint(
240            &mut self,
241            _id: Option<&gpui::GlobalElementId>,
242            _bounds: Bounds<Pixels>,
243            _request_layout: &mut Self::RequestLayoutState,
244            window: &mut Window,
245            _cx: &mut App,
246        ) -> Self::PrepaintState {
247            if let Some(on_hovered_indent_guide_click) = self.on_hovered_indent_guide_click.clone()
248            {
249                let hitboxes = self
250                    .indent_guides
251                    .as_ref()
252                    .iter()
253                    .map(|guide| window.insert_hitbox(guide.hitbox.unwrap_or(guide.bounds), false))
254                    .collect();
255                Self::PrepaintState::Interactive {
256                    hitboxes: Rc::new(hitboxes),
257                    on_hovered_indent_guide_click,
258                }
259            } else {
260                Self::PrepaintState::Static
261            }
262        }
263
264        fn paint(
265            &mut self,
266            _id: Option<&gpui::GlobalElementId>,
267            _bounds: Bounds<Pixels>,
268            _request_layout: &mut Self::RequestLayoutState,
269            prepaint: &mut Self::PrepaintState,
270            window: &mut Window,
271            _cx: &mut App,
272        ) {
273            let current_view = window.current_view();
274
275            match prepaint {
276                IndentGuidesElementPrepaintState::Static => {
277                    for indent_guide in self.indent_guides.as_ref() {
278                        let fill_color = if indent_guide.is_active {
279                            self.colors.active
280                        } else {
281                            self.colors.default
282                        };
283
284                        window.paint_quad(fill(indent_guide.bounds, fill_color));
285                    }
286                }
287                IndentGuidesElementPrepaintState::Interactive {
288                    hitboxes,
289                    on_hovered_indent_guide_click,
290                } => {
291                    window.on_mouse_event({
292                        let hitboxes = hitboxes.clone();
293                        let indent_guides = self.indent_guides.clone();
294                        let on_hovered_indent_guide_click = on_hovered_indent_guide_click.clone();
295                        move |event: &MouseDownEvent, phase, window, cx| {
296                            if phase == DispatchPhase::Bubble && event.button == MouseButton::Left {
297                                let mut active_hitbox_ix = None;
298                                for (i, hitbox) in hitboxes.iter().enumerate() {
299                                    if hitbox.is_hovered(window) {
300                                        active_hitbox_ix = Some(i);
301                                        break;
302                                    }
303                                }
304
305                                let Some(active_hitbox_ix) = active_hitbox_ix else {
306                                    return;
307                                };
308
309                                let active_indent_guide = &indent_guides[active_hitbox_ix].layout;
310                                on_hovered_indent_guide_click(active_indent_guide, window, cx);
311
312                                cx.stop_propagation();
313                                window.prevent_default();
314                            }
315                        }
316                    });
317                    let mut hovered_hitbox_id = None;
318                    for (i, hitbox) in hitboxes.iter().enumerate() {
319                        window.set_cursor_style(gpui::CursorStyle::PointingHand, Some(hitbox));
320                        let indent_guide = &self.indent_guides[i];
321                        let fill_color = if hitbox.is_hovered(window) {
322                            hovered_hitbox_id = Some(hitbox.id);
323                            self.colors.hover
324                        } else if indent_guide.is_active {
325                            self.colors.active
326                        } else {
327                            self.colors.default
328                        };
329
330                        window.paint_quad(fill(indent_guide.bounds, fill_color));
331                    }
332
333                    window.on_mouse_event({
334                        let prev_hovered_hitbox_id = hovered_hitbox_id;
335                        let hitboxes = hitboxes.clone();
336                        move |_: &MouseMoveEvent, phase, window, cx| {
337                            let mut hovered_hitbox_id = None;
338                            for hitbox in hitboxes.as_ref() {
339                                if hitbox.is_hovered(window) {
340                                    hovered_hitbox_id = Some(hitbox.id);
341                                    break;
342                                }
343                            }
344                            if phase == DispatchPhase::Capture {
345                                // If the hovered hitbox has changed, we need to re-paint the indent guides.
346                                match (prev_hovered_hitbox_id, hovered_hitbox_id) {
347                                    (Some(prev_id), Some(id)) => {
348                                        if prev_id != id {
349                                            cx.notify(current_view)
350                                        }
351                                    }
352                                    (None, Some(_)) => cx.notify(current_view),
353                                    (Some(_), None) => cx.notify(current_view),
354                                    (None, None) => {}
355                                }
356                            }
357                        }
358                    });
359                }
360            }
361        }
362    }
363
364    impl IntoElement for IndentGuidesElement {
365        type Element = Self;
366
367        fn into_element(self) -> Self::Element {
368            self
369        }
370    }
371}
372
373fn compute_indent_guides(
374    indents: &[usize],
375    offset: usize,
376    includes_trailing_indent: bool,
377) -> SmallVec<[IndentGuideLayout; 12]> {
378    let mut indent_guides = SmallVec::<[IndentGuideLayout; 12]>::new();
379    let mut indent_stack = SmallVec::<[IndentGuideLayout; 8]>::new();
380
381    let mut min_depth = usize::MAX;
382    for (row, &depth) in indents.iter().enumerate() {
383        if includes_trailing_indent && row == indents.len() - 1 {
384            continue;
385        }
386
387        let current_row = row + offset;
388        let current_depth = indent_stack.len();
389        if depth < min_depth {
390            min_depth = depth;
391        }
392
393        match depth.cmp(&current_depth) {
394            Ordering::Less => {
395                for _ in 0..(current_depth - depth) {
396                    if let Some(guide) = indent_stack.pop() {
397                        indent_guides.push(guide);
398                    }
399                }
400            }
401            Ordering::Greater => {
402                for new_depth in current_depth..depth {
403                    indent_stack.push(IndentGuideLayout {
404                        offset: Point::new(new_depth, current_row),
405                        length: current_row,
406                        continues_offscreen: false,
407                    });
408                }
409            }
410            _ => {}
411        }
412
413        for indent in indent_stack.iter_mut() {
414            indent.length = current_row - indent.offset.y + 1;
415        }
416    }
417
418    indent_guides.extend(indent_stack);
419
420    for guide in indent_guides.iter_mut() {
421        if includes_trailing_indent
422            && guide.offset.y + guide.length == offset + indents.len().saturating_sub(1)
423        {
424            guide.continues_offscreen = indents
425                .last()
426                .map(|last_indent| guide.offset.x < *last_indent)
427                .unwrap_or(false);
428        }
429    }
430
431    indent_guides
432}
433
434#[cfg(test)]
435mod tests {
436    use super::*;
437
438    #[test]
439    fn test_compute_indent_guides() {
440        fn assert_compute_indent_guides(
441            input: &[usize],
442            offset: usize,
443            includes_trailing_indent: bool,
444            expected: Vec<IndentGuideLayout>,
445        ) {
446            use std::collections::HashSet;
447            assert_eq!(
448                compute_indent_guides(input, offset, includes_trailing_indent)
449                    .into_vec()
450                    .into_iter()
451                    .collect::<HashSet<_>>(),
452                expected.into_iter().collect::<HashSet<_>>(),
453            );
454        }
455
456        assert_compute_indent_guides(
457            &[0, 1, 2, 2, 1, 0],
458            0,
459            false,
460            vec![
461                IndentGuideLayout {
462                    offset: Point::new(0, 1),
463                    length: 4,
464                    continues_offscreen: false,
465                },
466                IndentGuideLayout {
467                    offset: Point::new(1, 2),
468                    length: 2,
469                    continues_offscreen: false,
470                },
471            ],
472        );
473
474        assert_compute_indent_guides(
475            &[2, 2, 2, 1, 1],
476            0,
477            false,
478            vec![
479                IndentGuideLayout {
480                    offset: Point::new(0, 0),
481                    length: 5,
482                    continues_offscreen: false,
483                },
484                IndentGuideLayout {
485                    offset: Point::new(1, 0),
486                    length: 3,
487                    continues_offscreen: false,
488                },
489            ],
490        );
491
492        assert_compute_indent_guides(
493            &[1, 2, 3, 2, 1],
494            0,
495            false,
496            vec![
497                IndentGuideLayout {
498                    offset: Point::new(0, 0),
499                    length: 5,
500                    continues_offscreen: false,
501                },
502                IndentGuideLayout {
503                    offset: Point::new(1, 1),
504                    length: 3,
505                    continues_offscreen: false,
506                },
507                IndentGuideLayout {
508                    offset: Point::new(2, 2),
509                    length: 1,
510                    continues_offscreen: false,
511                },
512            ],
513        );
514
515        assert_compute_indent_guides(
516            &[0, 1, 0],
517            0,
518            true,
519            vec![IndentGuideLayout {
520                offset: Point::new(0, 1),
521                length: 1,
522                continues_offscreen: false,
523            }],
524        );
525
526        assert_compute_indent_guides(
527            &[0, 1, 1],
528            0,
529            true,
530            vec![IndentGuideLayout {
531                offset: Point::new(0, 1),
532                length: 1,
533                continues_offscreen: true,
534            }],
535        );
536        assert_compute_indent_guides(
537            &[0, 1, 2],
538            0,
539            true,
540            vec![IndentGuideLayout {
541                offset: Point::new(0, 1),
542                length: 1,
543                continues_offscreen: true,
544            }],
545        );
546    }
547}