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, IconButton, IconButtonShape, Indicator, PopoverMenu,
30 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 |_, cx| {
108 if let Some(copilot) = Copilot::global(cx) {
109 copilot
110 .update(cx, |copilot, cx| {
111 copilot.reinstall(cx)
112 })
113 .detach();
114 }
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
245 if !current_user_terms_accepted.unwrap_or(false) {
246 let signed_in = current_user_terms_accepted.is_some();
247 let tooltip_meta = if signed_in {
248 "Read Terms of Service"
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(provider) = self.edit_prediction_provider.as_ref() {
407 if let Some(usage) = provider.usage(cx) {
408 menu = menu.header("Usage");
409 menu = menu.custom_entry(
410 move |_window, cx| {
411 let used_percentage = match usage.limit {
412 UsageLimit::Limited(limit) => {
413 Some((usage.amount as f32 / limit as f32) * 100.)
414 }
415 UsageLimit::Unlimited => None,
416 };
417
418 h_flex()
419 .flex_1()
420 .gap_1p5()
421 .children(
422 used_percentage
423 .map(|percent| ProgressBar::new("usage", percent, 100., cx)),
424 )
425 .child(
426 Label::new(match usage.limit {
427 UsageLimit::Limited(limit) => {
428 format!("{} / {limit}", usage.amount)
429 }
430 UsageLimit::Unlimited => format!("{} / ∞", usage.amount),
431 })
432 .size(LabelSize::Small)
433 .color(Color::Muted),
434 )
435 .into_any_element()
436 },
437 move |_, cx| cx.open_url(&zed_urls::account_url(cx)),
438 );
439 }
440 }
441
442 menu = menu.header("Show Edit Predictions For");
443
444 let language_state = self.language.as_ref().map(|language| {
445 (
446 language.clone(),
447 language_settings::language_settings(Some(language.name()), None, cx)
448 .show_edit_predictions,
449 )
450 });
451
452 if let Some(editor_focus_handle) = self.editor_focus_handle.clone() {
453 let entry = ContextMenuEntry::new("This Buffer")
454 .toggleable(IconPosition::Start, self.editor_show_predictions)
455 .action(Box::new(ToggleEditPrediction))
456 .handler(move |window, cx| {
457 editor_focus_handle.dispatch_action(&ToggleEditPrediction, window, cx);
458 });
459
460 match language_state.clone() {
461 Some((language, false)) => {
462 menu = menu.item(
463 entry
464 .disabled(true)
465 .documentation_aside(move |_cx| {
466 Label::new(format!("Edit predictions cannot be toggled for this buffer because they are disabled for {}", language.name()))
467 .into_any_element()
468 })
469 );
470 }
471 Some(_) | None => menu = menu.item(entry),
472 }
473 }
474
475 if let Some((language, language_enabled)) = language_state {
476 let fs = fs.clone();
477
478 menu = menu.toggleable_entry(
479 language.name(),
480 language_enabled,
481 IconPosition::Start,
482 None,
483 move |_, cx| {
484 toggle_show_inline_completions_for_language(language.clone(), fs.clone(), cx)
485 },
486 );
487 }
488
489 let settings = AllLanguageSettings::get_global(cx);
490
491 let globally_enabled = settings.show_edit_predictions(None, cx);
492 menu = menu.toggleable_entry("All Files", globally_enabled, IconPosition::Start, None, {
493 let fs = fs.clone();
494 move |_, cx| toggle_inline_completions_globally(fs.clone(), cx)
495 });
496
497 let provider = settings.edit_predictions.provider;
498 let current_mode = settings.edit_predictions_mode();
499 let subtle_mode = matches!(current_mode, EditPredictionsMode::Subtle);
500 let eager_mode = matches!(current_mode, EditPredictionsMode::Eager);
501
502 if matches!(provider, EditPredictionProvider::Zed) {
503 menu = menu
504 .separator()
505 .header("Display Modes")
506 .item(
507 ContextMenuEntry::new("Eager")
508 .toggleable(IconPosition::Start, eager_mode)
509 .documentation_aside(move |_| {
510 Label::new("Display predictions inline when there are no language server completions available.").into_any_element()
511 })
512 .handler({
513 let fs = fs.clone();
514 move |_, cx| {
515 toggle_edit_prediction_mode(fs.clone(), EditPredictionsMode::Eager, cx)
516 }
517 }),
518 )
519 .item(
520 ContextMenuEntry::new("Subtle")
521 .toggleable(IconPosition::Start, subtle_mode)
522 .documentation_aside(move |_| {
523 Label::new("Display predictions inline only when holding a modifier key (alt by default).").into_any_element()
524 })
525 .handler({
526 let fs = fs.clone();
527 move |_, cx| {
528 toggle_edit_prediction_mode(fs.clone(), EditPredictionsMode::Subtle, cx)
529 }
530 }),
531 );
532 }
533
534 menu = menu.separator().header("Privacy Settings");
535 if let Some(provider) = &self.edit_prediction_provider {
536 let data_collection = provider.data_collection_state(cx);
537 if data_collection.is_supported() {
538 let provider = provider.clone();
539 let enabled = data_collection.is_enabled();
540 let is_open_source = data_collection.is_project_open_source();
541 let is_collecting = data_collection.is_enabled();
542 let (icon_name, icon_color) = if is_open_source && is_collecting {
543 (IconName::Check, Color::Success)
544 } else {
545 (IconName::Check, Color::Accent)
546 };
547
548 menu = menu.item(
549 ContextMenuEntry::new("Training Data Collection")
550 .toggleable(IconPosition::Start, data_collection.is_enabled())
551 .icon(icon_name)
552 .icon_color(icon_color)
553 .documentation_aside(move |cx| {
554 let (msg, label_color, icon_name, icon_color) = match (is_open_source, is_collecting) {
555 (true, true) => (
556 "Project identified as open source, and you're sharing data.",
557 Color::Default,
558 IconName::Check,
559 Color::Success,
560 ),
561 (true, false) => (
562 "Project identified as open source, but you're not sharing data.",
563 Color::Muted,
564 IconName::Close,
565 Color::Muted,
566 ),
567 (false, true) => (
568 "Project not identified as open source. No data captured.",
569 Color::Muted,
570 IconName::Close,
571 Color::Muted,
572 ),
573 (false, false) => (
574 "Project not identified as open source, and setting turned off.",
575 Color::Muted,
576 IconName::Close,
577 Color::Muted,
578 ),
579 };
580 v_flex()
581 .gap_2()
582 .child(
583 Label::new(indoc!{
584 "Help us improve our open dataset model by sharing data from open source repositories. \
585 Zed must detect a license file in your repo for this setting to take effect."
586 })
587 )
588 .child(
589 h_flex()
590 .items_start()
591 .pt_2()
592 .flex_1()
593 .gap_1p5()
594 .border_t_1()
595 .border_color(cx.theme().colors().border_variant)
596 .child(h_flex().flex_shrink_0().h(line_height).child(Icon::new(icon_name).size(IconSize::XSmall).color(icon_color)))
597 .child(div().child(msg).w_full().text_sm().text_color(label_color.color(cx)))
598 )
599 .into_any_element()
600 })
601 .handler(move |_, cx| {
602 provider.toggle_data_collection(cx);
603
604 if !enabled {
605 telemetry::event!(
606 "Data Collection Enabled",
607 source = "Edit Prediction Status Menu"
608 );
609 } else {
610 telemetry::event!(
611 "Data Collection Disabled",
612 source = "Edit Prediction Status Menu"
613 );
614 }
615 })
616 );
617
618 if is_collecting && !is_open_source {
619 menu = menu.item(
620 ContextMenuEntry::new("No data captured.")
621 .disabled(true)
622 .icon(IconName::Close)
623 .icon_color(Color::Error)
624 .icon_size(IconSize::Small),
625 );
626 }
627 }
628 }
629
630 menu = menu.item(
631 ContextMenuEntry::new("Configure Excluded Files")
632 .icon(IconName::LockOutlined)
633 .icon_color(Color::Muted)
634 .documentation_aside(|_| {
635 Label::new(indoc!{"
636 Open your settings to add sensitive paths for which Zed will never predict edits."}).into_any_element()
637 })
638 .handler(move |window, cx| {
639 if let Some(workspace) = window.root().flatten() {
640 let workspace = workspace.downgrade();
641 window
642 .spawn(cx, async |cx| {
643 open_disabled_globs_setting_in_editor(
644 workspace,
645 cx,
646 ).await
647 })
648 .detach_and_log_err(cx);
649 }
650 }),
651 );
652
653 if !self.editor_enabled.unwrap_or(true) {
654 menu = menu.item(
655 ContextMenuEntry::new("This file is excluded.")
656 .disabled(true)
657 .icon(IconName::ZedPredictDisabled)
658 .icon_size(IconSize::Small),
659 );
660 }
661
662 if let Some(editor_focus_handle) = self.editor_focus_handle.clone() {
663 menu = menu
664 .separator()
665 .entry(
666 "Predict Edit at Cursor",
667 Some(Box::new(ShowEditPrediction)),
668 {
669 let editor_focus_handle = editor_focus_handle.clone();
670 move |window, cx| {
671 editor_focus_handle.dispatch_action(&ShowEditPrediction, window, cx);
672 }
673 },
674 )
675 .context(editor_focus_handle);
676 }
677
678 menu
679 }
680
681 fn build_copilot_context_menu(
682 &self,
683 window: &mut Window,
684 cx: &mut Context<Self>,
685 ) -> Entity<ContextMenu> {
686 ContextMenu::build(window, cx, |menu, window, cx| {
687 self.build_language_settings_menu(menu, window, cx)
688 .separator()
689 .link(
690 "Go to Copilot Settings",
691 OpenBrowser {
692 url: COPILOT_SETTINGS_URL.to_string(),
693 }
694 .boxed_clone(),
695 )
696 .action("Sign Out", copilot::SignOut.boxed_clone())
697 })
698 }
699
700 fn build_supermaven_context_menu(
701 &self,
702 window: &mut Window,
703 cx: &mut Context<Self>,
704 ) -> Entity<ContextMenu> {
705 ContextMenu::build(window, cx, |menu, window, cx| {
706 self.build_language_settings_menu(menu, window, cx)
707 .separator()
708 .action("Sign Out", supermaven::SignOut.boxed_clone())
709 })
710 }
711
712 fn build_zeta_context_menu(
713 &self,
714 window: &mut Window,
715 cx: &mut Context<Self>,
716 ) -> Entity<ContextMenu> {
717 ContextMenu::build(window, cx, |menu, window, cx| {
718 self.build_language_settings_menu(menu, window, cx).when(
719 cx.has_flag::<PredictEditsRateCompletionsFeatureFlag>(),
720 |this| this.action("Rate Completions", RateCompletions.boxed_clone()),
721 )
722 })
723 }
724
725 pub fn update_enabled(&mut self, editor: Entity<Editor>, cx: &mut Context<Self>) {
726 let editor = editor.read(cx);
727 let snapshot = editor.buffer().read(cx).snapshot(cx);
728 let suggestion_anchor = editor.selections.newest_anchor().start;
729 let language = snapshot.language_at(suggestion_anchor);
730 let file = snapshot.file_at(suggestion_anchor).cloned();
731 self.editor_enabled = {
732 let file = file.as_ref();
733 Some(
734 file.map(|file| {
735 all_language_settings(Some(file), cx)
736 .edit_predictions_enabled_for_file(file, cx)
737 })
738 .unwrap_or(true),
739 )
740 };
741 self.editor_show_predictions = editor.edit_predictions_enabled();
742 self.edit_prediction_provider = editor.edit_prediction_provider();
743 self.language = language.cloned();
744 self.file = file;
745 self.editor_focus_handle = Some(editor.focus_handle(cx));
746
747 cx.notify();
748 }
749
750 pub fn toggle_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) {
751 self.popover_menu_handle.toggle(window, cx);
752 }
753}
754
755impl StatusItemView for InlineCompletionButton {
756 fn set_active_pane_item(
757 &mut self,
758 item: Option<&dyn ItemHandle>,
759 _: &mut Window,
760 cx: &mut Context<Self>,
761 ) {
762 if let Some(editor) = item.and_then(|item| item.act_as::<Editor>(cx)) {
763 self.editor_subscription = Some((
764 cx.observe(&editor, Self::update_enabled),
765 editor.entity_id().as_u64() as usize,
766 ));
767 self.update_enabled(editor, cx);
768 } else {
769 self.language = None;
770 self.editor_subscription = None;
771 self.editor_enabled = None;
772 }
773 cx.notify();
774 }
775}
776
777impl SupermavenButtonStatus {
778 fn to_icon(&self) -> IconName {
779 match self {
780 SupermavenButtonStatus::Ready => IconName::Supermaven,
781 SupermavenButtonStatus::Errored(_) => IconName::SupermavenError,
782 SupermavenButtonStatus::NeedsActivation(_) => IconName::SupermavenInit,
783 SupermavenButtonStatus::Initializing => IconName::SupermavenInit,
784 }
785 }
786
787 fn to_tooltip(&self) -> String {
788 match self {
789 SupermavenButtonStatus::Ready => "Supermaven is ready".to_string(),
790 SupermavenButtonStatus::Errored(error) => format!("Supermaven error: {}", error),
791 SupermavenButtonStatus::NeedsActivation(_) => "Supermaven needs activation".to_string(),
792 SupermavenButtonStatus::Initializing => "Supermaven initializing".to_string(),
793 }
794 }
795
796 fn has_menu(&self) -> bool {
797 match self {
798 SupermavenButtonStatus::Ready | SupermavenButtonStatus::NeedsActivation(_) => true,
799 SupermavenButtonStatus::Errored(_) | SupermavenButtonStatus::Initializing => false,
800 }
801 }
802}
803
804async fn open_disabled_globs_setting_in_editor(
805 workspace: WeakEntity<Workspace>,
806 cx: &mut AsyncWindowContext,
807) -> Result<()> {
808 let settings_editor = workspace
809 .update_in(cx, |_, window, cx| {
810 create_and_open_local_file(paths::settings_file(), window, cx, || {
811 settings::initial_user_settings_content().as_ref().into()
812 })
813 })?
814 .await?
815 .downcast::<Editor>()
816 .unwrap();
817
818 settings_editor
819 .downgrade()
820 .update_in(cx, |item, window, cx| {
821 let text = item.buffer().read(cx).snapshot(cx).text();
822
823 let settings = cx.global::<SettingsStore>();
824
825 // Ensure that we always have "inline_completions { "disabled_globs": [] }"
826 let edits = settings.edits_for_update::<AllLanguageSettings>(&text, |file| {
827 file.edit_predictions
828 .get_or_insert_with(Default::default)
829 .disabled_globs
830 .get_or_insert_with(Vec::new);
831 });
832
833 if !edits.is_empty() {
834 item.edit(edits.iter().cloned(), cx);
835 }
836
837 let text = item.buffer().read(cx).snapshot(cx).text();
838
839 static DISABLED_GLOBS_REGEX: LazyLock<Regex> = LazyLock::new(|| {
840 Regex::new(r#""disabled_globs":\s*\[\s*(?P<content>(?:.|\n)*?)\s*\]"#).unwrap()
841 });
842 // Only capture [...]
843 let range = DISABLED_GLOBS_REGEX.captures(&text).and_then(|captures| {
844 captures
845 .name("content")
846 .map(|inner_match| inner_match.start()..inner_match.end())
847 });
848 if let Some(range) = range {
849 item.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
850 selections.select_ranges(vec![range]);
851 });
852 }
853 })?;
854
855 anyhow::Ok(())
856}
857
858fn toggle_inline_completions_globally(fs: Arc<dyn Fs>, cx: &mut App) {
859 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
860 update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
861 file.defaults.show_edit_predictions = Some(!show_edit_predictions)
862 });
863}
864
865fn set_completion_provider(fs: Arc<dyn Fs>, cx: &mut App, provider: EditPredictionProvider) {
866 update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
867 file.features
868 .get_or_insert(Default::default())
869 .edit_prediction_provider = Some(provider);
870 });
871}
872
873fn toggle_show_inline_completions_for_language(
874 language: Arc<Language>,
875 fs: Arc<dyn Fs>,
876 cx: &mut App,
877) {
878 let show_edit_predictions =
879 all_language_settings(None, cx).show_edit_predictions(Some(&language), cx);
880 update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
881 file.languages
882 .entry(language.name())
883 .or_default()
884 .show_edit_predictions = Some(!show_edit_predictions);
885 });
886}
887
888fn hide_copilot(fs: Arc<dyn Fs>, cx: &mut App) {
889 update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
890 file.features
891 .get_or_insert(Default::default())
892 .edit_prediction_provider = Some(EditPredictionProvider::None);
893 });
894}
895
896fn toggle_edit_prediction_mode(fs: Arc<dyn Fs>, mode: EditPredictionsMode, cx: &mut App) {
897 let settings = AllLanguageSettings::get_global(cx);
898 let current_mode = settings.edit_predictions_mode();
899
900 if current_mode != mode {
901 update_settings_file::<AllLanguageSettings>(fs, cx, move |settings, _cx| {
902 if let Some(edit_predictions) = settings.edit_predictions.as_mut() {
903 edit_predictions.mode = mode;
904 } else {
905 settings.edit_predictions =
906 Some(language_settings::EditPredictionSettingsContent {
907 mode,
908 ..Default::default()
909 });
910 }
911 });
912 }
913}