1use anyhow::Result;
2use copilot::{Copilot, Status};
3use editor::{scroll::Autoscroll, Editor};
4use fs::Fs;
5use gpui::{
6 div, Action, AnchorCorner, AppContext, AsyncWindowContext, Entity, IntoElement, ParentElement,
7 Render, Subscription, View, ViewContext, WeakView, WindowContext,
8};
9use language::{
10 language_settings::{
11 self, all_language_settings, AllLanguageSettings, InlineCompletionProvider,
12 },
13 File, Language,
14};
15use settings::{update_settings_file, Settings, SettingsStore};
16use std::{path::Path, sync::Arc};
17use supermaven::{AccountStatus, Supermaven};
18use workspace::{
19 create_and_open_local_file,
20 item::ItemHandle,
21 notifications::NotificationId,
22 ui::{
23 ButtonCommon, Clickable, ContextMenu, IconButton, IconName, IconSize, PopoverMenu, Tooltip,
24 },
25 StatusItemView, Toast, Workspace,
26};
27use zed_actions::OpenBrowser;
28
29const COPILOT_SETTINGS_URL: &str = "https://github.com/settings/copilot";
30
31struct CopilotErrorToast;
32
33pub struct InlineCompletionButton {
34 editor_subscription: Option<(Subscription, usize)>,
35 editor_enabled: Option<bool>,
36 language: Option<Arc<Language>>,
37 file: Option<Arc<dyn File>>,
38 fs: Arc<dyn Fs>,
39}
40
41enum SupermavenButtonStatus {
42 Ready,
43 Errored(String),
44 NeedsActivation(String),
45 Initializing,
46}
47
48impl Render for InlineCompletionButton {
49 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
50 let all_language_settings = all_language_settings(None, cx);
51
52 match all_language_settings.inline_completions.provider {
53 InlineCompletionProvider::None => div(),
54
55 InlineCompletionProvider::Copilot => {
56 let Some(copilot) = Copilot::global(cx) else {
57 return div();
58 };
59 let status = copilot.read(cx).status();
60
61 let enabled = self.editor_enabled.unwrap_or_else(|| {
62 all_language_settings.inline_completions_enabled(None, None, cx)
63 });
64
65 let icon = match status {
66 Status::Error(_) => IconName::CopilotError,
67 Status::Authorized => {
68 if enabled {
69 IconName::Copilot
70 } else {
71 IconName::CopilotDisabled
72 }
73 }
74 _ => IconName::CopilotInit,
75 };
76
77 if let Status::Error(e) = status {
78 return div().child(
79 IconButton::new("copilot-error", icon)
80 .icon_size(IconSize::Small)
81 .on_click(cx.listener(move |_, _, cx| {
82 if let Some(workspace) = cx.window_handle().downcast::<Workspace>()
83 {
84 workspace
85 .update(cx, |workspace, cx| {
86 workspace.show_toast(
87 Toast::new(
88 NotificationId::unique::<CopilotErrorToast>(),
89 format!("Copilot can't be started: {}", e),
90 )
91 .on_click("Reinstall Copilot", |cx| {
92 if let Some(copilot) = Copilot::global(cx) {
93 copilot
94 .update(cx, |copilot, cx| {
95 copilot.reinstall(cx)
96 })
97 .detach();
98 }
99 }),
100 cx,
101 );
102 })
103 .ok();
104 }
105 }))
106 .tooltip(|cx| Tooltip::text("GitHub Copilot", cx)),
107 );
108 }
109 let this = cx.view().clone();
110
111 div().child(
112 PopoverMenu::new("copilot")
113 .menu(move |cx| {
114 Some(match status {
115 Status::Authorized => {
116 this.update(cx, |this, cx| this.build_copilot_context_menu(cx))
117 }
118 _ => this.update(cx, |this, cx| this.build_copilot_start_menu(cx)),
119 })
120 })
121 .anchor(AnchorCorner::BottomRight)
122 .trigger(
123 IconButton::new("copilot-icon", icon)
124 .tooltip(|cx| Tooltip::text("GitHub Copilot", cx)),
125 ),
126 )
127 }
128
129 InlineCompletionProvider::Supermaven => {
130 let Some(supermaven) = Supermaven::global(cx) else {
131 return div();
132 };
133
134 let supermaven = supermaven.read(cx);
135
136 let status = match supermaven {
137 Supermaven::Starting => SupermavenButtonStatus::Initializing,
138 Supermaven::FailedDownload { error } => {
139 SupermavenButtonStatus::Errored(error.to_string())
140 }
141 Supermaven::Spawned(agent) => {
142 let account_status = agent.account_status.clone();
143 match account_status {
144 AccountStatus::NeedsActivation { activate_url } => {
145 SupermavenButtonStatus::NeedsActivation(activate_url.clone())
146 }
147 AccountStatus::Unknown => SupermavenButtonStatus::Initializing,
148 AccountStatus::Ready => SupermavenButtonStatus::Ready,
149 }
150 }
151 Supermaven::Error { error } => {
152 SupermavenButtonStatus::Errored(error.to_string())
153 }
154 };
155
156 let icon = status.to_icon();
157 let tooltip_text = status.to_tooltip();
158 let this = cx.view().clone();
159 let fs = self.fs.clone();
160
161 return div().child(
162 PopoverMenu::new("supermaven")
163 .menu(move |cx| match &status {
164 SupermavenButtonStatus::NeedsActivation(activate_url) => {
165 Some(ContextMenu::build(cx, |menu, _| {
166 let fs = fs.clone();
167 let activate_url = activate_url.clone();
168 menu.entry("Sign In", None, move |cx| {
169 cx.open_url(activate_url.as_str())
170 })
171 .entry(
172 "Use Copilot",
173 None,
174 move |cx| {
175 set_completion_provider(
176 fs.clone(),
177 cx,
178 InlineCompletionProvider::Copilot,
179 )
180 },
181 )
182 }))
183 }
184 SupermavenButtonStatus::Ready => Some(
185 this.update(cx, |this, cx| this.build_supermaven_context_menu(cx)),
186 ),
187 _ => None,
188 })
189 .anchor(AnchorCorner::BottomRight)
190 .trigger(
191 IconButton::new("supermaven-icon", icon)
192 .tooltip(move |cx| Tooltip::text(tooltip_text.clone(), cx)),
193 ),
194 );
195 }
196 }
197 }
198}
199
200impl InlineCompletionButton {
201 pub fn new(fs: Arc<dyn Fs>, cx: &mut ViewContext<Self>) -> Self {
202 if let Some(copilot) = Copilot::global(cx) {
203 cx.observe(&copilot, |_, _, cx| cx.notify()).detach()
204 }
205
206 cx.observe_global::<SettingsStore>(move |_, cx| cx.notify())
207 .detach();
208
209 Self {
210 editor_subscription: None,
211 editor_enabled: None,
212 language: None,
213 file: None,
214 fs,
215 }
216 }
217
218 pub fn build_copilot_start_menu(&mut self, cx: &mut ViewContext<Self>) -> View<ContextMenu> {
219 let fs = self.fs.clone();
220 ContextMenu::build(cx, |menu, _| {
221 menu.entry("Sign In", None, copilot::initiate_sign_in)
222 .entry("Disable Copilot", None, {
223 let fs = fs.clone();
224 move |cx| hide_copilot(fs.clone(), cx)
225 })
226 .entry("Use Supermaven", None, {
227 let fs = fs.clone();
228 move |cx| {
229 set_completion_provider(
230 fs.clone(),
231 cx,
232 InlineCompletionProvider::Supermaven,
233 )
234 }
235 })
236 })
237 }
238
239 pub fn build_language_settings_menu(
240 &self,
241 mut menu: ContextMenu,
242 cx: &mut WindowContext,
243 ) -> ContextMenu {
244 let fs = self.fs.clone();
245
246 if let Some(language) = self.language.clone() {
247 let fs = fs.clone();
248 let language_enabled =
249 language_settings::language_settings(Some(language.name()), None, cx)
250 .show_inline_completions;
251
252 menu = menu.entry(
253 format!(
254 "{} Inline Completions for {}",
255 if language_enabled { "Hide" } else { "Show" },
256 language.name()
257 ),
258 None,
259 move |cx| toggle_inline_completions_for_language(language.clone(), fs.clone(), cx),
260 );
261 }
262
263 let settings = AllLanguageSettings::get_global(cx);
264
265 if let Some(file) = &self.file {
266 let path = file.path().clone();
267 let path_enabled = settings.inline_completions_enabled_for_path(&path);
268
269 menu = menu.entry(
270 format!(
271 "{} Inline Completions for This Path",
272 if path_enabled { "Hide" } else { "Show" }
273 ),
274 None,
275 move |cx| {
276 if let Some(workspace) = cx.window_handle().downcast::<Workspace>() {
277 if let Ok(workspace) = workspace.root_view(cx) {
278 let workspace = workspace.downgrade();
279 cx.spawn(|cx| {
280 configure_disabled_globs(
281 workspace,
282 path_enabled.then_some(path.clone()),
283 cx,
284 )
285 })
286 .detach_and_log_err(cx);
287 }
288 }
289 },
290 );
291 }
292
293 let globally_enabled = settings.inline_completions_enabled(None, None, cx);
294 menu.entry(
295 if globally_enabled {
296 "Hide Inline Completions for All Files"
297 } else {
298 "Show Inline Completions for All Files"
299 },
300 None,
301 move |cx| toggle_inline_completions_globally(fs.clone(), cx),
302 )
303 }
304
305 fn build_copilot_context_menu(&self, cx: &mut ViewContext<Self>) -> View<ContextMenu> {
306 ContextMenu::build(cx, |menu, cx| {
307 self.build_language_settings_menu(menu, cx)
308 .separator()
309 .link(
310 "Go to Copilot Settings",
311 OpenBrowser {
312 url: COPILOT_SETTINGS_URL.to_string(),
313 }
314 .boxed_clone(),
315 )
316 .action("Sign Out", copilot::SignOut.boxed_clone())
317 })
318 }
319
320 fn build_supermaven_context_menu(&self, cx: &mut ViewContext<Self>) -> View<ContextMenu> {
321 ContextMenu::build(cx, |menu, cx| {
322 self.build_language_settings_menu(menu, cx)
323 .separator()
324 .action("Sign Out", supermaven::SignOut.boxed_clone())
325 })
326 }
327
328 pub fn update_enabled(&mut self, editor: View<Editor>, cx: &mut ViewContext<Self>) {
329 let editor = editor.read(cx);
330 let snapshot = editor.buffer().read(cx).snapshot(cx);
331 let suggestion_anchor = editor.selections.newest_anchor().start;
332 let language = snapshot.language_at(suggestion_anchor);
333 let file = snapshot.file_at(suggestion_anchor).cloned();
334 self.editor_enabled = {
335 let file = file.as_ref();
336 Some(
337 file.map(|file| !file.is_private()).unwrap_or(true)
338 && all_language_settings(file, cx).inline_completions_enabled(
339 language,
340 file.map(|file| file.path().as_ref()),
341 cx,
342 ),
343 )
344 };
345 self.language = language.cloned();
346 self.file = file;
347
348 cx.notify()
349 }
350}
351
352impl StatusItemView for InlineCompletionButton {
353 fn set_active_pane_item(&mut self, item: Option<&dyn ItemHandle>, cx: &mut ViewContext<Self>) {
354 if let Some(editor) = item.and_then(|item| item.act_as::<Editor>(cx)) {
355 self.editor_subscription = Some((
356 cx.observe(&editor, Self::update_enabled),
357 editor.entity_id().as_u64() as usize,
358 ));
359 self.update_enabled(editor, cx);
360 } else {
361 self.language = None;
362 self.editor_subscription = None;
363 self.editor_enabled = None;
364 }
365 cx.notify();
366 }
367}
368
369impl SupermavenButtonStatus {
370 fn to_icon(&self) -> IconName {
371 match self {
372 SupermavenButtonStatus::Ready => IconName::Supermaven,
373 SupermavenButtonStatus::Errored(_) => IconName::SupermavenError,
374 SupermavenButtonStatus::NeedsActivation(_) => IconName::SupermavenInit,
375 SupermavenButtonStatus::Initializing => IconName::SupermavenInit,
376 }
377 }
378
379 fn to_tooltip(&self) -> String {
380 match self {
381 SupermavenButtonStatus::Ready => "Supermaven is ready".to_string(),
382 SupermavenButtonStatus::Errored(error) => format!("Supermaven error: {}", error),
383 SupermavenButtonStatus::NeedsActivation(_) => "Supermaven needs activation".to_string(),
384 SupermavenButtonStatus::Initializing => "Supermaven initializing".to_string(),
385 }
386 }
387}
388
389async fn configure_disabled_globs(
390 workspace: WeakView<Workspace>,
391 path_to_disable: Option<Arc<Path>>,
392 mut cx: AsyncWindowContext,
393) -> Result<()> {
394 let settings_editor = workspace
395 .update(&mut cx, |_, cx| {
396 create_and_open_local_file(paths::settings_file(), cx, || {
397 settings::initial_user_settings_content().as_ref().into()
398 })
399 })?
400 .await?
401 .downcast::<Editor>()
402 .unwrap();
403
404 settings_editor.downgrade().update(&mut cx, |item, cx| {
405 let text = item.buffer().read(cx).snapshot(cx).text();
406
407 let settings = cx.global::<SettingsStore>();
408 let edits = settings.edits_for_update::<AllLanguageSettings>(&text, |file| {
409 let copilot = file.inline_completions.get_or_insert_with(Default::default);
410 let globs = copilot.disabled_globs.get_or_insert_with(|| {
411 settings
412 .get::<AllLanguageSettings>(None)
413 .inline_completions
414 .disabled_globs
415 .iter()
416 .map(|glob| glob.glob().to_string())
417 .collect()
418 });
419
420 if let Some(path_to_disable) = &path_to_disable {
421 globs.push(path_to_disable.to_string_lossy().into_owned());
422 } else {
423 globs.clear();
424 }
425 });
426
427 if !edits.is_empty() {
428 item.change_selections(Some(Autoscroll::newest()), cx, |selections| {
429 selections.select_ranges(edits.iter().map(|e| e.0.clone()));
430 });
431
432 // When *enabling* a path, don't actually perform an edit, just select the range.
433 if path_to_disable.is_some() {
434 item.edit(edits.iter().cloned(), cx);
435 }
436 }
437 })?;
438
439 anyhow::Ok(())
440}
441
442fn toggle_inline_completions_globally(fs: Arc<dyn Fs>, cx: &mut AppContext) {
443 let show_inline_completions =
444 all_language_settings(None, cx).inline_completions_enabled(None, None, cx);
445 update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
446 file.defaults.show_inline_completions = Some(!show_inline_completions)
447 });
448}
449
450fn set_completion_provider(
451 fs: Arc<dyn Fs>,
452 cx: &mut AppContext,
453 provider: InlineCompletionProvider,
454) {
455 update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
456 file.features
457 .get_or_insert(Default::default())
458 .inline_completion_provider = Some(provider);
459 });
460}
461
462fn toggle_inline_completions_for_language(
463 language: Arc<Language>,
464 fs: Arc<dyn Fs>,
465 cx: &mut AppContext,
466) {
467 let show_inline_completions =
468 all_language_settings(None, cx).inline_completions_enabled(Some(&language), None, cx);
469 update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
470 file.languages
471 .entry(language.name())
472 .or_default()
473 .show_inline_completions = Some(!show_inline_completions);
474 });
475}
476
477fn hide_copilot(fs: Arc<dyn Fs>, cx: &mut AppContext) {
478 update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
479 file.features
480 .get_or_insert(Default::default())
481 .inline_completion_provider = Some(InlineCompletionProvider::None);
482 });
483}