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::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                    "Go to 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)
302                .separator()
303                .action("Sign Out", supermaven::SignOut.boxed_clone())
304        })
305    }
306
307    pub fn update_enabled(&mut self, editor: View<Editor>, cx: &mut ViewContext<Self>) {
308        let editor = editor.read(cx);
309        let snapshot = editor.buffer().read(cx).snapshot(cx);
310        let suggestion_anchor = editor.selections.newest_anchor().start;
311        let language = snapshot.language_at(suggestion_anchor);
312        let file = snapshot.file_at(suggestion_anchor).cloned();
313        self.editor_enabled = {
314            let file = file.as_ref();
315            Some(
316                file.map(|file| !file.is_private()).unwrap_or(true)
317                    && all_language_settings(file, cx).inline_completions_enabled(
318                        language,
319                        file.map(|file| file.path().as_ref()),
320                    ),
321            )
322        };
323        self.language = language.cloned();
324        self.file = file;
325
326        cx.notify()
327    }
328}
329
330impl StatusItemView for InlineCompletionButton {
331    fn set_active_pane_item(&mut self, item: Option<&dyn ItemHandle>, cx: &mut ViewContext<Self>) {
332        if let Some(editor) = item.and_then(|item| item.act_as::<Editor>(cx)) {
333            self.editor_subscription = Some((
334                cx.observe(&editor, Self::update_enabled),
335                editor.entity_id().as_u64() as usize,
336            ));
337            self.update_enabled(editor, cx);
338        } else {
339            self.language = None;
340            self.editor_subscription = None;
341            self.editor_enabled = None;
342        }
343        cx.notify();
344    }
345}
346
347impl SupermavenButtonStatus {
348    fn to_icon(&self) -> IconName {
349        match self {
350            SupermavenButtonStatus::Ready => IconName::Supermaven,
351            SupermavenButtonStatus::Errored(_) => IconName::SupermavenError,
352            SupermavenButtonStatus::NeedsActivation(_) => IconName::SupermavenInit,
353            SupermavenButtonStatus::Initializing => IconName::SupermavenInit,
354        }
355    }
356
357    fn to_tooltip(&self) -> String {
358        match self {
359            SupermavenButtonStatus::Ready => "Supermaven is ready".to_string(),
360            SupermavenButtonStatus::Errored(error) => format!("Supermaven error: {}", error),
361            SupermavenButtonStatus::NeedsActivation(_) => "Supermaven needs activation".to_string(),
362            SupermavenButtonStatus::Initializing => "Supermaven initializing".to_string(),
363        }
364    }
365}
366
367async fn configure_disabled_globs(
368    workspace: WeakView<Workspace>,
369    path_to_disable: Option<Arc<Path>>,
370    mut cx: AsyncWindowContext,
371) -> Result<()> {
372    let settings_editor = workspace
373        .update(&mut cx, |_, cx| {
374            create_and_open_local_file(paths::settings_file(), cx, || {
375                settings::initial_user_settings_content().as_ref().into()
376            })
377        })?
378        .await?
379        .downcast::<Editor>()
380        .unwrap();
381
382    settings_editor.downgrade().update(&mut cx, |item, cx| {
383        let text = item.buffer().read(cx).snapshot(cx).text();
384
385        let settings = cx.global::<SettingsStore>();
386        let edits = settings.edits_for_update::<AllLanguageSettings>(&text, |file| {
387            let copilot = file.inline_completions.get_or_insert_with(Default::default);
388            let globs = copilot.disabled_globs.get_or_insert_with(|| {
389                settings
390                    .get::<AllLanguageSettings>(None)
391                    .inline_completions
392                    .disabled_globs
393                    .iter()
394                    .map(|glob| glob.glob().to_string())
395                    .collect()
396            });
397
398            if let Some(path_to_disable) = &path_to_disable {
399                globs.push(path_to_disable.to_string_lossy().into_owned());
400            } else {
401                globs.clear();
402            }
403        });
404
405        if !edits.is_empty() {
406            item.change_selections(Some(Autoscroll::newest()), cx, |selections| {
407                selections.select_ranges(edits.iter().map(|e| e.0.clone()));
408            });
409
410            // When *enabling* a path, don't actually perform an edit, just select the range.
411            if path_to_disable.is_some() {
412                item.edit(edits.iter().cloned(), cx);
413            }
414        }
415    })?;
416
417    anyhow::Ok(())
418}
419
420fn toggle_inline_completions_globally(fs: Arc<dyn Fs>, cx: &mut AppContext) {
421    let show_inline_completions =
422        all_language_settings(None, cx).inline_completions_enabled(None, None);
423    update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
424        file.defaults.show_inline_completions = Some(!show_inline_completions)
425    });
426}
427
428fn toggle_inline_completions_for_language(
429    language: Arc<Language>,
430    fs: Arc<dyn Fs>,
431    cx: &mut AppContext,
432) {
433    let show_inline_completions =
434        all_language_settings(None, cx).inline_completions_enabled(Some(&language), None);
435    update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
436        file.languages
437            .entry(language.name())
438            .or_default()
439            .show_inline_completions = Some(!show_inline_completions);
440    });
441}
442
443fn hide_copilot(fs: Arc<dyn Fs>, cx: &mut AppContext) {
444    update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
445        file.features
446            .get_or_insert(Default::default())
447            .inline_completion_provider = Some(InlineCompletionProvider::None);
448    });
449}
450
451pub fn initiate_sign_in(cx: &mut WindowContext) {
452    let Some(copilot) = Copilot::global(cx) else {
453        return;
454    };
455    let status = copilot.read(cx).status();
456    let Some(workspace) = cx.window_handle().downcast::<Workspace>() else {
457        return;
458    };
459    match status {
460        Status::Starting { task } => {
461            let Some(workspace) = cx.window_handle().downcast::<Workspace>() else {
462                return;
463            };
464
465            let Ok(workspace) = workspace.update(cx, |workspace, cx| {
466                workspace.show_toast(
467                    Toast::new(
468                        NotificationId::unique::<CopilotStartingToast>(),
469                        "Copilot is starting...",
470                    ),
471                    cx,
472                );
473                workspace.weak_handle()
474            }) else {
475                return;
476            };
477
478            cx.spawn(|mut cx| async move {
479                task.await;
480                if let Some(copilot) = cx.update(|cx| Copilot::global(cx)).ok().flatten() {
481                    workspace
482                        .update(&mut cx, |workspace, cx| match copilot.read(cx).status() {
483                            Status::Authorized => workspace.show_toast(
484                                Toast::new(
485                                    NotificationId::unique::<CopilotStartingToast>(),
486                                    "Copilot has started!",
487                                ),
488                                cx,
489                            ),
490                            _ => {
491                                workspace.dismiss_toast(
492                                    &NotificationId::unique::<CopilotStartingToast>(),
493                                    cx,
494                                );
495                                copilot
496                                    .update(cx, |copilot, cx| copilot.sign_in(cx))
497                                    .detach_and_log_err(cx);
498                            }
499                        })
500                        .log_err();
501                }
502            })
503            .detach();
504        }
505        _ => {
506            copilot.update(cx, |this, cx| this.sign_in(cx)).detach();
507            workspace
508                .update(cx, |this, cx| {
509                    this.toggle_modal(cx, |cx| CopilotCodeVerification::new(&copilot, cx));
510                })
511                .ok();
512        }
513    }
514}