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                let fs = self.fs.clone();
163
164                return div().child(
165                    PopoverMenu::new("supermaven")
166                        .menu(move |cx| match &status {
167                            SupermavenButtonStatus::NeedsActivation(activate_url) => {
168                                Some(ContextMenu::build(cx, |menu, _| {
169                                    let fs = fs.clone();
170                                    let activate_url = activate_url.clone();
171                                    menu.entry("Sign In", None, move |cx| {
172                                        cx.open_url(activate_url.as_str())
173                                    })
174                                    .entry(
175                                        "Use Copilot",
176                                        None,
177                                        move |cx| {
178                                            set_completion_provider(
179                                                fs.clone(),
180                                                cx,
181                                                InlineCompletionProvider::Copilot,
182                                            )
183                                        },
184                                    )
185                                }))
186                            }
187                            SupermavenButtonStatus::Ready => Some(
188                                this.update(cx, |this, cx| this.build_supermaven_context_menu(cx)),
189                            ),
190                            _ => None,
191                        })
192                        .anchor(AnchorCorner::BottomRight)
193                        .trigger(
194                            IconButton::new("supermaven-icon", icon)
195                                .tooltip(move |cx| Tooltip::text(tooltip_text.clone(), cx)),
196                        ),
197                );
198            }
199        }
200    }
201}
202
203impl InlineCompletionButton {
204    pub fn new(fs: Arc<dyn Fs>, cx: &mut ViewContext<Self>) -> Self {
205        if let Some(copilot) = Copilot::global(cx) {
206            cx.observe(&copilot, |_, _, cx| cx.notify()).detach()
207        }
208
209        cx.observe_global::<SettingsStore>(move |_, cx| cx.notify())
210            .detach();
211
212        Self {
213            editor_subscription: None,
214            editor_enabled: None,
215            language: None,
216            file: None,
217            fs,
218        }
219    }
220
221    pub fn build_copilot_start_menu(&mut self, cx: &mut ViewContext<Self>) -> View<ContextMenu> {
222        let fs = self.fs.clone();
223        ContextMenu::build(cx, |menu, _| {
224            menu.entry("Sign In", None, initiate_sign_in)
225                .entry("Disable Copilot", None, {
226                    let fs = fs.clone();
227                    move |cx| hide_copilot(fs.clone(), cx)
228                })
229                .entry("Use Supermaven", None, {
230                    let fs = fs.clone();
231                    move |cx| {
232                        set_completion_provider(
233                            fs.clone(),
234                            cx,
235                            InlineCompletionProvider::Supermaven,
236                        )
237                    }
238                })
239        })
240    }
241
242    pub fn build_language_settings_menu(
243        &self,
244        mut menu: ContextMenu,
245        cx: &mut WindowContext,
246    ) -> ContextMenu {
247        let fs = self.fs.clone();
248
249        if let Some(language) = self.language.clone() {
250            let fs = fs.clone();
251            let language_enabled = language_settings::language_settings(Some(&language), None, cx)
252                .show_inline_completions;
253
254            menu = menu.entry(
255                format!(
256                    "{} Inline Completions for {}",
257                    if language_enabled { "Hide" } else { "Show" },
258                    language.name()
259                ),
260                None,
261                move |cx| toggle_inline_completions_for_language(language.clone(), fs.clone(), cx),
262            );
263        }
264
265        let settings = AllLanguageSettings::get_global(cx);
266
267        if let Some(file) = &self.file {
268            let path = file.path().clone();
269            let path_enabled = settings.inline_completions_enabled_for_path(&path);
270
271            menu = menu.entry(
272                format!(
273                    "{} Inline Completions for This Path",
274                    if path_enabled { "Hide" } else { "Show" }
275                ),
276                None,
277                move |cx| {
278                    if let Some(workspace) = cx.window_handle().downcast::<Workspace>() {
279                        if let Ok(workspace) = workspace.root_view(cx) {
280                            let workspace = workspace.downgrade();
281                            cx.spawn(|cx| {
282                                configure_disabled_globs(
283                                    workspace,
284                                    path_enabled.then_some(path.clone()),
285                                    cx,
286                                )
287                            })
288                            .detach_and_log_err(cx);
289                        }
290                    }
291                },
292            );
293        }
294
295        let globally_enabled = settings.inline_completions_enabled(None, None);
296        menu.entry(
297            if globally_enabled {
298                "Hide Inline Completions for All Files"
299            } else {
300                "Show Inline Completions for All Files"
301            },
302            None,
303            move |cx| toggle_inline_completions_globally(fs.clone(), cx),
304        )
305    }
306
307    fn build_copilot_context_menu(&self, cx: &mut ViewContext<Self>) -> View<ContextMenu> {
308        ContextMenu::build(cx, |menu, cx| {
309            self.build_language_settings_menu(menu, cx)
310                .separator()
311                .link(
312                    "Go to Copilot Settings",
313                    OpenBrowser {
314                        url: COPILOT_SETTINGS_URL.to_string(),
315                    }
316                    .boxed_clone(),
317                )
318                .action("Sign Out", copilot::SignOut.boxed_clone())
319        })
320    }
321
322    fn build_supermaven_context_menu(&self, cx: &mut ViewContext<Self>) -> View<ContextMenu> {
323        ContextMenu::build(cx, |menu, cx| {
324            self.build_language_settings_menu(menu, cx)
325                .separator()
326                .action("Sign Out", supermaven::SignOut.boxed_clone())
327        })
328    }
329
330    pub fn update_enabled(&mut self, editor: View<Editor>, cx: &mut ViewContext<Self>) {
331        let editor = editor.read(cx);
332        let snapshot = editor.buffer().read(cx).snapshot(cx);
333        let suggestion_anchor = editor.selections.newest_anchor().start;
334        let language = snapshot.language_at(suggestion_anchor);
335        let file = snapshot.file_at(suggestion_anchor).cloned();
336        self.editor_enabled = {
337            let file = file.as_ref();
338            Some(
339                file.map(|file| !file.is_private()).unwrap_or(true)
340                    && all_language_settings(file, cx).inline_completions_enabled(
341                        language,
342                        file.map(|file| file.path().as_ref()),
343                    ),
344            )
345        };
346        self.language = language.cloned();
347        self.file = file;
348
349        cx.notify()
350    }
351}
352
353impl StatusItemView for InlineCompletionButton {
354    fn set_active_pane_item(&mut self, item: Option<&dyn ItemHandle>, cx: &mut ViewContext<Self>) {
355        if let Some(editor) = item.and_then(|item| item.act_as::<Editor>(cx)) {
356            self.editor_subscription = Some((
357                cx.observe(&editor, Self::update_enabled),
358                editor.entity_id().as_u64() as usize,
359            ));
360            self.update_enabled(editor, cx);
361        } else {
362            self.language = None;
363            self.editor_subscription = None;
364            self.editor_enabled = None;
365        }
366        cx.notify();
367    }
368}
369
370impl SupermavenButtonStatus {
371    fn to_icon(&self) -> IconName {
372        match self {
373            SupermavenButtonStatus::Ready => IconName::Supermaven,
374            SupermavenButtonStatus::Errored(_) => IconName::SupermavenError,
375            SupermavenButtonStatus::NeedsActivation(_) => IconName::SupermavenInit,
376            SupermavenButtonStatus::Initializing => IconName::SupermavenInit,
377        }
378    }
379
380    fn to_tooltip(&self) -> String {
381        match self {
382            SupermavenButtonStatus::Ready => "Supermaven is ready".to_string(),
383            SupermavenButtonStatus::Errored(error) => format!("Supermaven error: {}", error),
384            SupermavenButtonStatus::NeedsActivation(_) => "Supermaven needs activation".to_string(),
385            SupermavenButtonStatus::Initializing => "Supermaven initializing".to_string(),
386        }
387    }
388}
389
390async fn configure_disabled_globs(
391    workspace: WeakView<Workspace>,
392    path_to_disable: Option<Arc<Path>>,
393    mut cx: AsyncWindowContext,
394) -> Result<()> {
395    let settings_editor = workspace
396        .update(&mut cx, |_, cx| {
397            create_and_open_local_file(paths::settings_file(), cx, || {
398                settings::initial_user_settings_content().as_ref().into()
399            })
400        })?
401        .await?
402        .downcast::<Editor>()
403        .unwrap();
404
405    settings_editor.downgrade().update(&mut cx, |item, cx| {
406        let text = item.buffer().read(cx).snapshot(cx).text();
407
408        let settings = cx.global::<SettingsStore>();
409        let edits = settings.edits_for_update::<AllLanguageSettings>(&text, |file| {
410            let copilot = file.inline_completions.get_or_insert_with(Default::default);
411            let globs = copilot.disabled_globs.get_or_insert_with(|| {
412                settings
413                    .get::<AllLanguageSettings>(None)
414                    .inline_completions
415                    .disabled_globs
416                    .iter()
417                    .map(|glob| glob.glob().to_string())
418                    .collect()
419            });
420
421            if let Some(path_to_disable) = &path_to_disable {
422                globs.push(path_to_disable.to_string_lossy().into_owned());
423            } else {
424                globs.clear();
425            }
426        });
427
428        if !edits.is_empty() {
429            item.change_selections(Some(Autoscroll::newest()), cx, |selections| {
430                selections.select_ranges(edits.iter().map(|e| e.0.clone()));
431            });
432
433            // When *enabling* a path, don't actually perform an edit, just select the range.
434            if path_to_disable.is_some() {
435                item.edit(edits.iter().cloned(), cx);
436            }
437        }
438    })?;
439
440    anyhow::Ok(())
441}
442
443fn toggle_inline_completions_globally(fs: Arc<dyn Fs>, cx: &mut AppContext) {
444    let show_inline_completions =
445        all_language_settings(None, cx).inline_completions_enabled(None, None);
446    update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
447        file.defaults.show_inline_completions = Some(!show_inline_completions)
448    });
449}
450
451fn set_completion_provider(
452    fs: Arc<dyn Fs>,
453    cx: &mut AppContext,
454    provider: InlineCompletionProvider,
455) {
456    update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
457        file.features
458            .get_or_insert(Default::default())
459            .inline_completion_provider = Some(provider);
460    });
461}
462
463fn toggle_inline_completions_for_language(
464    language: Arc<Language>,
465    fs: Arc<dyn Fs>,
466    cx: &mut AppContext,
467) {
468    let show_inline_completions =
469        all_language_settings(None, cx).inline_completions_enabled(Some(&language), None);
470    update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
471        file.languages
472            .entry(language.name())
473            .or_default()
474            .show_inline_completions = Some(!show_inline_completions);
475    });
476}
477
478fn hide_copilot(fs: Arc<dyn Fs>, cx: &mut AppContext) {
479    update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
480        file.features
481            .get_or_insert(Default::default())
482            .inline_completion_provider = Some(InlineCompletionProvider::None);
483    });
484}
485
486pub fn initiate_sign_in(cx: &mut WindowContext) {
487    let Some(copilot) = Copilot::global(cx) else {
488        return;
489    };
490    let status = copilot.read(cx).status();
491    let Some(workspace) = cx.window_handle().downcast::<Workspace>() else {
492        return;
493    };
494    match status {
495        Status::Starting { task } => {
496            let Some(workspace) = cx.window_handle().downcast::<Workspace>() else {
497                return;
498            };
499
500            let Ok(workspace) = workspace.update(cx, |workspace, cx| {
501                workspace.show_toast(
502                    Toast::new(
503                        NotificationId::unique::<CopilotStartingToast>(),
504                        "Copilot is starting...",
505                    ),
506                    cx,
507                );
508                workspace.weak_handle()
509            }) else {
510                return;
511            };
512
513            cx.spawn(|mut cx| async move {
514                task.await;
515                if let Some(copilot) = cx.update(|cx| Copilot::global(cx)).ok().flatten() {
516                    workspace
517                        .update(&mut cx, |workspace, cx| match copilot.read(cx).status() {
518                            Status::Authorized => workspace.show_toast(
519                                Toast::new(
520                                    NotificationId::unique::<CopilotStartingToast>(),
521                                    "Copilot has started!",
522                                ),
523                                cx,
524                            ),
525                            _ => {
526                                workspace.dismiss_toast(
527                                    &NotificationId::unique::<CopilotStartingToast>(),
528                                    cx,
529                                );
530                                copilot
531                                    .update(cx, |copilot, cx| copilot.sign_in(cx))
532                                    .detach_and_log_err(cx);
533                            }
534                        })
535                        .log_err();
536                }
537            })
538            .detach();
539        }
540        _ => {
541            copilot.update(cx, |this, cx| this.sign_in(cx)).detach();
542            workspace
543                .update(cx, |this, cx| {
544                    this.toggle_modal(cx, |cx| CopilotCodeVerification::new(&copilot, cx));
545                })
546                .ok();
547        }
548    }
549}