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                                cx,
130                            )
131                        } else {
132                            Tooltip::for_action(
133                                "Show Symbol Outline",
134                                &zed_actions::outline::ToggleOutline,
135                                cx,
136                            )
137                        }
138                    }),
139            ),
140            None => element
141                // Match the height and padding of the `ButtonLike` in the other arm.
142                .h(rems_from_px(22.))
143                .pl_1()
144                .child(breadcrumbs_stack),
145        }
146    }
147}
148
149impl ToolbarItemView for Breadcrumbs {
150    fn set_active_pane_item(
151        &mut self,
152        active_pane_item: Option<&dyn ItemHandle>,
153        window: &mut Window,
154        cx: &mut Context<Self>,
155    ) -> ToolbarItemLocation {
156        cx.notify();
157        self.active_item = None;
158
159        let Some(item) = active_pane_item else {
160            return ToolbarItemLocation::Hidden;
161        };
162
163        let this = cx.entity().downgrade();
164        self.subscription = Some(item.subscribe_to_item_events(
165            window,
166            cx,
167            Box::new(move |event, _, cx| {
168                if let ItemEvent::UpdateBreadcrumbs = event {
169                    this.update(cx, |this, cx| {
170                        cx.notify();
171                        if let Some(active_item) = this.active_item.as_ref() {
172                            cx.emit(ToolbarItemEvent::ChangeLocation(
173                                active_item.breadcrumb_location(cx),
174                            ))
175                        }
176                    })
177                    .ok();
178                }
179            }),
180        ));
181        self.active_item = Some(item.boxed_clone());
182        item.breadcrumb_location(cx)
183    }
184
185    fn pane_focus_update(
186        &mut self,
187        pane_focused: bool,
188        _window: &mut Window,
189        _: &mut Context<Self>,
190    ) {
191        self.pane_focused = pane_focused;
192    }
193}
194
195fn apply_dirty_filename_style(
196    segment: &BreadcrumbText,
197    text_style: &gpui::TextStyle,
198    cx: &mut Context<Breadcrumbs>,
199) -> Option<gpui::AnyElement> {
200    let text = segment.text.replace('\n', "");
201
202    let filename_position = std::path::Path::new(&segment.text)
203        .file_name()
204        .and_then(|f| {
205            let filename_str = f.to_string_lossy();
206            segment.text.rfind(filename_str.as_ref())
207        })?;
208
209    let bold_weight = FontWeight::BOLD;
210    let default_color = Color::Default.color(cx);
211
212    if filename_position == 0 {
213        let mut filename_style = text_style.clone();
214        filename_style.font_weight = bold_weight;
215        filename_style.color = default_color;
216
217        return Some(
218            StyledText::new(text)
219                .with_default_highlights(&filename_style, [])
220                .into_any(),
221        );
222    }
223
224    let highlight_style = gpui::HighlightStyle {
225        font_weight: Some(bold_weight),
226        color: Some(default_color),
227        ..Default::default()
228    };
229
230    let highlight = vec![(filename_position..text.len(), highlight_style)];
231    Some(
232        StyledText::new(text)
233            .with_default_highlights(text_style, highlight)
234            .into_any(),
235    )
236}