inline_completion_button.rs

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