1use auto_update::{AutoUpdateStatus, AutoUpdater, DismissErrorMessage};
2use editor::Editor;
3use futures::StreamExt;
4use gpui::{
5 actions, svg, AppContext, CursorStyle, EventEmitter, InteractiveElement as _, Model,
6 ParentElement as _, Render, SharedString, StatefulInteractiveElement, Styled, View,
7 ViewContext, VisualContext as _,
8};
9use language::{LanguageRegistry, LanguageServerBinaryStatus};
10use project::{LanguageServerProgress, Project};
11use smallvec::SmallVec;
12use std::{cmp::Reverse, fmt::Write, sync::Arc};
13use ui::prelude::*;
14use util::ResultExt;
15use workspace::{item::ItemHandle, StatusItemView, Workspace};
16
17actions!(activity_indicator, [ShowErrorMessage]);
18
19const DOWNLOAD_ICON: &str = "icons/download.svg";
20const WARNING_ICON: &str = "icons/warning.svg";
21
22pub enum Event {
23 ShowError { lsp_name: Arc<str>, error: String },
24}
25
26pub struct ActivityIndicator {
27 statuses: Vec<LspStatus>,
28 project: Model<Project>,
29 auto_updater: Option<Model<AutoUpdater>>,
30}
31
32struct LspStatus {
33 name: Arc<str>,
34 status: LanguageServerBinaryStatus,
35}
36
37struct PendingWork<'a> {
38 language_server_name: &'a str,
39 progress_token: &'a str,
40 progress: &'a LanguageServerProgress,
41}
42
43#[derive(Default)]
44struct Content {
45 icon: Option<&'static str>,
46 message: String,
47 on_click: Option<Arc<dyn Fn(&mut ActivityIndicator, &mut ViewContext<ActivityIndicator>)>>,
48}
49
50impl ActivityIndicator {
51 pub fn new(
52 workspace: &mut Workspace,
53 languages: Arc<LanguageRegistry>,
54 cx: &mut ViewContext<Workspace>,
55 ) -> View<ActivityIndicator> {
56 let project = workspace.project().clone();
57 let auto_updater = AutoUpdater::get(cx);
58 let this = cx.new_view(|cx: &mut ViewContext<Self>| {
59 let mut status_events = languages.language_server_binary_statuses();
60 cx.spawn(|this, mut cx| async move {
61 while let Some((language, event)) = status_events.next().await {
62 this.update(&mut cx, |this, cx| {
63 this.statuses.retain(|s| s.name != language.name());
64 this.statuses.push(LspStatus {
65 name: language.name(),
66 status: event,
67 });
68 cx.notify();
69 })?;
70 }
71 anyhow::Ok(())
72 })
73 .detach();
74 cx.observe(&project, |_, _, cx| cx.notify()).detach();
75
76 if let Some(auto_updater) = auto_updater.as_ref() {
77 cx.observe(auto_updater, |_, _, cx| cx.notify()).detach();
78 }
79
80 Self {
81 statuses: Default::default(),
82 project: project.clone(),
83 auto_updater,
84 }
85 });
86
87 cx.subscribe(&this, move |workspace, _, event, cx| match event {
88 Event::ShowError { lsp_name, error } => {
89 if let Some(buffer) = project
90 .update(cx, |project, cx| project.create_buffer(error, None, cx))
91 .log_err()
92 {
93 buffer.update(cx, |buffer, cx| {
94 buffer.edit(
95 [(0..0, format!("Language server error: {}\n\n", lsp_name))],
96 None,
97 cx,
98 );
99 });
100 workspace.add_item(
101 Box::new(
102 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
103 ),
104 cx,
105 );
106 }
107 }
108 })
109 .detach();
110 this
111 }
112
113 fn show_error_message(&mut self, _: &ShowErrorMessage, cx: &mut ViewContext<Self>) {
114 self.statuses.retain(|status| {
115 if let LanguageServerBinaryStatus::Failed { error } = &status.status {
116 cx.emit(Event::ShowError {
117 lsp_name: status.name.clone(),
118 error: error.clone(),
119 });
120 false
121 } else {
122 true
123 }
124 });
125
126 cx.notify();
127 }
128
129 fn dismiss_error_message(&mut self, _: &DismissErrorMessage, cx: &mut ViewContext<Self>) {
130 if let Some(updater) = &self.auto_updater {
131 updater.update(cx, |updater, cx| {
132 updater.dismiss_error(cx);
133 });
134 }
135 cx.notify();
136 }
137
138 fn pending_language_server_work<'a>(
139 &self,
140 cx: &'a AppContext,
141 ) -> impl Iterator<Item = PendingWork<'a>> {
142 self.project
143 .read(cx)
144 .language_server_statuses()
145 .rev()
146 .filter_map(|status| {
147 if status.pending_work.is_empty() {
148 None
149 } else {
150 let mut pending_work = status
151 .pending_work
152 .iter()
153 .map(|(token, progress)| PendingWork {
154 language_server_name: status.name.as_str(),
155 progress_token: token.as_str(),
156 progress,
157 })
158 .collect::<SmallVec<[_; 4]>>();
159 pending_work.sort_by_key(|work| Reverse(work.progress.last_update_at));
160 Some(pending_work)
161 }
162 })
163 .flatten()
164 }
165
166 fn content_to_render(&mut self, cx: &mut ViewContext<Self>) -> Content {
167 // Show any language server has pending activity.
168 let mut pending_work = self.pending_language_server_work(cx);
169 if let Some(PendingWork {
170 language_server_name,
171 progress_token,
172 progress,
173 }) = pending_work.next()
174 {
175 let mut message = language_server_name.to_string();
176
177 message.push_str(": ");
178 if let Some(progress_message) = progress.message.as_ref() {
179 message.push_str(progress_message);
180 } else {
181 message.push_str(progress_token);
182 }
183
184 if let Some(percentage) = progress.percentage {
185 write!(&mut message, " ({}%)", percentage).unwrap();
186 }
187
188 let additional_work_count = pending_work.count();
189 if additional_work_count > 0 {
190 write!(&mut message, " + {} more", additional_work_count).unwrap();
191 }
192
193 return Content {
194 icon: None,
195 message,
196 on_click: None,
197 };
198 }
199
200 // Show any language server installation info.
201 let mut downloading = SmallVec::<[_; 3]>::new();
202 let mut checking_for_update = SmallVec::<[_; 3]>::new();
203 let mut failed = SmallVec::<[_; 3]>::new();
204 for status in &self.statuses {
205 let name = status.name.clone();
206 match status.status {
207 LanguageServerBinaryStatus::CheckingForUpdate => checking_for_update.push(name),
208 LanguageServerBinaryStatus::Downloading => downloading.push(name),
209 LanguageServerBinaryStatus::Failed { .. } => failed.push(name),
210 LanguageServerBinaryStatus::Downloaded | LanguageServerBinaryStatus::Cached => {}
211 }
212 }
213
214 if !downloading.is_empty() {
215 return Content {
216 icon: Some(DOWNLOAD_ICON),
217 message: format!(
218 "Downloading {} language server{}...",
219 downloading.join(", "),
220 if downloading.len() > 1 { "s" } else { "" }
221 ),
222 on_click: None,
223 };
224 } else if !checking_for_update.is_empty() {
225 return Content {
226 icon: Some(DOWNLOAD_ICON),
227 message: format!(
228 "Checking for updates to {} language server{}...",
229 checking_for_update.join(", "),
230 if checking_for_update.len() > 1 {
231 "s"
232 } else {
233 ""
234 }
235 ),
236 on_click: None,
237 };
238 } else if !failed.is_empty() {
239 return Content {
240 icon: Some(WARNING_ICON),
241 message: format!(
242 "Failed to download {} language server{}. Click to show error.",
243 failed.join(", "),
244 if failed.len() > 1 { "s" } else { "" }
245 ),
246 on_click: Some(Arc::new(|this, cx| {
247 this.show_error_message(&Default::default(), cx)
248 })),
249 };
250 }
251
252 // Show any application auto-update info.
253 if let Some(updater) = &self.auto_updater {
254 return match &updater.read(cx).status() {
255 AutoUpdateStatus::Checking => Content {
256 icon: Some(DOWNLOAD_ICON),
257 message: "Checking for Zed updates…".to_string(),
258 on_click: None,
259 },
260 AutoUpdateStatus::Downloading => Content {
261 icon: Some(DOWNLOAD_ICON),
262 message: "Downloading Zed update…".to_string(),
263 on_click: None,
264 },
265 AutoUpdateStatus::Installing => Content {
266 icon: Some(DOWNLOAD_ICON),
267 message: "Installing Zed update…".to_string(),
268 on_click: None,
269 },
270 AutoUpdateStatus::Updated => Content {
271 icon: None,
272 message: "Click to restart and update Zed".to_string(),
273 on_click: Some(Arc::new(|_, cx| {
274 workspace::restart(&Default::default(), cx)
275 })),
276 },
277 AutoUpdateStatus::Errored => Content {
278 icon: Some(WARNING_ICON),
279 message: "Auto update failed".to_string(),
280 on_click: Some(Arc::new(|this, cx| {
281 this.dismiss_error_message(&Default::default(), cx)
282 })),
283 },
284 AutoUpdateStatus::Idle => Default::default(),
285 };
286 }
287
288 Default::default()
289 }
290}
291
292impl EventEmitter<Event> for ActivityIndicator {}
293
294impl Render for ActivityIndicator {
295 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
296 let content = self.content_to_render(cx);
297
298 let mut result = h_flex()
299 .id("activity-indicator")
300 .on_action(cx.listener(Self::show_error_message))
301 .on_action(cx.listener(Self::dismiss_error_message));
302
303 if let Some(on_click) = content.on_click {
304 result = result
305 .cursor(CursorStyle::PointingHand)
306 .on_click(cx.listener(move |this, _, cx| {
307 on_click(this, cx);
308 }))
309 }
310
311 result
312 .children(content.icon.map(|icon| svg().path(icon)))
313 .child(Label::new(SharedString::from(content.message)).size(LabelSize::Small))
314 }
315}
316
317impl StatusItemView for ActivityIndicator {
318 fn set_active_pane_item(&mut self, _: Option<&dyn ItemHandle>, _: &mut ViewContext<Self>) {}
319}