breadcrumbs.rs

  1use editor::Editor;
  2use gpui::{
  3    Context, Element, EventEmitter, Focusable, FontWeight, IntoElement, ParentElement, Render,
  4    StyledText, Subscription, Window,
  5};
  6use itertools::Itertools;
  7use settings::Settings;
  8use std::cmp;
  9use theme::ActiveTheme;
 10use ui::{ButtonLike, ButtonStyle, Label, Tooltip, prelude::*};
 11use workspace::{
 12    TabBarSettings, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
 13    item::{BreadcrumbText, ItemEvent, ItemHandle},
 14};
 15
 16pub struct Breadcrumbs {
 17    pane_focused: bool,
 18    active_item: Option<Box<dyn ItemHandle>>,
 19    subscription: Option<Subscription>,
 20}
 21
 22impl Default for Breadcrumbs {
 23    fn default() -> Self {
 24        Self::new()
 25    }
 26}
 27
 28impl Breadcrumbs {
 29    pub fn new() -> Self {
 30        Self {
 31            pane_focused: false,
 32            active_item: Default::default(),
 33            subscription: Default::default(),
 34        }
 35    }
 36}
 37
 38impl EventEmitter<ToolbarItemEvent> for Breadcrumbs {}
 39
 40impl Render for Breadcrumbs {
 41    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 42        const MAX_SEGMENTS: usize = 12;
 43
 44        let element = h_flex()
 45            .id("breadcrumb-container")
 46            .flex_grow()
 47            .overflow_x_scroll()
 48            .text_ui(cx);
 49
 50        let Some(active_item) = self.active_item.as_ref() else {
 51            return element;
 52        };
 53
 54        let Some(mut segments) = active_item.breadcrumbs(cx.theme(), cx) else {
 55            return element;
 56        };
 57
 58        let prefix_end_ix = cmp::min(segments.len(), MAX_SEGMENTS / 2);
 59        let suffix_start_ix = cmp::max(
 60            prefix_end_ix,
 61            segments.len().saturating_sub(MAX_SEGMENTS / 2),
 62        );
 63
 64        if suffix_start_ix > prefix_end_ix {
 65            segments.splice(
 66                prefix_end_ix..suffix_start_ix,
 67                Some(BreadcrumbText {
 68                    text: "".into(),
 69                    highlights: None,
 70                    font: None,
 71                }),
 72            );
 73        }
 74
 75        let highlighted_segments = segments.into_iter().enumerate().map(|(index, segment)| {
 76            let mut text_style = window.text_style();
 77            if let Some(ref font) = segment.font {
 78                text_style.font_family = font.family.clone();
 79                text_style.font_features = font.features.clone();
 80                text_style.font_style = font.style;
 81                text_style.font_weight = font.weight;
 82            }
 83            text_style.color = Color::Muted.color(cx);
 84
 85            if index == 0
 86                && !TabBarSettings::get_global(cx).show
 87                && active_item.is_dirty(cx)
 88                && let Some(styled_element) = apply_dirty_filename_style(&segment, &text_style, cx)
 89            {
 90                return styled_element;
 91            }
 92
 93            StyledText::new(segment.text.replace('\n', ""))
 94                .with_default_highlights(&text_style, segment.highlights.unwrap_or_default())
 95                .into_any()
 96        });
 97        let breadcrumbs = Itertools::intersperse_with(highlighted_segments, || {
 98            Label::new("").color(Color::Placeholder).into_any_element()
 99        });
100
101        let breadcrumbs_stack = h_flex().gap_1().children(breadcrumbs);
102
103        match active_item
104            .downcast::<Editor>()
105            .map(|editor| editor.downgrade())
106        {
107            Some(editor) => element.child(
108                ButtonLike::new("toggle outline view")
109                    .child(breadcrumbs_stack)
110                    .style(ButtonStyle::Transparent)
111                    .on_click({
112                        let editor = editor.clone();
113                        move |_, window, cx| {
114                            if let Some((editor, callback)) = editor
115                                .upgrade()
116                                .zip(zed_actions::outline::TOGGLE_OUTLINE.get())
117                            {
118                                callback(editor.to_any(), window, cx);
119                            }
120                        }
121                    })
122                    .tooltip(move |window, cx| {
123                        if let Some(editor) = editor.upgrade() {
124                            let focus_handle = editor.read(cx).focus_handle(cx);
125                            Tooltip::for_action_in(
126                                "Show Symbol Outline",
127                                &zed_actions::outline::ToggleOutline,
128                                &focus_handle,
129                                window,
130                                cx,
131                            )
132                        } else {
133                            Tooltip::for_action(
134                                "Show Symbol Outline",
135                                &zed_actions::outline::ToggleOutline,
136                                window,
137                                cx,
138                            )
139                        }
140                    }),
141            ),
142            None => element
143                // Match the height and padding of the `ButtonLike` in the other arm.
144                .h(rems_from_px(22.))
145                .pl_1()
146                .child(breadcrumbs_stack),
147        }
148    }
149}
150
151impl ToolbarItemView for Breadcrumbs {
152    fn set_active_pane_item(
153        &mut self,
154        active_pane_item: Option<&dyn ItemHandle>,
155        window: &mut Window,
156        cx: &mut Context<Self>,
157    ) -> ToolbarItemLocation {
158        cx.notify();
159        self.active_item = None;
160
161        let Some(item) = active_pane_item else {
162            return ToolbarItemLocation::Hidden;
163        };
164
165        let this = cx.entity().downgrade();
166        self.subscription = Some(item.subscribe_to_item_events(
167            window,
168            cx,
169            Box::new(move |event, _, cx| {
170                if let ItemEvent::UpdateBreadcrumbs = event {
171                    this.update(cx, |this, cx| {
172                        cx.notify();
173                        if let Some(active_item) = this.active_item.as_ref() {
174                            cx.emit(ToolbarItemEvent::ChangeLocation(
175                                active_item.breadcrumb_location(cx),
176                            ))
177                        }
178                    })
179                    .ok();
180                }
181            }),
182        ));
183        self.active_item = Some(item.boxed_clone());
184        item.breadcrumb_location(cx)
185    }
186
187    fn pane_focus_update(
188        &mut self,
189        pane_focused: bool,
190        _window: &mut Window,
191        _: &mut Context<Self>,
192    ) {
193        self.pane_focused = pane_focused;
194    }
195}
196
197fn apply_dirty_filename_style(
198    segment: &BreadcrumbText,
199    text_style: &gpui::TextStyle,
200    cx: &mut Context<Breadcrumbs>,
201) -> Option<gpui::AnyElement> {
202    let text = segment.text.replace('\n', "");
203
204    let filename_position = std::path::Path::new(&segment.text)
205        .file_name()
206        .and_then(|f| {
207            let filename_str = f.to_string_lossy();
208            segment.text.rfind(filename_str.as_ref())
209        })?;
210
211    let bold_weight = FontWeight::BOLD;
212    let default_color = Color::Default.color(cx);
213
214    if filename_position == 0 {
215        let mut filename_style = text_style.clone();
216        filename_style.font_weight = bold_weight;
217        filename_style.color = default_color;
218
219        return Some(
220            StyledText::new(text)
221                .with_default_highlights(&filename_style, [])
222                .into_any(),
223        );
224    }
225
226    let highlight_style = gpui::HighlightStyle {
227        font_weight: Some(bold_weight),
228        color: Some(default_color),
229        ..Default::default()
230    };
231
232    let highlight = vec![(filename_position..text.len(), highlight_style)];
233    Some(
234        StyledText::new(text)
235            .with_default_highlights(text_style, highlight)
236            .into_any(),
237    )
238}