inline_completion_button.rs

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