inline_completion_button.rs

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