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