1use std::collections::HashSet;
2use std::sync::OnceLock;
3use std::sync::atomic::{AtomicUsize, Ordering};
4
5use db::kvp::KEY_VALUE_STORE;
6use gpui::{App, EntityId, EventEmitter, Subscription};
7use ui::{IconButtonShape, Tooltip, prelude::*};
8use workspace::item::{ItemBufferKind, 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.buffer_kind(cx) == ItemBufferKind::Singleton
83 || active_pane_item.breadcrumbs(cx.theme(), cx).is_none()
84 || !active_pane_item.can_save(cx)
85 {
86 return ToolbarItemLocation::Hidden;
87 }
88
89 if self.shown_on.insert(active_pane_item.item_id()) {
90 Self::increment_count(cx);
91 }
92
93 ToolbarItemLocation::Secondary
94 }
95}
96
97impl EventEmitter<ToolbarItemEvent> for MultibufferHint {}
98
99impl ToolbarItemView for MultibufferHint {
100 fn set_active_pane_item(
101 &mut self,
102 active_pane_item: Option<&dyn ItemHandle>,
103 window: &mut Window,
104 cx: &mut Context<Self>,
105 ) -> ToolbarItemLocation {
106 cx.notify();
107 self.active_item = active_pane_item.map(|item| item.boxed_clone());
108
109 let Some(active_pane_item) = active_pane_item else {
110 return ToolbarItemLocation::Hidden;
111 };
112
113 let this = cx.entity().downgrade();
114 self.subscription = Some(active_pane_item.subscribe_to_item_events(
115 window,
116 cx,
117 Box::new(move |event, _, cx| {
118 if let ItemEvent::UpdateBreadcrumbs = event {
119 this.update(cx, |this, cx| {
120 cx.notify();
121 let location = this.determine_toolbar_location(cx);
122 cx.emit(ToolbarItemEvent::ChangeLocation(location))
123 })
124 .ok();
125 }
126 }),
127 ));
128
129 self.determine_toolbar_location(cx)
130 }
131}
132
133impl Render for MultibufferHint {
134 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
135 h_flex()
136 .px_2()
137 .py_0p5()
138 .justify_between()
139 .bg(cx.theme().status().info_background.opacity(0.5))
140 .border_1()
141 .border_color(cx.theme().colors().border_variant)
142 .rounded_sm()
143 .overflow_hidden()
144 .child(
145 h_flex()
146 .gap_0p5()
147 .child(
148 h_flex()
149 .gap_2()
150 .child(
151 Icon::new(IconName::Info)
152 .size(IconSize::XSmall)
153 .color(Color::Muted),
154 )
155 .child(Label::new(
156 "Edit and save files directly in the results multibuffer!",
157 )),
158 )
159 .child(
160 Button::new("open_docs", "Learn More")
161 .icon(IconName::ArrowUpRight)
162 .icon_size(IconSize::Small)
163 .icon_color(Color::Muted)
164 .icon_position(IconPosition::End)
165 .on_click(move |_event, _, cx| {
166 cx.open_url("https://zed.dev/docs/multibuffers")
167 }),
168 ),
169 )
170 .child(
171 IconButton::new("dismiss", IconName::Close)
172 .shape(IconButtonShape::Square)
173 .icon_size(IconSize::Small)
174 .on_click(cx.listener(|this, _event, _, cx| {
175 this.dismiss(cx);
176 cx.emit(ToolbarItemEvent::ChangeLocation(
177 ToolbarItemLocation::Hidden,
178 ))
179 }))
180 .tooltip(Tooltip::text("Dismiss Hint")),
181 )
182 .into_any_element()
183 }
184}