1use editor::Editor;
2use futures::StreamExt;
3use gpui::{
4 actions, elements::*, platform::CursorStyle, AppContext, Entity, EventContext, ModelHandle,
5 MutableAppContext, RenderContext, View, ViewContext, ViewHandle,
6};
7use language::{LanguageRegistry, LanguageServerBinaryStatus};
8use project::{LanguageServerProgress, Project};
9use settings::Settings;
10use smallvec::SmallVec;
11use std::{cmp::Reverse, fmt::Write, sync::Arc};
12use util::ResultExt;
13use workspace::{ItemHandle, StatusItemView, Workspace};
14
15actions!(lsp_status, [ShowErrorMessage]);
16
17pub enum Event {
18 ShowError { lsp_name: Arc<str>, error: String },
19}
20
21pub struct LspStatusItem {
22 statuses: Vec<LspStatus>,
23 project: ModelHandle<Project>,
24}
25
26struct LspStatus {
27 name: Arc<str>,
28 status: LanguageServerBinaryStatus,
29}
30
31pub fn init(cx: &mut MutableAppContext) {
32 cx.add_action(LspStatusItem::show_error_message);
33}
34
35impl LspStatusItem {
36 pub fn new(
37 workspace: &mut Workspace,
38 languages: Arc<LanguageRegistry>,
39 cx: &mut ViewContext<Workspace>,
40 ) -> ViewHandle<LspStatusItem> {
41 let project = workspace.project().clone();
42 let this = cx.add_view(|cx: &mut ViewContext<Self>| {
43 let mut status_events = languages.language_server_binary_statuses();
44 cx.spawn_weak(|this, mut cx| async move {
45 while let Some((language, event)) = status_events.next().await {
46 if let Some(this) = this.upgrade(&cx) {
47 this.update(&mut cx, |this, cx| {
48 this.statuses.retain(|s| s.name != language.name());
49 this.statuses.push(LspStatus {
50 name: language.name(),
51 status: event,
52 });
53 cx.notify();
54 });
55 } else {
56 break;
57 }
58 }
59 })
60 .detach();
61 cx.observe(&project, |_, _, cx| cx.notify()).detach();
62
63 Self {
64 statuses: Default::default(),
65 project: project.clone(),
66 }
67 });
68 cx.subscribe(&this, move |workspace, _, event, cx| match event {
69 Event::ShowError { lsp_name, error } => {
70 if let Some(buffer) = project
71 .update(cx, |project, cx| project.create_buffer(&error, None, cx))
72 .log_err()
73 {
74 buffer.update(cx, |buffer, cx| {
75 buffer.edit(
76 [(0..0, format!("Language server error: {}\n\n", lsp_name))],
77 cx,
78 );
79 });
80 workspace.add_item(
81 Box::new(
82 cx.add_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
83 ),
84 cx,
85 );
86 }
87 }
88 })
89 .detach();
90 this
91 }
92
93 fn show_error_message(&mut self, _: &ShowErrorMessage, cx: &mut ViewContext<Self>) {
94 self.statuses.retain(|status| {
95 if let LanguageServerBinaryStatus::Failed { error } = &status.status {
96 cx.emit(Event::ShowError {
97 lsp_name: status.name.clone(),
98 error: error.clone(),
99 });
100 false
101 } else {
102 true
103 }
104 });
105
106 cx.notify();
107 }
108
109 fn pending_language_server_work<'a>(
110 &self,
111 cx: &'a AppContext,
112 ) -> impl Iterator<Item = (&'a str, &'a str, &'a LanguageServerProgress)> {
113 self.project
114 .read(cx)
115 .language_server_statuses()
116 .rev()
117 .filter_map(|status| {
118 if status.pending_work.is_empty() {
119 None
120 } else {
121 let mut pending_work = status
122 .pending_work
123 .iter()
124 .map(|(token, progress)| (status.name.as_str(), token.as_str(), progress))
125 .collect::<SmallVec<[_; 4]>>();
126 pending_work.sort_by_key(|(_, _, progress)| Reverse(progress.last_update_at));
127 Some(pending_work)
128 }
129 })
130 .flatten()
131 }
132}
133
134impl Entity for LspStatusItem {
135 type Event = Event;
136}
137
138impl View for LspStatusItem {
139 fn ui_name() -> &'static str {
140 "LspStatus"
141 }
142
143 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
144 let mut message;
145 let mut icon = None;
146 let mut handler = None;
147
148 let mut pending_work = self.pending_language_server_work(cx);
149 if let Some((lang_server_name, progress_token, progress)) = pending_work.next() {
150 message = lang_server_name.to_string();
151
152 message.push_str(": ");
153 if let Some(progress_message) = progress.message.as_ref() {
154 message.push_str(progress_message);
155 } else {
156 message.push_str(progress_token);
157 }
158
159 if let Some(percentage) = progress.percentage {
160 write!(&mut message, " ({}%)", percentage).unwrap();
161 }
162
163 let additional_work_count = pending_work.count();
164 if additional_work_count > 0 {
165 write!(&mut message, " + {} more", additional_work_count).unwrap();
166 }
167 } else {
168 drop(pending_work);
169
170 let mut downloading = SmallVec::<[_; 3]>::new();
171 let mut checking_for_update = SmallVec::<[_; 3]>::new();
172 let mut failed = SmallVec::<[_; 3]>::new();
173 for status in &self.statuses {
174 match status.status {
175 LanguageServerBinaryStatus::CheckingForUpdate => {
176 checking_for_update.push(status.name.clone());
177 }
178 LanguageServerBinaryStatus::Downloading => {
179 downloading.push(status.name.clone());
180 }
181 LanguageServerBinaryStatus::Failed { .. } => {
182 failed.push(status.name.clone());
183 }
184 LanguageServerBinaryStatus::Downloaded | LanguageServerBinaryStatus::Cached => {
185 }
186 }
187 }
188
189 if !downloading.is_empty() {
190 icon = Some("icons/download-solid-14.svg");
191 message = format!(
192 "Downloading {} language server{}...",
193 downloading.join(", "),
194 if downloading.len() > 1 { "s" } else { "" }
195 );
196 } else if !checking_for_update.is_empty() {
197 icon = Some("icons/download-solid-14.svg");
198 message = format!(
199 "Checking for updates to {} language server{}...",
200 checking_for_update.join(", "),
201 if checking_for_update.len() > 1 {
202 "s"
203 } else {
204 ""
205 }
206 );
207 } else if !failed.is_empty() {
208 icon = Some("icons/warning-solid-14.svg");
209 message = format!(
210 "Failed to download {} language server{}. Click to show error.",
211 failed.join(", "),
212 if failed.len() > 1 { "s" } else { "" }
213 );
214 handler = Some(|_, _, cx: &mut EventContext| cx.dispatch_action(ShowErrorMessage));
215 } else {
216 return Empty::new().boxed();
217 }
218 }
219
220 let mut element = MouseEventHandler::new::<Self, _, _>(0, cx, |state, cx| {
221 let theme = &cx
222 .global::<Settings>()
223 .theme
224 .workspace
225 .status_bar
226 .lsp_status;
227 let style = if state.hovered && handler.is_some() {
228 theme.hover.as_ref().unwrap_or(&theme.default)
229 } else {
230 &theme.default
231 };
232 Flex::row()
233 .with_children(icon.map(|path| {
234 Svg::new(path)
235 .with_color(style.icon_color)
236 .constrained()
237 .with_width(style.icon_width)
238 .contained()
239 .with_margin_right(style.icon_spacing)
240 .aligned()
241 .named("warning-icon")
242 }))
243 .with_child(Label::new(message, style.message.clone()).aligned().boxed())
244 .constrained()
245 .with_height(style.height)
246 .contained()
247 .with_style(style.container)
248 .aligned()
249 .boxed()
250 });
251
252 if let Some(handler) = handler {
253 element = element
254 .with_cursor_style(CursorStyle::PointingHand)
255 .on_click(handler);
256 }
257
258 element.boxed()
259 }
260}
261
262impl StatusItemView for LspStatusItem {
263 fn set_active_pane_item(&mut self, _: Option<&dyn ItemHandle>, _: &mut ViewContext<Self>) {}
264}