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