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