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(
403        &self,
404        mut menu: ContextMenu,
405        window: &Window,
406        cx: &mut App,
407    ) -> ContextMenu {
408        let fs = self.fs.clone();
409        let line_height = window.line_height();
410
411        menu = menu.header("Show Edit Predictions For");
412
413        let language_state = self.language.as_ref().map(|language| {
414            (
415                language.clone(),
416                language_settings::language_settings(Some(language.name()), None, cx)
417                    .show_edit_predictions,
418            )
419        });
420
421        if let Some(editor_focus_handle) = self.editor_focus_handle.clone() {
422            let entry = ContextMenuEntry::new("This Buffer")
423                .toggleable(IconPosition::Start, self.editor_show_predictions)
424                .action(Box::new(ToggleEditPrediction))
425                .handler(move |window, cx| {
426                    editor_focus_handle.dispatch_action(&ToggleEditPrediction, window, cx);
427                });
428
429            match language_state.clone() {
430                Some((language, false)) => {
431                    menu = menu.item(
432                        entry
433                            .disabled(true)
434                            .documentation_aside(move |_cx| {
435                                Label::new(format!("Edit predictions cannot be toggled for this buffer because they are disabled for {}", language.name()))
436                                    .into_any_element()
437                            })
438                    );
439                }
440                Some(_) | None => menu = menu.item(entry),
441            }
442        }
443
444        if let Some((language, language_enabled)) = language_state {
445            let fs = fs.clone();
446
447            menu = menu.toggleable_entry(
448                language.name(),
449                language_enabled,
450                IconPosition::Start,
451                None,
452                move |_, cx| {
453                    toggle_show_inline_completions_for_language(language.clone(), fs.clone(), cx)
454                },
455            );
456        }
457
458        let settings = AllLanguageSettings::get_global(cx);
459        let globally_enabled = settings.show_edit_predictions(None, cx);
460        menu = menu.toggleable_entry("All Files", globally_enabled, IconPosition::Start, None, {
461            let fs = fs.clone();
462            move |_, cx| toggle_inline_completions_globally(fs.clone(), cx)
463        });
464        menu = menu.separator().header("Privacy Settings");
465
466        if let Some(provider) = &self.edit_prediction_provider {
467            let data_collection = provider.data_collection_state(cx);
468            if data_collection.is_supported() {
469                let provider = provider.clone();
470                let enabled = data_collection.is_enabled();
471                let is_open_source = data_collection.is_project_open_source();
472                let is_collecting = data_collection.is_enabled();
473                let (icon_name, icon_color) = if is_open_source && is_collecting {
474                    (IconName::Check, Color::Success)
475                } else {
476                    (IconName::Check, Color::Accent)
477                };
478
479                menu = menu.item(
480                    ContextMenuEntry::new("Training Data Collection")
481                        .toggleable(IconPosition::Start, data_collection.is_enabled())
482                        .icon(icon_name)
483                        .icon_color(icon_color)
484                        .documentation_aside(move |cx| {
485                            let (msg, label_color, icon_name, icon_color) = match (is_open_source, is_collecting) {
486                                (true, true) => (
487                                    "Project identified as open source, and you're sharing data.",
488                                    Color::Default,
489                                    IconName::Check,
490                                    Color::Success,
491                                ),
492                                (true, false) => (
493                                    "Project identified as open source, but you're not sharing data.",
494                                    Color::Muted,
495                                    IconName::Close,
496                                    Color::Muted,
497                                ),
498                                (false, true) => (
499                                    "Project not identified as open source. No data captured.",
500                                    Color::Muted,
501                                    IconName::Close,
502                                    Color::Muted,
503                                ),
504                                (false, false) => (
505                                    "Project not identified as open source, and setting turned off.",
506                                    Color::Muted,
507                                    IconName::Close,
508                                    Color::Muted,
509                                ),
510                            };
511                            v_flex()
512                                .gap_2()
513                                .child(
514                                    Label::new(indoc!{
515                                        "Help us improve our open dataset model by sharing data from open source repositories. \
516                                        Zed must detect a license file in your repo for this setting to take effect."
517                                    })
518                                )
519                                .child(
520                                    h_flex()
521                                        .items_start()
522                                        .pt_2()
523                                        .flex_1()
524                                        .gap_1p5()
525                                        .border_t_1()
526                                        .border_color(cx.theme().colors().border_variant)
527                                        .child(h_flex().flex_shrink_0().h(line_height).child(Icon::new(icon_name).size(IconSize::XSmall).color(icon_color)))
528                                        .child(div().child(msg).w_full().text_sm().text_color(label_color.color(cx)))
529                                )
530                                .into_any_element()
531                        })
532                        .handler(move |_, cx| {
533                            provider.toggle_data_collection(cx);
534
535                            if !enabled {
536                                telemetry::event!(
537                                    "Data Collection Enabled",
538                                    source = "Edit Prediction Status Menu"
539                                );
540                            } else {
541                                telemetry::event!(
542                                    "Data Collection Disabled",
543                                    source = "Edit Prediction Status Menu"
544                                );
545                            }
546                        })
547                );
548
549                if is_collecting && !is_open_source {
550                    menu = menu.item(
551                        ContextMenuEntry::new("No data captured.")
552                            .disabled(true)
553                            .icon(IconName::Close)
554                            .icon_color(Color::Error)
555                            .icon_size(IconSize::Small),
556                    );
557                }
558            }
559        }
560
561        menu = menu.item(
562            ContextMenuEntry::new("Configure Excluded Files")
563                .icon(IconName::LockOutlined)
564                .icon_color(Color::Muted)
565                .documentation_aside(|_| {
566                    Label::new(indoc!{"
567                        Open your settings to add sensitive paths for which Zed will never predict edits."}).into_any_element()
568                })
569                .handler(move |window, cx| {
570                    if let Some(workspace) = window.root().flatten() {
571                        let workspace = workspace.downgrade();
572                        window
573                            .spawn(cx, |cx| {
574                                open_disabled_globs_setting_in_editor(
575                                    workspace,
576                                    cx,
577                                )
578                            })
579                            .detach_and_log_err(cx);
580                    }
581                }),
582        );
583
584        if !self.editor_enabled.unwrap_or(true) {
585            menu = menu.item(
586                ContextMenuEntry::new("This file is excluded.")
587                    .disabled(true)
588                    .icon(IconName::ZedPredictDisabled)
589                    .icon_size(IconSize::Small),
590            );
591        }
592
593        if cx.has_flag::<feature_flags::PredictEditsNonEagerModeFeatureFlag>() {
594            let is_eager_preview_enabled = match settings.edit_predictions_mode() {
595                language::EditPredictionsMode::Subtle => false,
596                language::EditPredictionsMode::Eager => true,
597            };
598            menu = menu.separator().toggleable_entry(
599                "Eager Preview Mode",
600                is_eager_preview_enabled,
601                IconPosition::Start,
602                None,
603                {
604                    let fs = fs.clone();
605                    move |_window, cx| {
606                        update_settings_file::<AllLanguageSettings>(
607                            fs.clone(),
608                            cx,
609                            move |settings, _cx| {
610                                let new_mode = match is_eager_preview_enabled {
611                                    true => language::EditPredictionsMode::Subtle,
612                                    false => language::EditPredictionsMode::Eager,
613                                };
614
615                                if let Some(edit_predictions) = settings.edit_predictions.as_mut() {
616                                    edit_predictions.mode = new_mode;
617                                } else {
618                                    settings.edit_predictions =
619                                        Some(language_settings::EditPredictionSettingsContent {
620                                            mode: new_mode,
621                                            ..Default::default()
622                                        });
623                                }
624                            },
625                        );
626                    }
627                },
628            );
629        }
630
631        if let Some(editor_focus_handle) = self.editor_focus_handle.clone() {
632            menu = menu
633                .separator()
634                .entry(
635                    "Predict Edit at Cursor",
636                    Some(Box::new(ShowEditPrediction)),
637                    {
638                        let editor_focus_handle = editor_focus_handle.clone();
639                        move |window, cx| {
640                            editor_focus_handle.dispatch_action(&ShowEditPrediction, window, cx);
641                        }
642                    },
643                )
644                .context(editor_focus_handle);
645        }
646
647        menu
648    }
649
650    fn build_copilot_context_menu(
651        &self,
652        window: &mut Window,
653        cx: &mut Context<Self>,
654    ) -> Entity<ContextMenu> {
655        ContextMenu::build(window, cx, |menu, window, cx| {
656            self.build_language_settings_menu(menu, window, cx)
657                .separator()
658                .link(
659                    "Go to Copilot Settings",
660                    OpenBrowser {
661                        url: COPILOT_SETTINGS_URL.to_string(),
662                    }
663                    .boxed_clone(),
664                )
665                .action("Sign Out", copilot::SignOut.boxed_clone())
666        })
667    }
668
669    fn build_supermaven_context_menu(
670        &self,
671        window: &mut Window,
672        cx: &mut Context<Self>,
673    ) -> Entity<ContextMenu> {
674        ContextMenu::build(window, cx, |menu, window, cx| {
675            self.build_language_settings_menu(menu, window, cx)
676                .separator()
677                .action("Sign Out", supermaven::SignOut.boxed_clone())
678        })
679    }
680
681    fn build_zeta_context_menu(
682        &self,
683        window: &mut Window,
684        cx: &mut Context<Self>,
685    ) -> Entity<ContextMenu> {
686        ContextMenu::build(window, cx, |menu, window, cx| {
687            self.build_language_settings_menu(menu, window, cx).when(
688                cx.has_flag::<PredictEditsRateCompletionsFeatureFlag>(),
689                |this| this.action("Rate Completions", RateCompletions.boxed_clone()),
690            )
691        })
692    }
693
694    pub fn update_enabled(&mut self, editor: Entity<Editor>, cx: &mut Context<Self>) {
695        let editor = editor.read(cx);
696        let snapshot = editor.buffer().read(cx).snapshot(cx);
697        let suggestion_anchor = editor.selections.newest_anchor().start;
698        let language = snapshot.language_at(suggestion_anchor);
699        let file = snapshot.file_at(suggestion_anchor).cloned();
700        self.editor_enabled = {
701            let file = file.as_ref();
702            Some(
703                file.map(|file| {
704                    all_language_settings(Some(file), cx)
705                        .edit_predictions_enabled_for_file(file, cx)
706                })
707                .unwrap_or(true),
708            )
709        };
710        self.editor_show_predictions = editor.edit_predictions_enabled();
711        self.edit_prediction_provider = editor.edit_prediction_provider();
712        self.language = language.cloned();
713        self.file = file;
714        self.editor_focus_handle = Some(editor.focus_handle(cx));
715
716        cx.notify();
717    }
718
719    pub fn toggle_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) {
720        self.popover_menu_handle.toggle(window, cx);
721    }
722}
723
724impl StatusItemView for InlineCompletionButton {
725    fn set_active_pane_item(
726        &mut self,
727        item: Option<&dyn ItemHandle>,
728        _: &mut Window,
729        cx: &mut Context<Self>,
730    ) {
731        if let Some(editor) = item.and_then(|item| item.act_as::<Editor>(cx)) {
732            self.editor_subscription = Some((
733                cx.observe(&editor, Self::update_enabled),
734                editor.entity_id().as_u64() as usize,
735            ));
736            self.update_enabled(editor, cx);
737        } else {
738            self.language = None;
739            self.editor_subscription = None;
740            self.editor_enabled = None;
741        }
742        cx.notify();
743    }
744}
745
746impl SupermavenButtonStatus {
747    fn to_icon(&self) -> IconName {
748        match self {
749            SupermavenButtonStatus::Ready => IconName::Supermaven,
750            SupermavenButtonStatus::Errored(_) => IconName::SupermavenError,
751            SupermavenButtonStatus::NeedsActivation(_) => IconName::SupermavenInit,
752            SupermavenButtonStatus::Initializing => IconName::SupermavenInit,
753        }
754    }
755
756    fn to_tooltip(&self) -> String {
757        match self {
758            SupermavenButtonStatus::Ready => "Supermaven is ready".to_string(),
759            SupermavenButtonStatus::Errored(error) => format!("Supermaven error: {}", error),
760            SupermavenButtonStatus::NeedsActivation(_) => "Supermaven needs activation".to_string(),
761            SupermavenButtonStatus::Initializing => "Supermaven initializing".to_string(),
762        }
763    }
764
765    fn has_menu(&self) -> bool {
766        match self {
767            SupermavenButtonStatus::Ready | SupermavenButtonStatus::NeedsActivation(_) => true,
768            SupermavenButtonStatus::Errored(_) | SupermavenButtonStatus::Initializing => false,
769        }
770    }
771}
772
773async fn open_disabled_globs_setting_in_editor(
774    workspace: WeakEntity<Workspace>,
775    mut cx: AsyncWindowContext,
776) -> Result<()> {
777    let settings_editor = workspace
778        .update_in(&mut cx, |_, window, cx| {
779            create_and_open_local_file(paths::settings_file(), window, cx, || {
780                settings::initial_user_settings_content().as_ref().into()
781            })
782        })?
783        .await?
784        .downcast::<Editor>()
785        .unwrap();
786
787    settings_editor
788        .downgrade()
789        .update_in(&mut cx, |item, window, cx| {
790            let text = item.buffer().read(cx).snapshot(cx).text();
791
792            let settings = cx.global::<SettingsStore>();
793
794            // Ensure that we always have "inline_completions { "disabled_globs": [] }"
795            let edits = settings.edits_for_update::<AllLanguageSettings>(&text, |file| {
796                file.edit_predictions
797                    .get_or_insert_with(Default::default)
798                    .disabled_globs
799                    .get_or_insert_with(Vec::new);
800            });
801
802            if !edits.is_empty() {
803                item.edit(edits.iter().cloned(), cx);
804            }
805
806            let text = item.buffer().read(cx).snapshot(cx).text();
807
808            static DISABLED_GLOBS_REGEX: LazyLock<Regex> = LazyLock::new(|| {
809                Regex::new(r#""disabled_globs":\s*\[\s*(?P<content>(?:.|\n)*?)\s*\]"#).unwrap()
810            });
811            // Only capture [...]
812            let range = DISABLED_GLOBS_REGEX.captures(&text).and_then(|captures| {
813                captures
814                    .name("content")
815                    .map(|inner_match| inner_match.start()..inner_match.end())
816            });
817            if let Some(range) = range {
818                item.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
819                    selections.select_ranges(vec![range]);
820                });
821            }
822        })?;
823
824    anyhow::Ok(())
825}
826
827fn toggle_inline_completions_globally(fs: Arc<dyn Fs>, cx: &mut App) {
828    let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
829    update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
830        file.defaults.show_edit_predictions = Some(!show_edit_predictions)
831    });
832}
833
834fn set_completion_provider(fs: Arc<dyn Fs>, cx: &mut App, provider: EditPredictionProvider) {
835    update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
836        file.features
837            .get_or_insert(Default::default())
838            .edit_prediction_provider = Some(provider);
839    });
840}
841
842fn toggle_show_inline_completions_for_language(
843    language: Arc<Language>,
844    fs: Arc<dyn Fs>,
845    cx: &mut App,
846) {
847    let show_edit_predictions =
848        all_language_settings(None, cx).show_edit_predictions(Some(&language), cx);
849    update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
850        file.languages
851            .entry(language.name())
852            .or_default()
853            .show_edit_predictions = Some(!show_edit_predictions);
854    });
855}
856
857fn hide_copilot(fs: Arc<dyn Fs>, cx: &mut App) {
858    update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
859        file.features
860            .get_or_insert(Default::default())
861            .edit_prediction_provider = Some(EditPredictionProvider::None);
862    });
863}