inline_completion_button.rs

  1use anyhow::Result;
  2use client::UserStore;
  3use copilot::{Copilot, Status};
  4use editor::{
  5    actions::{ShowEditPrediction, ToggleEditPrediction},
  6    scroll::Autoscroll,
  7    Editor,
  8};
  9use feature_flags::{
 10    FeatureFlagAppExt, PredictEditsFeatureFlag, PredictEditsRateCompletionsFeatureFlag,
 11};
 12use fs::Fs;
 13use gpui::{
 14    actions, div, pulsating_between, Action, Animation, AnimationExt, App, AsyncWindowContext,
 15    Corner, Entity, FocusHandle, Focusable, IntoElement, ParentElement, Render, Subscription,
 16    WeakEntity,
 17};
 18use indoc::indoc;
 19use language::{
 20    language_settings::{self, all_language_settings, AllLanguageSettings, EditPredictionProvider},
 21    File, Language,
 22};
 23use regex::Regex;
 24use settings::{update_settings_file, Settings, SettingsStore};
 25use std::{
 26    sync::{Arc, LazyLock},
 27    time::Duration,
 28};
 29use supermaven::{AccountStatus, Supermaven};
 30use ui::{
 31    prelude::*, Clickable, ContextMenu, ContextMenuEntry, IconButton, IconButtonShape, Indicator,
 32    PopoverMenu, PopoverMenuHandle, Tooltip,
 33};
 34use workspace::{
 35    create_and_open_local_file, item::ItemHandle, notifications::NotificationId, StatusItemView,
 36    Toast, Workspace,
 37};
 38use zed_actions::OpenBrowser;
 39use zeta::RateCompletions;
 40
 41actions!(edit_prediction, [ToggleMenu]);
 42
 43const COPILOT_SETTINGS_URL: &str = "https://github.com/settings/copilot";
 44
 45struct CopilotErrorToast;
 46
 47pub struct InlineCompletionButton {
 48    editor_subscription: Option<(Subscription, usize)>,
 49    editor_enabled: Option<bool>,
 50    editor_show_predictions: bool,
 51    editor_focus_handle: Option<FocusHandle>,
 52    language: Option<Arc<Language>>,
 53    file: Option<Arc<dyn File>>,
 54    edit_prediction_provider: Option<Arc<dyn inline_completion::InlineCompletionProviderHandle>>,
 55    fs: Arc<dyn Fs>,
 56    user_store: Entity<UserStore>,
 57    popover_menu_handle: PopoverMenuHandle<ContextMenu>,
 58}
 59
 60enum SupermavenButtonStatus {
 61    Ready,
 62    Errored(String),
 63    NeedsActivation(String),
 64    Initializing,
 65}
 66
 67impl Render for InlineCompletionButton {
 68    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 69        let all_language_settings = all_language_settings(None, cx);
 70
 71        match all_language_settings.edit_predictions.provider {
 72            EditPredictionProvider::None => div(),
 73
 74            EditPredictionProvider::Copilot => {
 75                let Some(copilot) = Copilot::global(cx) else {
 76                    return div();
 77                };
 78                let status = copilot.read(cx).status();
 79
 80                let enabled = self.editor_enabled.unwrap_or(false);
 81
 82                let icon = match status {
 83                    Status::Error(_) => IconName::CopilotError,
 84                    Status::Authorized => {
 85                        if enabled {
 86                            IconName::Copilot
 87                        } else {
 88                            IconName::CopilotDisabled
 89                        }
 90                    }
 91                    _ => IconName::CopilotInit,
 92                };
 93
 94                if let Status::Error(e) = status {
 95                    return div().child(
 96                        IconButton::new("copilot-error", icon)
 97                            .icon_size(IconSize::Small)
 98                            .on_click(cx.listener(move |_, _, window, cx| {
 99                                if let Some(workspace) = window.root::<Workspace>().flatten() {
100                                    workspace.update(cx, |workspace, cx| {
101                                        workspace.show_toast(
102                                            Toast::new(
103                                                NotificationId::unique::<CopilotErrorToast>(),
104                                                format!("Copilot can't be started: {}", e),
105                                            )
106                                            .on_click(
107                                                "Reinstall Copilot",
108                                                |_, cx| {
109                                                    if let Some(copilot) = Copilot::global(cx) {
110                                                        copilot
111                                                            .update(cx, |copilot, cx| {
112                                                                copilot.reinstall(cx)
113                                                            })
114                                                            .detach();
115                                                    }
116                                                },
117                                            ),
118                                            cx,
119                                        );
120                                    });
121                                }
122                            }))
123                            .tooltip(|window, cx| {
124                                Tooltip::for_action("GitHub Copilot", &ToggleMenu, window, cx)
125                            }),
126                    );
127                }
128                let this = cx.entity().clone();
129
130                div().child(
131                    PopoverMenu::new("copilot")
132                        .menu(move |window, cx| {
133                            Some(match status {
134                                Status::Authorized => this.update(cx, |this, cx| {
135                                    this.build_copilot_context_menu(window, cx)
136                                }),
137                                _ => this.update(cx, |this, cx| {
138                                    this.build_copilot_start_menu(window, cx)
139                                }),
140                            })
141                        })
142                        .anchor(Corner::BottomRight)
143                        .trigger_with_tooltip(
144                            IconButton::new("copilot-icon", icon),
145                            |window, cx| {
146                                Tooltip::for_action("GitHub Copilot", &ToggleMenu, window, cx)
147                            },
148                        )
149                        .with_handle(self.popover_menu_handle.clone()),
150                )
151            }
152
153            EditPredictionProvider::Supermaven => {
154                let Some(supermaven) = Supermaven::global(cx) else {
155                    return div();
156                };
157
158                let supermaven = supermaven.read(cx);
159
160                let status = match supermaven {
161                    Supermaven::Starting => SupermavenButtonStatus::Initializing,
162                    Supermaven::FailedDownload { error } => {
163                        SupermavenButtonStatus::Errored(error.to_string())
164                    }
165                    Supermaven::Spawned(agent) => {
166                        let account_status = agent.account_status.clone();
167                        match account_status {
168                            AccountStatus::NeedsActivation { activate_url } => {
169                                SupermavenButtonStatus::NeedsActivation(activate_url.clone())
170                            }
171                            AccountStatus::Unknown => SupermavenButtonStatus::Initializing,
172                            AccountStatus::Ready => SupermavenButtonStatus::Ready,
173                        }
174                    }
175                    Supermaven::Error { error } => {
176                        SupermavenButtonStatus::Errored(error.to_string())
177                    }
178                };
179
180                let icon = status.to_icon();
181                let tooltip_text = status.to_tooltip();
182                let has_menu = status.has_menu();
183                let this = cx.entity().clone();
184                let fs = self.fs.clone();
185
186                return div().child(
187                    PopoverMenu::new("supermaven")
188                        .menu(move |window, cx| match &status {
189                            SupermavenButtonStatus::NeedsActivation(activate_url) => {
190                                Some(ContextMenu::build(window, cx, |menu, _, _| {
191                                    let fs = fs.clone();
192                                    let activate_url = activate_url.clone();
193                                    menu.entry("Sign In", None, move |_, cx| {
194                                        cx.open_url(activate_url.as_str())
195                                    })
196                                    .entry(
197                                        "Use Copilot",
198                                        None,
199                                        move |_, cx| {
200                                            set_completion_provider(
201                                                fs.clone(),
202                                                cx,
203                                                EditPredictionProvider::Copilot,
204                                            )
205                                        },
206                                    )
207                                }))
208                            }
209                            SupermavenButtonStatus::Ready => Some(this.update(cx, |this, cx| {
210                                this.build_supermaven_context_menu(window, cx)
211                            })),
212                            _ => None,
213                        })
214                        .anchor(Corner::BottomRight)
215                        .trigger_with_tooltip(
216                            IconButton::new("supermaven-icon", icon),
217                            move |window, cx| {
218                                if has_menu {
219                                    Tooltip::for_action(
220                                        tooltip_text.clone(),
221                                        &ToggleMenu,
222                                        window,
223                                        cx,
224                                    )
225                                } else {
226                                    Tooltip::text(tooltip_text.clone())(window, cx)
227                                }
228                            },
229                        )
230                        .with_handle(self.popover_menu_handle.clone()),
231                );
232            }
233
234            EditPredictionProvider::Zed => {
235                if !cx.has_flag::<PredictEditsFeatureFlag>() {
236                    return div();
237                }
238
239                let enabled = self.editor_enabled.unwrap_or(true);
240
241                let zeta_icon = if enabled {
242                    IconName::ZedPredict
243                } else {
244                    IconName::ZedPredictDisabled
245                };
246
247                let current_user_terms_accepted =
248                    self.user_store.read(cx).current_user_has_accepted_terms();
249
250                if !current_user_terms_accepted.unwrap_or(false) {
251                    let signed_in = current_user_terms_accepted.is_some();
252                    let tooltip_meta = if signed_in {
253                        "Read Terms of Service"
254                    } else {
255                        "Sign in to use"
256                    };
257
258                    return div().child(
259                        IconButton::new("zed-predict-pending-button", zeta_icon)
260                            .shape(IconButtonShape::Square)
261                            .indicator(Indicator::dot().color(Color::Error))
262                            .indicator_border_color(Some(cx.theme().colors().status_bar_background))
263                            .tooltip(move |window, cx| {
264                                Tooltip::with_meta(
265                                    "Edit Predictions",
266                                    None,
267                                    tooltip_meta,
268                                    window,
269                                    cx,
270                                )
271                            })
272                            .on_click(cx.listener(move |_, _, window, cx| {
273                                telemetry::event!(
274                                    "Pending ToS Clicked",
275                                    source = "Edit Prediction Status Button"
276                                );
277                                window.dispatch_action(
278                                    zed_actions::OpenZedPredictOnboarding.boxed_clone(),
279                                    cx,
280                                );
281                            })),
282                    );
283                }
284
285                let show_editor_predictions = self.editor_show_predictions;
286
287                let icon_button = IconButton::new("zed-predict-pending-button", zeta_icon)
288                    .shape(IconButtonShape::Square)
289                    .when(enabled && !show_editor_predictions, |this| {
290                        this.indicator(Indicator::dot().color(Color::Muted))
291                            .indicator_border_color(Some(cx.theme().colors().status_bar_background))
292                    })
293                    .when(!self.popover_menu_handle.is_deployed(), |element| {
294                        element.tooltip(move |window, cx| {
295                            if enabled {
296                                if show_editor_predictions {
297                                    Tooltip::for_action("Edit Prediction", &ToggleMenu, window, cx)
298                                } else {
299                                    Tooltip::with_meta(
300                                        "Edit Prediction",
301                                        Some(&ToggleMenu),
302                                        "Hidden For This File",
303                                        window,
304                                        cx,
305                                    )
306                                }
307                            } else {
308                                Tooltip::with_meta(
309                                    "Edit Prediction",
310                                    Some(&ToggleMenu),
311                                    "Disabled For This File",
312                                    window,
313                                    cx,
314                                )
315                            }
316                        })
317                    });
318
319                let this = cx.entity().clone();
320
321                let mut popover_menu = PopoverMenu::new("zeta")
322                    .menu(move |window, cx| {
323                        Some(this.update(cx, |this, cx| this.build_zeta_context_menu(window, cx)))
324                    })
325                    .anchor(Corner::BottomRight)
326                    .with_handle(self.popover_menu_handle.clone());
327
328                let is_refreshing = self
329                    .edit_prediction_provider
330                    .as_ref()
331                    .map_or(false, |provider| provider.is_refreshing(cx));
332
333                if is_refreshing {
334                    popover_menu = popover_menu.trigger(
335                        icon_button.with_animation(
336                            "pulsating-label",
337                            Animation::new(Duration::from_secs(2))
338                                .repeat()
339                                .with_easing(pulsating_between(0.2, 1.0)),
340                            |icon_button, delta| icon_button.alpha(delta),
341                        ),
342                    );
343                } else {
344                    popover_menu = popover_menu.trigger(icon_button);
345                }
346
347                div().child(popover_menu.into_any_element())
348            }
349        }
350    }
351}
352
353impl InlineCompletionButton {
354    pub fn new(
355        fs: Arc<dyn Fs>,
356        user_store: Entity<UserStore>,
357        popover_menu_handle: PopoverMenuHandle<ContextMenu>,
358        cx: &mut Context<Self>,
359    ) -> Self {
360        if let Some(copilot) = Copilot::global(cx) {
361            cx.observe(&copilot, |_, _, cx| cx.notify()).detach()
362        }
363
364        cx.observe_global::<SettingsStore>(move |_, cx| cx.notify())
365            .detach();
366
367        Self {
368            editor_subscription: None,
369            editor_enabled: None,
370            editor_show_predictions: true,
371            editor_focus_handle: None,
372            language: None,
373            file: None,
374            edit_prediction_provider: None,
375            popover_menu_handle,
376            fs,
377            user_store,
378        }
379    }
380
381    pub fn build_copilot_start_menu(
382        &mut self,
383        window: &mut Window,
384        cx: &mut Context<Self>,
385    ) -> Entity<ContextMenu> {
386        let fs = self.fs.clone();
387        ContextMenu::build(window, cx, |menu, _, _| {
388            menu.entry("Sign In", None, copilot::initiate_sign_in)
389                .entry("Disable Copilot", None, {
390                    let fs = fs.clone();
391                    move |_window, cx| hide_copilot(fs.clone(), cx)
392                })
393                .entry("Use Supermaven", None, {
394                    let fs = fs.clone();
395                    move |_window, cx| {
396                        set_completion_provider(fs.clone(), cx, EditPredictionProvider::Supermaven)
397                    }
398                })
399        })
400    }
401
402    pub fn build_language_settings_menu(&self, mut menu: ContextMenu, cx: &mut App) -> ContextMenu {
403        let fs = self.fs.clone();
404
405        menu = menu.header("Show Edit Predictions For");
406
407        if let Some(editor_focus_handle) = self.editor_focus_handle.clone() {
408            menu = menu.toggleable_entry(
409                "This Buffer",
410                self.editor_show_predictions,
411                IconPosition::Start,
412                Some(Box::new(ToggleEditPrediction)),
413                {
414                    let editor_focus_handle = editor_focus_handle.clone();
415                    move |window, cx| {
416                        editor_focus_handle.dispatch_action(&ToggleEditPrediction, window, cx);
417                    }
418                },
419            );
420        }
421
422        if let Some(language) = self.language.clone() {
423            let fs = fs.clone();
424            let language_enabled =
425                language_settings::language_settings(Some(language.name()), None, cx)
426                    .show_edit_predictions;
427
428            menu = menu.toggleable_entry(
429                language.name(),
430                language_enabled,
431                IconPosition::Start,
432                None,
433                move |_, cx| {
434                    toggle_show_inline_completions_for_language(language.clone(), fs.clone(), cx)
435                },
436            );
437        }
438
439        let settings = AllLanguageSettings::get_global(cx);
440        let globally_enabled = settings.show_inline_completions(None, cx);
441        menu = menu.toggleable_entry("All Files", globally_enabled, IconPosition::Start, None, {
442            let fs = fs.clone();
443            move |_, cx| toggle_inline_completions_globally(fs.clone(), cx)
444        });
445        menu = menu.separator().header("Privacy Settings");
446
447        if let Some(provider) = &self.edit_prediction_provider {
448            let data_collection = provider.data_collection_state(cx);
449            if data_collection.is_supported() {
450                let provider = provider.clone();
451                let enabled = data_collection.is_enabled();
452                let is_open_source = data_collection.is_project_open_source();
453                let is_collecting = data_collection.is_enabled();
454                let (icon_name, icon_color) = if is_open_source && is_collecting {
455                    (IconName::Check, Color::Success)
456                } else {
457                    (IconName::Check, Color::Accent)
458                };
459
460                menu = menu.item(
461                    ContextMenuEntry::new("Training Data Collection")
462                        .toggleable(IconPosition::Start, data_collection.is_enabled())
463                        .icon(icon_name)
464                        .icon_color(icon_color)
465                        .documentation_aside(move |cx| {
466                            let (msg, label_color, icon_name, icon_color) = match (is_open_source, is_collecting) {
467                                (true, true) => (
468                                    "Project identified as open source, and you're sharing data.",
469                                    Color::Default,
470                                    IconName::Check,
471                                    Color::Success,
472                                ),
473                                (true, false) => (
474                                    "Project identified as open source, but you're not sharing data.",
475                                    Color::Muted,
476                                    IconName::Close,
477                                    Color::Muted,
478                                ),
479                                (false, true) => (
480                                    "Project not identified as open source. No data captured.",
481                                    Color::Muted,
482                                    IconName::Close,
483                                    Color::Muted,
484                                ),
485                                (false, false) => (
486                                    "Project not identified as open source, and setting turned off.",
487                                    Color::Muted,
488                                    IconName::Close,
489                                    Color::Muted,
490                                ),
491                            };
492                            v_flex()
493                                .gap_2()
494                                .child(
495                                    Label::new(indoc!{
496                                        "Help us improve our open dataset model by sharing data from open source repositories. \
497                                        Zed must detect a license file in your repo for this setting to take effect."
498                                    })
499                                )
500                                .child(
501                                    h_flex()
502                                        .pt_2()
503                                        .gap_1p5()
504                                        .border_t_1()
505                                        .border_color(cx.theme().colors().border_variant)
506                                        .child(Icon::new(icon_name).size(IconSize::XSmall).color(icon_color))
507                                        .child(div().child(Label::new(msg).size(LabelSize::Small).color(label_color)))
508                                )
509                                .into_any_element()
510                        })
511                        .handler(move |_, cx| {
512                            provider.toggle_data_collection(cx);
513
514                            if !enabled {
515                                telemetry::event!(
516                                    "Data Collection Enabled",
517                                    source = "Edit Prediction Status Menu"
518                                );
519                            } else {
520                                telemetry::event!(
521                                    "Data Collection Disabled",
522                                    source = "Edit Prediction Status Menu"
523                                );
524                            }
525                        })
526                );
527
528                if is_collecting && !is_open_source {
529                    menu = menu.item(
530                        ContextMenuEntry::new("No data captured.")
531                            .disabled(true)
532                            .icon(IconName::Close)
533                            .icon_color(Color::Error)
534                            .icon_size(IconSize::Small),
535                    );
536                }
537            }
538        }
539
540        menu = menu.item(
541            ContextMenuEntry::new("Configure Excluded Files")
542                .icon(IconName::LockOutlined)
543                .icon_color(Color::Muted)
544                .documentation_aside(|_| {
545                    Label::new(indoc!{"
546                        Open your settings to add sensitive paths for which Zed will never predict edits."}).into_any_element()
547                })
548                .handler(move |window, cx| {
549                    if let Some(workspace) = window.root().flatten() {
550                        let workspace = workspace.downgrade();
551                        window
552                            .spawn(cx, |cx| {
553                                open_disabled_globs_setting_in_editor(
554                                    workspace,
555                                    cx,
556                                )
557                            })
558                            .detach_and_log_err(cx);
559                    }
560                }),
561        );
562
563        if !self.editor_enabled.unwrap_or(true) {
564            menu = menu.item(
565                ContextMenuEntry::new("This file is excluded.")
566                    .disabled(true)
567                    .icon(IconName::ZedPredictDisabled)
568                    .icon_size(IconSize::Small),
569            );
570        }
571
572        let is_eager_preview_enabled = match settings.edit_predictions_mode() {
573            language::EditPredictionsMode::Auto => false,
574            language::EditPredictionsMode::EagerPreview => true,
575        };
576        menu = if cx.is_staff() {
577            menu.separator().toggleable_entry(
578                "Eager Preview Mode",
579                is_eager_preview_enabled,
580                IconPosition::Start,
581                None,
582                {
583                    let fs = fs.clone();
584                    move |_window, cx| {
585                        update_settings_file::<AllLanguageSettings>(
586                            fs.clone(),
587                            cx,
588                            move |settings, _cx| {
589                                let new_mode = match is_eager_preview_enabled {
590                                    true => language::EditPredictionsMode::Auto,
591                                    false => language::EditPredictionsMode::EagerPreview,
592                                };
593
594                                if let Some(edit_predictions) = settings.edit_predictions.as_mut() {
595                                    edit_predictions.mode = new_mode;
596                                } else {
597                                    settings.edit_predictions =
598                                        Some(language_settings::EditPredictionSettingsContent {
599                                            mode: new_mode,
600                                            ..Default::default()
601                                        });
602                                }
603                            },
604                        );
605                    }
606                },
607            )
608        } else {
609            menu
610        };
611
612        if let Some(editor_focus_handle) = self.editor_focus_handle.clone() {
613            menu = menu
614                .separator()
615                .entry(
616                    "Predict Edit at Cursor",
617                    Some(Box::new(ShowEditPrediction)),
618                    {
619                        let editor_focus_handle = editor_focus_handle.clone();
620                        move |window, cx| {
621                            editor_focus_handle.dispatch_action(&ShowEditPrediction, window, cx);
622                        }
623                    },
624                )
625                .context(editor_focus_handle);
626        }
627
628        menu
629    }
630
631    fn build_copilot_context_menu(
632        &self,
633        window: &mut Window,
634        cx: &mut Context<Self>,
635    ) -> Entity<ContextMenu> {
636        ContextMenu::build(window, cx, |menu, _, cx| {
637            self.build_language_settings_menu(menu, cx)
638                .separator()
639                .link(
640                    "Go to Copilot Settings",
641                    OpenBrowser {
642                        url: COPILOT_SETTINGS_URL.to_string(),
643                    }
644                    .boxed_clone(),
645                )
646                .action("Sign Out", copilot::SignOut.boxed_clone())
647        })
648    }
649
650    fn build_supermaven_context_menu(
651        &self,
652        window: &mut Window,
653        cx: &mut Context<Self>,
654    ) -> Entity<ContextMenu> {
655        ContextMenu::build(window, cx, |menu, _, cx| {
656            self.build_language_settings_menu(menu, cx)
657                .separator()
658                .action("Sign Out", supermaven::SignOut.boxed_clone())
659        })
660    }
661
662    fn build_zeta_context_menu(
663        &self,
664        window: &mut Window,
665        cx: &mut Context<Self>,
666    ) -> Entity<ContextMenu> {
667        ContextMenu::build(window, cx, |menu, _window, cx| {
668            self.build_language_settings_menu(menu, cx).when(
669                cx.has_flag::<PredictEditsRateCompletionsFeatureFlag>(),
670                |this| this.action("Rate Completions", RateCompletions.boxed_clone()),
671            )
672        })
673    }
674
675    pub fn update_enabled(&mut self, editor: Entity<Editor>, cx: &mut Context<Self>) {
676        let editor = editor.read(cx);
677        let snapshot = editor.buffer().read(cx).snapshot(cx);
678        let suggestion_anchor = editor.selections.newest_anchor().start;
679        let language = snapshot.language_at(suggestion_anchor);
680        let file = snapshot.file_at(suggestion_anchor).cloned();
681        self.editor_enabled = {
682            let file = file.as_ref();
683            Some(
684                file.map(|file| {
685                    all_language_settings(Some(file), cx)
686                        .inline_completions_enabled_for_path(file.path())
687                })
688                .unwrap_or(true),
689            )
690        };
691        self.editor_show_predictions = editor.edit_predictions_enabled();
692        self.edit_prediction_provider = editor.edit_prediction_provider();
693        self.language = language.cloned();
694        self.file = file;
695        self.editor_focus_handle = Some(editor.focus_handle(cx));
696
697        cx.notify();
698    }
699
700    pub fn toggle_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) {
701        self.popover_menu_handle.toggle(window, cx);
702    }
703}
704
705impl StatusItemView for InlineCompletionButton {
706    fn set_active_pane_item(
707        &mut self,
708        item: Option<&dyn ItemHandle>,
709        _: &mut Window,
710        cx: &mut Context<Self>,
711    ) {
712        if let Some(editor) = item.and_then(|item| item.act_as::<Editor>(cx)) {
713            self.editor_subscription = Some((
714                cx.observe(&editor, Self::update_enabled),
715                editor.entity_id().as_u64() as usize,
716            ));
717            self.update_enabled(editor, cx);
718        } else {
719            self.language = None;
720            self.editor_subscription = None;
721            self.editor_enabled = None;
722        }
723        cx.notify();
724    }
725}
726
727impl SupermavenButtonStatus {
728    fn to_icon(&self) -> IconName {
729        match self {
730            SupermavenButtonStatus::Ready => IconName::Supermaven,
731            SupermavenButtonStatus::Errored(_) => IconName::SupermavenError,
732            SupermavenButtonStatus::NeedsActivation(_) => IconName::SupermavenInit,
733            SupermavenButtonStatus::Initializing => IconName::SupermavenInit,
734        }
735    }
736
737    fn to_tooltip(&self) -> String {
738        match self {
739            SupermavenButtonStatus::Ready => "Supermaven is ready".to_string(),
740            SupermavenButtonStatus::Errored(error) => format!("Supermaven error: {}", error),
741            SupermavenButtonStatus::NeedsActivation(_) => "Supermaven needs activation".to_string(),
742            SupermavenButtonStatus::Initializing => "Supermaven initializing".to_string(),
743        }
744    }
745
746    fn has_menu(&self) -> bool {
747        match self {
748            SupermavenButtonStatus::Ready | SupermavenButtonStatus::NeedsActivation(_) => true,
749            SupermavenButtonStatus::Errored(_) | SupermavenButtonStatus::Initializing => false,
750        }
751    }
752}
753
754async fn open_disabled_globs_setting_in_editor(
755    workspace: WeakEntity<Workspace>,
756    mut cx: AsyncWindowContext,
757) -> Result<()> {
758    let settings_editor = workspace
759        .update_in(&mut cx, |_, window, cx| {
760            create_and_open_local_file(paths::settings_file(), window, cx, || {
761                settings::initial_user_settings_content().as_ref().into()
762            })
763        })?
764        .await?
765        .downcast::<Editor>()
766        .unwrap();
767
768    settings_editor
769        .downgrade()
770        .update_in(&mut cx, |item, window, cx| {
771            let text = item.buffer().read(cx).snapshot(cx).text();
772
773            let settings = cx.global::<SettingsStore>();
774
775            // Ensure that we always have "inline_completions { "disabled_globs": [] }"
776            let edits = settings.edits_for_update::<AllLanguageSettings>(&text, |file| {
777                file.edit_predictions
778                    .get_or_insert_with(Default::default)
779                    .disabled_globs
780                    .get_or_insert_with(Vec::new);
781            });
782
783            if !edits.is_empty() {
784                item.edit(edits.iter().cloned(), cx);
785            }
786
787            let text = item.buffer().read(cx).snapshot(cx).text();
788
789            static DISABLED_GLOBS_REGEX: LazyLock<Regex> = LazyLock::new(|| {
790                Regex::new(r#""disabled_globs":\s*\[\s*(?P<content>(?:.|\n)*?)\s*\]"#).unwrap()
791            });
792            // Only capture [...]
793            let range = DISABLED_GLOBS_REGEX.captures(&text).and_then(|captures| {
794                captures
795                    .name("content")
796                    .map(|inner_match| inner_match.start()..inner_match.end())
797            });
798            if let Some(range) = range {
799                item.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
800                    selections.select_ranges(vec![range]);
801                });
802            }
803        })?;
804
805    anyhow::Ok(())
806}
807
808fn toggle_inline_completions_globally(fs: Arc<dyn Fs>, cx: &mut App) {
809    let show_edit_predictions = all_language_settings(None, cx).show_inline_completions(None, cx);
810    update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
811        file.defaults.show_edit_predictions = Some(!show_edit_predictions)
812    });
813}
814
815fn set_completion_provider(fs: Arc<dyn Fs>, cx: &mut App, provider: EditPredictionProvider) {
816    update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
817        file.features
818            .get_or_insert(Default::default())
819            .edit_prediction_provider = Some(provider);
820    });
821}
822
823fn toggle_show_inline_completions_for_language(
824    language: Arc<Language>,
825    fs: Arc<dyn Fs>,
826    cx: &mut App,
827) {
828    let show_edit_predictions =
829        all_language_settings(None, cx).show_inline_completions(Some(&language), cx);
830    update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
831        file.languages
832            .entry(language.name())
833            .or_default()
834            .show_edit_predictions = Some(!show_edit_predictions);
835    });
836}
837
838fn hide_copilot(fs: Arc<dyn Fs>, cx: &mut App) {
839    update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
840        file.features
841            .get_or_insert(Default::default())
842            .edit_prediction_provider = Some(EditPredictionProvider::None);
843    });
844}