multibuffer_hint.rs

  1use std::collections::HashSet;
  2use std::sync::atomic::{AtomicUsize, Ordering};
  3use std::sync::OnceLock;
  4
  5use db::kvp::KEY_VALUE_STORE;
  6use gpui::{App, EntityId, EventEmitter, Subscription};
  7use ui::{prelude::*, IconButtonShape, Tooltip};
  8use workspace::item::{ItemEvent, ItemHandle};
  9use workspace::{ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView};
 10
 11pub struct MultibufferHint {
 12    shown_on: HashSet<EntityId>,
 13    active_item: Option<Box<dyn ItemHandle>>,
 14    subscription: Option<Subscription>,
 15}
 16
 17const NUMBER_OF_HINTS: usize = 10;
 18
 19const SHOWN_COUNT_KEY: &str = "MULTIBUFFER_HINT_SHOWN_COUNT";
 20
 21impl Default for MultibufferHint {
 22    fn default() -> Self {
 23        Self::new()
 24    }
 25}
 26
 27impl MultibufferHint {
 28    pub fn new() -> Self {
 29        Self {
 30            shown_on: Default::default(),
 31            active_item: None,
 32            subscription: None,
 33        }
 34    }
 35}
 36
 37impl MultibufferHint {
 38    fn counter() -> &'static AtomicUsize {
 39        static SHOWN_COUNT: OnceLock<AtomicUsize> = OnceLock::new();
 40        SHOWN_COUNT.get_or_init(|| {
 41            let value: usize = KEY_VALUE_STORE
 42                .read_kvp(SHOWN_COUNT_KEY)
 43                .ok()
 44                .flatten()
 45                .and_then(|v| v.parse().ok())
 46                .unwrap_or(0);
 47
 48            AtomicUsize::new(value)
 49        })
 50    }
 51
 52    fn shown_count() -> usize {
 53        Self::counter().load(Ordering::Relaxed)
 54    }
 55
 56    fn increment_count(cx: &mut App) {
 57        Self::set_count(Self::shown_count() + 1, cx)
 58    }
 59
 60    pub(crate) fn set_count(count: usize, cx: &mut App) {
 61        Self::counter().store(count, Ordering::Relaxed);
 62
 63        db::write_and_log(cx, move || {
 64            KEY_VALUE_STORE.write_kvp(SHOWN_COUNT_KEY.to_string(), format!("{}", count))
 65        });
 66    }
 67
 68    fn dismiss(&mut self, cx: &mut App) {
 69        Self::set_count(NUMBER_OF_HINTS, cx)
 70    }
 71
 72    /// Determines the toolbar location for this [`MultibufferHint`].
 73    fn determine_toolbar_location(&mut self, cx: &mut Context<Self>) -> ToolbarItemLocation {
 74        if Self::shown_count() >= NUMBER_OF_HINTS {
 75            return ToolbarItemLocation::Hidden;
 76        }
 77
 78        let Some(active_pane_item) = self.active_item.as_ref() else {
 79            return ToolbarItemLocation::Hidden;
 80        };
 81
 82        if active_pane_item.is_singleton(cx)
 83            || active_pane_item.breadcrumbs(cx.theme(), cx).is_none()
 84        {
 85            return ToolbarItemLocation::Hidden;
 86        }
 87
 88        if self.shown_on.insert(active_pane_item.item_id()) {
 89            Self::increment_count(cx);
 90        }
 91
 92        ToolbarItemLocation::Secondary
 93    }
 94}
 95
 96impl EventEmitter<ToolbarItemEvent> for MultibufferHint {}
 97
 98impl ToolbarItemView for MultibufferHint {
 99    fn set_active_pane_item(
100        &mut self,
101        active_pane_item: Option<&dyn ItemHandle>,
102        window: &mut Window,
103        cx: &mut Context<Self>,
104    ) -> ToolbarItemLocation {
105        cx.notify();
106        self.active_item = active_pane_item.map(|item| item.boxed_clone());
107
108        let Some(active_pane_item) = active_pane_item else {
109            return ToolbarItemLocation::Hidden;
110        };
111
112        let this = cx.entity().downgrade();
113        self.subscription = Some(active_pane_item.subscribe_to_item_events(
114            window,
115            cx,
116            Box::new(move |event, _, cx| {
117                if let ItemEvent::UpdateBreadcrumbs = event {
118                    this.update(cx, |this, cx| {
119                        cx.notify();
120                        let location = this.determine_toolbar_location(cx);
121                        cx.emit(ToolbarItemEvent::ChangeLocation(location))
122                    })
123                    .ok();
124                }
125            }),
126        ));
127
128        self.determine_toolbar_location(cx)
129    }
130}
131
132impl Render for MultibufferHint {
133    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
134        h_flex()
135            .px_2()
136            .py_0p5()
137            .justify_between()
138            .bg(cx.theme().status().info_background.opacity(0.5))
139            .border_1()
140            .border_color(cx.theme().colors().border_variant)
141            .rounded_sm()
142            .overflow_hidden()
143            .child(
144                h_flex()
145                    .gap_0p5()
146                    .child(
147                        h_flex()
148                            .gap_2()
149                            .child(
150                                Icon::new(IconName::Info)
151                                    .size(IconSize::XSmall)
152                                    .color(Color::Muted),
153                            )
154                            .child(Label::new(
155                                "Edit and save files directly in the results multibuffer!",
156                            )),
157                    )
158                    .child(
159                        Button::new("open_docs", "Learn More")
160                            .icon(IconName::ArrowUpRight)
161                            .icon_size(IconSize::XSmall)
162                            .icon_color(Color::Muted)
163                            .icon_position(IconPosition::End)
164                            .on_click(move |_event, _, cx| {
165                                cx.open_url("https://zed.dev/docs/multibuffers")
166                            }),
167                    ),
168            )
169            .child(
170                IconButton::new("dismiss", IconName::Close)
171                    .shape(IconButtonShape::Square)
172                    .icon_size(IconSize::Small)
173                    .on_click(cx.listener(|this, _event, _, cx| {
174                        this.dismiss(cx);
175                        cx.emit(ToolbarItemEvent::ChangeLocation(
176                            ToolbarItemLocation::Hidden,
177                        ))
178                    }))
179                    .tooltip(Tooltip::text("Dismiss Hint")),
180            )
181            .into_any_element()
182    }
183}