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