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