inline_completion_button.rs

  1use anyhow::Result;
  2use client::UserStore;
  3use copilot::{Copilot, Status};
  4use editor::{scroll::Autoscroll, Editor};
  5use feature_flags::{FeatureFlagAppExt, PredictEditsFeatureFlag};
  6use fs::Fs;
  7use gpui::{
  8    actions, div, pulsating_between, Action, Animation, AnimationExt, AppContext,
  9    AsyncWindowContext, Corner, Entity, IntoElement, Model, ParentElement, Render, Subscription,
 10    View, ViewContext, WeakView, WindowContext,
 11};
 12use language::{
 13    language_settings::{
 14        self, all_language_settings, AllLanguageSettings, InlineCompletionProvider,
 15    },
 16    File, Language,
 17};
 18use settings::{update_settings_file, Settings, SettingsStore};
 19use std::{path::Path, sync::Arc, time::Duration};
 20use supermaven::{AccountStatus, Supermaven};
 21use ui::{prelude::*, ButtonLike, Color, Icon, IconWithIndicator, Indicator, PopoverMenuHandle};
 22use workspace::{
 23    create_and_open_local_file,
 24    item::ItemHandle,
 25    notifications::NotificationId,
 26    ui::{
 27        ButtonCommon, Clickable, ContextMenu, IconButton, IconName, IconSize, PopoverMenu, Tooltip,
 28    },
 29    StatusItemView, Toast, Workspace,
 30};
 31use zed_actions::OpenBrowser;
 32use zed_predict_tos::ZedPredictTos;
 33use zeta::RateCompletionModal;
 34
 35actions!(zeta, [RateCompletions]);
 36actions!(inline_completion, [ToggleMenu]);
 37
 38const COPILOT_SETTINGS_URL: &str = "https://github.com/settings/copilot";
 39
 40struct CopilotErrorToast;
 41
 42pub struct InlineCompletionButton {
 43    editor_subscription: Option<(Subscription, usize)>,
 44    editor_enabled: Option<bool>,
 45    language: Option<Arc<Language>>,
 46    file: Option<Arc<dyn File>>,
 47    inline_completion_provider: Option<Arc<dyn inline_completion::InlineCompletionProviderHandle>>,
 48    fs: Arc<dyn Fs>,
 49    workspace: WeakView<Workspace>,
 50    user_store: Model<UserStore>,
 51    popover_menu_handle: PopoverMenuHandle<ContextMenu>,
 52}
 53
 54enum SupermavenButtonStatus {
 55    Ready,
 56    Errored(String),
 57    NeedsActivation(String),
 58    Initializing,
 59}
 60
 61impl Render for InlineCompletionButton {
 62    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
 63        let all_language_settings = all_language_settings(None, cx);
 64
 65        match all_language_settings.inline_completions.provider {
 66            InlineCompletionProvider::None => div(),
 67
 68            InlineCompletionProvider::Copilot => {
 69                let Some(copilot) = Copilot::global(cx) else {
 70                    return div();
 71                };
 72                let status = copilot.read(cx).status();
 73
 74                let enabled = self.editor_enabled.unwrap_or_else(|| {
 75                    all_language_settings.inline_completions_enabled(None, None, cx)
 76                });
 77
 78                let icon = match status {
 79                    Status::Error(_) => IconName::CopilotError,
 80                    Status::Authorized => {
 81                        if enabled {
 82                            IconName::Copilot
 83                        } else {
 84                            IconName::CopilotDisabled
 85                        }
 86                    }
 87                    _ => IconName::CopilotInit,
 88                };
 89
 90                if let Status::Error(e) = status {
 91                    return div().child(
 92                        IconButton::new("copilot-error", icon)
 93                            .icon_size(IconSize::Small)
 94                            .on_click(cx.listener(move |_, _, cx| {
 95                                if let Some(workspace) = cx.window_handle().downcast::<Workspace>()
 96                                {
 97                                    workspace
 98                                        .update(cx, |workspace, cx| {
 99                                            workspace.show_toast(
100                                                Toast::new(
101                                                    NotificationId::unique::<CopilotErrorToast>(),
102                                                    format!("Copilot can't be started: {}", e),
103                                                )
104                                                .on_click("Reinstall Copilot", |cx| {
105                                                    if let Some(copilot) = Copilot::global(cx) {
106                                                        copilot
107                                                            .update(cx, |copilot, cx| {
108                                                                copilot.reinstall(cx)
109                                                            })
110                                                            .detach();
111                                                    }
112                                                }),
113                                                cx,
114                                            );
115                                        })
116                                        .ok();
117                                }
118                            }))
119                            .tooltip(|cx| Tooltip::for_action("GitHub Copilot", &ToggleMenu, cx)),
120                    );
121                }
122                let this = cx.view().clone();
123
124                div().child(
125                    PopoverMenu::new("copilot")
126                        .menu(move |cx| {
127                            Some(match status {
128                                Status::Authorized => {
129                                    this.update(cx, |this, cx| this.build_copilot_context_menu(cx))
130                                }
131                                _ => this.update(cx, |this, cx| this.build_copilot_start_menu(cx)),
132                            })
133                        })
134                        .anchor(Corner::BottomRight)
135                        .trigger(
136                            IconButton::new("copilot-icon", icon).tooltip(|cx| {
137                                Tooltip::for_action("GitHub Copilot", &ToggleMenu, cx)
138                            }),
139                        )
140                        .with_handle(self.popover_menu_handle.clone()),
141                )
142            }
143
144            InlineCompletionProvider::Supermaven => {
145                let Some(supermaven) = Supermaven::global(cx) else {
146                    return div();
147                };
148
149                let supermaven = supermaven.read(cx);
150
151                let status = match supermaven {
152                    Supermaven::Starting => SupermavenButtonStatus::Initializing,
153                    Supermaven::FailedDownload { error } => {
154                        SupermavenButtonStatus::Errored(error.to_string())
155                    }
156                    Supermaven::Spawned(agent) => {
157                        let account_status = agent.account_status.clone();
158                        match account_status {
159                            AccountStatus::NeedsActivation { activate_url } => {
160                                SupermavenButtonStatus::NeedsActivation(activate_url.clone())
161                            }
162                            AccountStatus::Unknown => SupermavenButtonStatus::Initializing,
163                            AccountStatus::Ready => SupermavenButtonStatus::Ready,
164                        }
165                    }
166                    Supermaven::Error { error } => {
167                        SupermavenButtonStatus::Errored(error.to_string())
168                    }
169                };
170
171                let icon = status.to_icon();
172                let tooltip_text = status.to_tooltip();
173                let has_menu = status.has_menu();
174                let this = cx.view().clone();
175                let fs = self.fs.clone();
176
177                return div().child(
178                    PopoverMenu::new("supermaven")
179                        .menu(move |cx| match &status {
180                            SupermavenButtonStatus::NeedsActivation(activate_url) => {
181                                Some(ContextMenu::build(cx, |menu, _| {
182                                    let fs = fs.clone();
183                                    let activate_url = activate_url.clone();
184                                    menu.entry("Sign In", None, move |cx| {
185                                        cx.open_url(activate_url.as_str())
186                                    })
187                                    .entry(
188                                        "Use Copilot",
189                                        None,
190                                        move |cx| {
191                                            set_completion_provider(
192                                                fs.clone(),
193                                                cx,
194                                                InlineCompletionProvider::Copilot,
195                                            )
196                                        },
197                                    )
198                                }))
199                            }
200                            SupermavenButtonStatus::Ready => Some(
201                                this.update(cx, |this, cx| this.build_supermaven_context_menu(cx)),
202                            ),
203                            _ => None,
204                        })
205                        .anchor(Corner::BottomRight)
206                        .trigger(IconButton::new("supermaven-icon", icon).tooltip(move |cx| {
207                            if has_menu {
208                                Tooltip::for_action(tooltip_text.clone(), &ToggleMenu, cx)
209                            } else {
210                                Tooltip::text(tooltip_text.clone(), cx)
211                            }
212                        }))
213                        .with_handle(self.popover_menu_handle.clone()),
214                );
215            }
216
217            InlineCompletionProvider::Zed => {
218                if !cx.has_flag::<PredictEditsFeatureFlag>() {
219                    return div();
220                }
221
222                if !self
223                    .user_store
224                    .read(cx)
225                    .current_user_has_accepted_terms()
226                    .unwrap_or(false)
227                {
228                    let workspace = self.workspace.clone();
229                    let user_store = self.user_store.clone();
230
231                    return div().child(
232                        ButtonLike::new("zeta-pending-tos-icon")
233                            .child(
234                                IconWithIndicator::new(
235                                    Icon::new(IconName::ZedPredict),
236                                    Some(Indicator::dot().color(Color::Error)),
237                                )
238                                .indicator_border_color(Some(
239                                    cx.theme().colors().status_bar_background,
240                                ))
241                                .into_any_element(),
242                            )
243                            .tooltip(|cx| {
244                                Tooltip::with_meta(
245                                    "Edit Predictions",
246                                    None,
247                                    "Read Terms of Service",
248                                    cx,
249                                )
250                            })
251                            .on_click(cx.listener(move |_, _, cx| {
252                                let user_store = user_store.clone();
253
254                                if let Some(workspace) = workspace.upgrade() {
255                                    ZedPredictTos::toggle(workspace, user_store, cx);
256                                }
257                            })),
258                    );
259                }
260
261                let this = cx.view().clone();
262                let button = IconButton::new("zeta", IconName::ZedPredict).when(
263                    !self.popover_menu_handle.is_deployed(),
264                    |button| {
265                        button.tooltip(|cx| Tooltip::for_action("Edit Prediction", &ToggleMenu, cx))
266                    },
267                );
268
269                let is_refreshing = self
270                    .inline_completion_provider
271                    .as_ref()
272                    .map_or(false, |provider| provider.is_refreshing(cx));
273
274                let mut popover_menu = PopoverMenu::new("zeta")
275                    .menu(move |cx| {
276                        Some(this.update(cx, |this, cx| this.build_zeta_context_menu(cx)))
277                    })
278                    .anchor(Corner::BottomRight)
279                    .with_handle(self.popover_menu_handle.clone());
280
281                if is_refreshing {
282                    popover_menu = popover_menu.trigger(
283                        button.with_animation(
284                            "pulsating-label",
285                            Animation::new(Duration::from_secs(2))
286                                .repeat()
287                                .with_easing(pulsating_between(0.2, 1.0)),
288                            |icon_button, delta| icon_button.alpha(delta),
289                        ),
290                    );
291                } else {
292                    popover_menu = popover_menu.trigger(button);
293                }
294
295                div().child(popover_menu.into_any_element())
296            }
297        }
298    }
299}
300
301impl InlineCompletionButton {
302    pub fn new(
303        workspace: WeakView<Workspace>,
304        fs: Arc<dyn Fs>,
305        user_store: Model<UserStore>,
306        popover_menu_handle: PopoverMenuHandle<ContextMenu>,
307        cx: &mut ViewContext<Self>,
308    ) -> Self {
309        if let Some(copilot) = Copilot::global(cx) {
310            cx.observe(&copilot, |_, _, cx| cx.notify()).detach()
311        }
312
313        cx.observe_global::<SettingsStore>(move |_, cx| cx.notify())
314            .detach();
315
316        Self {
317            editor_subscription: None,
318            editor_enabled: None,
319            language: None,
320            file: None,
321            inline_completion_provider: None,
322            popover_menu_handle,
323            workspace,
324            fs,
325            user_store,
326        }
327    }
328
329    pub fn build_copilot_start_menu(&mut self, cx: &mut ViewContext<Self>) -> View<ContextMenu> {
330        let fs = self.fs.clone();
331        ContextMenu::build(cx, |menu, _| {
332            menu.entry("Sign In", None, copilot::initiate_sign_in)
333                .entry("Disable Copilot", None, {
334                    let fs = fs.clone();
335                    move |cx| hide_copilot(fs.clone(), cx)
336                })
337                .entry("Use Supermaven", None, {
338                    let fs = fs.clone();
339                    move |cx| {
340                        set_completion_provider(
341                            fs.clone(),
342                            cx,
343                            InlineCompletionProvider::Supermaven,
344                        )
345                    }
346                })
347        })
348    }
349
350    pub fn build_language_settings_menu(
351        &self,
352        mut menu: ContextMenu,
353        cx: &mut WindowContext,
354    ) -> ContextMenu {
355        let fs = self.fs.clone();
356
357        if let Some(language) = self.language.clone() {
358            let fs = fs.clone();
359            let language_enabled =
360                language_settings::language_settings(Some(language.name()), None, cx)
361                    .show_inline_completions;
362
363            menu = menu.entry(
364                format!(
365                    "{} Inline Completions for {}",
366                    if language_enabled { "Hide" } else { "Show" },
367                    language.name()
368                ),
369                None,
370                move |cx| toggle_inline_completions_for_language(language.clone(), fs.clone(), cx),
371            );
372        }
373
374        let settings = AllLanguageSettings::get_global(cx);
375
376        if let Some(file) = &self.file {
377            let path = file.path().clone();
378            let path_enabled = settings.inline_completions_enabled_for_path(&path);
379
380            menu = menu.entry(
381                format!(
382                    "{} Inline Completions for This Path",
383                    if path_enabled { "Hide" } else { "Show" }
384                ),
385                None,
386                move |cx| {
387                    if let Some(workspace) = cx.window_handle().downcast::<Workspace>() {
388                        if let Ok(workspace) = workspace.root_view(cx) {
389                            let workspace = workspace.downgrade();
390                            cx.spawn(|cx| {
391                                configure_disabled_globs(
392                                    workspace,
393                                    path_enabled.then_some(path.clone()),
394                                    cx,
395                                )
396                            })
397                            .detach_and_log_err(cx);
398                        }
399                    }
400                },
401            );
402        }
403
404        let globally_enabled = settings.inline_completions_enabled(None, None, cx);
405        menu.entry(
406            if globally_enabled {
407                "Hide Inline Completions for All Files"
408            } else {
409                "Show Inline Completions for All Files"
410            },
411            None,
412            move |cx| toggle_inline_completions_globally(fs.clone(), cx),
413        )
414    }
415
416    fn build_copilot_context_menu(&self, cx: &mut ViewContext<Self>) -> View<ContextMenu> {
417        ContextMenu::build(cx, |menu, cx| {
418            self.build_language_settings_menu(menu, cx)
419                .separator()
420                .link(
421                    "Go to Copilot Settings",
422                    OpenBrowser {
423                        url: COPILOT_SETTINGS_URL.to_string(),
424                    }
425                    .boxed_clone(),
426                )
427                .action("Sign Out", copilot::SignOut.boxed_clone())
428        })
429    }
430
431    fn build_supermaven_context_menu(&self, cx: &mut ViewContext<Self>) -> View<ContextMenu> {
432        ContextMenu::build(cx, |menu, cx| {
433            self.build_language_settings_menu(menu, cx)
434                .separator()
435                .action("Sign Out", supermaven::SignOut.boxed_clone())
436        })
437    }
438
439    fn build_zeta_context_menu(&self, cx: &mut ViewContext<Self>) -> View<ContextMenu> {
440        let workspace = self.workspace.clone();
441        ContextMenu::build(cx, |menu, cx| {
442            self.build_language_settings_menu(menu, cx)
443                .separator()
444                .entry(
445                    "Rate Completions",
446                    Some(RateCompletions.boxed_clone()),
447                    move |cx| {
448                        workspace
449                            .update(cx, |workspace, cx| {
450                                RateCompletionModal::toggle(workspace, cx)
451                            })
452                            .ok();
453                    },
454                )
455        })
456    }
457
458    pub fn update_enabled(&mut self, editor: View<Editor>, cx: &mut ViewContext<Self>) {
459        let editor = editor.read(cx);
460        let snapshot = editor.buffer().read(cx).snapshot(cx);
461        let suggestion_anchor = editor.selections.newest_anchor().start;
462        let language = snapshot.language_at(suggestion_anchor);
463        let file = snapshot.file_at(suggestion_anchor).cloned();
464        self.editor_enabled = {
465            let file = file.as_ref();
466            Some(
467                file.map(|file| !file.is_private()).unwrap_or(true)
468                    && all_language_settings(file, cx).inline_completions_enabled(
469                        language,
470                        file.map(|file| file.path().as_ref()),
471                        cx,
472                    ),
473            )
474        };
475        self.inline_completion_provider = editor.inline_completion_provider();
476        self.language = language.cloned();
477        self.file = file;
478
479        cx.notify()
480    }
481
482    pub fn toggle_menu(&mut self, cx: &mut ViewContext<Self>) {
483        self.popover_menu_handle.toggle(cx);
484    }
485}
486
487impl StatusItemView for InlineCompletionButton {
488    fn set_active_pane_item(&mut self, item: Option<&dyn ItemHandle>, cx: &mut ViewContext<Self>) {
489        if let Some(editor) = item.and_then(|item| item.act_as::<Editor>(cx)) {
490            self.editor_subscription = Some((
491                cx.observe(&editor, Self::update_enabled),
492                editor.entity_id().as_u64() as usize,
493            ));
494            self.update_enabled(editor, cx);
495        } else {
496            self.language = None;
497            self.editor_subscription = None;
498            self.editor_enabled = None;
499        }
500        cx.notify();
501    }
502}
503
504impl SupermavenButtonStatus {
505    fn to_icon(&self) -> IconName {
506        match self {
507            SupermavenButtonStatus::Ready => IconName::Supermaven,
508            SupermavenButtonStatus::Errored(_) => IconName::SupermavenError,
509            SupermavenButtonStatus::NeedsActivation(_) => IconName::SupermavenInit,
510            SupermavenButtonStatus::Initializing => IconName::SupermavenInit,
511        }
512    }
513
514    fn to_tooltip(&self) -> String {
515        match self {
516            SupermavenButtonStatus::Ready => "Supermaven is ready".to_string(),
517            SupermavenButtonStatus::Errored(error) => format!("Supermaven error: {}", error),
518            SupermavenButtonStatus::NeedsActivation(_) => "Supermaven needs activation".to_string(),
519            SupermavenButtonStatus::Initializing => "Supermaven initializing".to_string(),
520        }
521    }
522
523    fn has_menu(&self) -> bool {
524        match self {
525            SupermavenButtonStatus::Ready | SupermavenButtonStatus::NeedsActivation(_) => true,
526            SupermavenButtonStatus::Errored(_) | SupermavenButtonStatus::Initializing => false,
527        }
528    }
529}
530
531async fn configure_disabled_globs(
532    workspace: WeakView<Workspace>,
533    path_to_disable: Option<Arc<Path>>,
534    mut cx: AsyncWindowContext,
535) -> Result<()> {
536    let settings_editor = workspace
537        .update(&mut cx, |_, cx| {
538            create_and_open_local_file(paths::settings_file(), cx, || {
539                settings::initial_user_settings_content().as_ref().into()
540            })
541        })?
542        .await?
543        .downcast::<Editor>()
544        .unwrap();
545
546    settings_editor.downgrade().update(&mut cx, |item, cx| {
547        let text = item.buffer().read(cx).snapshot(cx).text();
548
549        let settings = cx.global::<SettingsStore>();
550        let edits = settings.edits_for_update::<AllLanguageSettings>(&text, |file| {
551            let copilot = file.inline_completions.get_or_insert_with(Default::default);
552            let globs = copilot.disabled_globs.get_or_insert_with(|| {
553                settings
554                    .get::<AllLanguageSettings>(None)
555                    .inline_completions
556                    .disabled_globs
557                    .iter()
558                    .map(|glob| glob.glob().to_string())
559                    .collect()
560            });
561
562            if let Some(path_to_disable) = &path_to_disable {
563                globs.push(path_to_disable.to_string_lossy().into_owned());
564            } else {
565                globs.clear();
566            }
567        });
568
569        if !edits.is_empty() {
570            item.change_selections(Some(Autoscroll::newest()), cx, |selections| {
571                selections.select_ranges(edits.iter().map(|e| e.0.clone()));
572            });
573
574            // When *enabling* a path, don't actually perform an edit, just select the range.
575            if path_to_disable.is_some() {
576                item.edit(edits.iter().cloned(), cx);
577            }
578        }
579    })?;
580
581    anyhow::Ok(())
582}
583
584fn toggle_inline_completions_globally(fs: Arc<dyn Fs>, cx: &mut AppContext) {
585    let show_inline_completions =
586        all_language_settings(None, cx).inline_completions_enabled(None, None, cx);
587    update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
588        file.defaults.show_inline_completions = Some(!show_inline_completions)
589    });
590}
591
592fn set_completion_provider(
593    fs: Arc<dyn Fs>,
594    cx: &mut AppContext,
595    provider: InlineCompletionProvider,
596) {
597    update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
598        file.features
599            .get_or_insert(Default::default())
600            .inline_completion_provider = Some(provider);
601    });
602}
603
604fn toggle_inline_completions_for_language(
605    language: Arc<Language>,
606    fs: Arc<dyn Fs>,
607    cx: &mut AppContext,
608) {
609    let show_inline_completions =
610        all_language_settings(None, cx).inline_completions_enabled(Some(&language), None, cx);
611    update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
612        file.languages
613            .entry(language.name())
614            .or_default()
615            .show_inline_completions = Some(!show_inline_completions);
616    });
617}
618
619fn hide_copilot(fs: Arc<dyn Fs>, cx: &mut AppContext) {
620    update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
621        file.features
622            .get_or_insert(Default::default())
623            .inline_completion_provider = Some(InlineCompletionProvider::None);
624    });
625}