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