1use anyhow::Result;
2use copilot::{Copilot, Status};
3use editor::{scroll::Autoscroll, Editor};
4use feature_flags::{FeatureFlagAppExt, ZetaFeatureFlag};
5use fs::Fs;
6use gpui::{
7 actions, div, Action, AppContext, AsyncWindowContext, Corner, Entity, IntoElement,
8 ParentElement, Render, Subscription, View, ViewContext, WeakView, WindowContext,
9};
10use language::{
11 language_settings::{
12 self, all_language_settings, AllLanguageSettings, InlineCompletionProvider,
13 },
14 File, Language,
15};
16use settings::{update_settings_file, Settings, SettingsStore};
17use std::{path::Path, sync::Arc};
18use supermaven::{AccountStatus, Supermaven};
19use workspace::{
20 create_and_open_local_file,
21 item::ItemHandle,
22 notifications::NotificationId,
23 ui::{
24 ButtonCommon, Clickable, ContextMenu, IconButton, IconName, IconSize, PopoverMenu, Tooltip,
25 },
26 StatusItemView, Toast, Workspace,
27};
28use zed_actions::OpenBrowser;
29use zeta::RateCompletionModal;
30
31actions!(zeta, [RateCompletions]);
32
33const COPILOT_SETTINGS_URL: &str = "https://github.com/settings/copilot";
34
35struct CopilotErrorToast;
36
37pub struct InlineCompletionButton {
38 editor_subscription: Option<(Subscription, usize)>,
39 editor_enabled: Option<bool>,
40 language: Option<Arc<Language>>,
41 file: Option<Arc<dyn File>>,
42 fs: Arc<dyn Fs>,
43 workspace: WeakView<Workspace>,
44}
45
46enum SupermavenButtonStatus {
47 Ready,
48 Errored(String),
49 NeedsActivation(String),
50 Initializing,
51}
52
53impl Render for InlineCompletionButton {
54 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
55 let all_language_settings = all_language_settings(None, cx);
56
57 match all_language_settings.inline_completions.provider {
58 InlineCompletionProvider::None => div(),
59
60 InlineCompletionProvider::Copilot => {
61 let Some(copilot) = Copilot::global(cx) else {
62 return div();
63 };
64 let status = copilot.read(cx).status();
65
66 let enabled = self.editor_enabled.unwrap_or_else(|| {
67 all_language_settings.inline_completions_enabled(None, None, cx)
68 });
69
70 let icon = match status {
71 Status::Error(_) => IconName::CopilotError,
72 Status::Authorized => {
73 if enabled {
74 IconName::Copilot
75 } else {
76 IconName::CopilotDisabled
77 }
78 }
79 _ => IconName::CopilotInit,
80 };
81
82 if let Status::Error(e) = status {
83 return div().child(
84 IconButton::new("copilot-error", icon)
85 .icon_size(IconSize::Small)
86 .on_click(cx.listener(move |_, _, cx| {
87 if let Some(workspace) = cx.window_handle().downcast::<Workspace>()
88 {
89 workspace
90 .update(cx, |workspace, cx| {
91 workspace.show_toast(
92 Toast::new(
93 NotificationId::unique::<CopilotErrorToast>(),
94 format!("Copilot can't be started: {}", e),
95 )
96 .on_click("Reinstall Copilot", |cx| {
97 if let Some(copilot) = Copilot::global(cx) {
98 copilot
99 .update(cx, |copilot, cx| {
100 copilot.reinstall(cx)
101 })
102 .detach();
103 }
104 }),
105 cx,
106 );
107 })
108 .ok();
109 }
110 }))
111 .tooltip(|cx| Tooltip::text("GitHub Copilot", cx)),
112 );
113 }
114 let this = cx.view().clone();
115
116 div().child(
117 PopoverMenu::new("copilot")
118 .menu(move |cx| {
119 Some(match status {
120 Status::Authorized => {
121 this.update(cx, |this, cx| this.build_copilot_context_menu(cx))
122 }
123 _ => this.update(cx, |this, cx| this.build_copilot_start_menu(cx)),
124 })
125 })
126 .anchor(Corner::BottomRight)
127 .trigger(
128 IconButton::new("copilot-icon", icon)
129 .tooltip(|cx| Tooltip::text("GitHub Copilot", cx)),
130 ),
131 )
132 }
133
134 InlineCompletionProvider::Supermaven => {
135 let Some(supermaven) = Supermaven::global(cx) else {
136 return div();
137 };
138
139 let supermaven = supermaven.read(cx);
140
141 let status = match supermaven {
142 Supermaven::Starting => SupermavenButtonStatus::Initializing,
143 Supermaven::FailedDownload { error } => {
144 SupermavenButtonStatus::Errored(error.to_string())
145 }
146 Supermaven::Spawned(agent) => {
147 let account_status = agent.account_status.clone();
148 match account_status {
149 AccountStatus::NeedsActivation { activate_url } => {
150 SupermavenButtonStatus::NeedsActivation(activate_url.clone())
151 }
152 AccountStatus::Unknown => SupermavenButtonStatus::Initializing,
153 AccountStatus::Ready => SupermavenButtonStatus::Ready,
154 }
155 }
156 Supermaven::Error { error } => {
157 SupermavenButtonStatus::Errored(error.to_string())
158 }
159 };
160
161 let icon = status.to_icon();
162 let tooltip_text = status.to_tooltip();
163 let this = cx.view().clone();
164 let fs = self.fs.clone();
165
166 return div().child(
167 PopoverMenu::new("supermaven")
168 .menu(move |cx| match &status {
169 SupermavenButtonStatus::NeedsActivation(activate_url) => {
170 Some(ContextMenu::build(cx, |menu, _| {
171 let fs = fs.clone();
172 let activate_url = activate_url.clone();
173 menu.entry("Sign In", None, move |cx| {
174 cx.open_url(activate_url.as_str())
175 })
176 .entry(
177 "Use Copilot",
178 None,
179 move |cx| {
180 set_completion_provider(
181 fs.clone(),
182 cx,
183 InlineCompletionProvider::Copilot,
184 )
185 },
186 )
187 }))
188 }
189 SupermavenButtonStatus::Ready => Some(
190 this.update(cx, |this, cx| this.build_supermaven_context_menu(cx)),
191 ),
192 _ => None,
193 })
194 .anchor(Corner::BottomRight)
195 .trigger(
196 IconButton::new("supermaven-icon", icon)
197 .tooltip(move |cx| Tooltip::text(tooltip_text.clone(), cx)),
198 ),
199 );
200 }
201
202 InlineCompletionProvider::Zeta => {
203 if !cx.has_flag::<ZetaFeatureFlag>() {
204 return div();
205 }
206
207 let this = cx.view().clone();
208 div().child(
209 PopoverMenu::new("zeta")
210 .menu(move |cx| {
211 Some(this.update(cx, |this, cx| this.build_zeta_context_menu(cx)))
212 })
213 .anchor(Corner::BottomRight)
214 .trigger(
215 IconButton::new("zeta", IconName::ZedPredict)
216 .tooltip(|cx| Tooltip::text("Zed Predict", cx)),
217 ),
218 )
219 }
220 }
221 }
222}
223
224impl InlineCompletionButton {
225 pub fn new(
226 workspace: WeakView<Workspace>,
227 fs: Arc<dyn Fs>,
228 cx: &mut ViewContext<Self>,
229 ) -> Self {
230 if let Some(copilot) = Copilot::global(cx) {
231 cx.observe(&copilot, |_, _, cx| cx.notify()).detach()
232 }
233
234 cx.observe_global::<SettingsStore>(move |_, cx| cx.notify())
235 .detach();
236
237 Self {
238 editor_subscription: None,
239 editor_enabled: None,
240 language: None,
241 file: None,
242 workspace,
243 fs,
244 }
245 }
246
247 pub fn build_copilot_start_menu(&mut self, cx: &mut ViewContext<Self>) -> View<ContextMenu> {
248 let fs = self.fs.clone();
249 ContextMenu::build(cx, |menu, _| {
250 menu.entry("Sign In", None, copilot::initiate_sign_in)
251 .entry("Disable Copilot", None, {
252 let fs = fs.clone();
253 move |cx| hide_copilot(fs.clone(), cx)
254 })
255 .entry("Use Supermaven", None, {
256 let fs = fs.clone();
257 move |cx| {
258 set_completion_provider(
259 fs.clone(),
260 cx,
261 InlineCompletionProvider::Supermaven,
262 )
263 }
264 })
265 })
266 }
267
268 pub fn build_language_settings_menu(
269 &self,
270 mut menu: ContextMenu,
271 cx: &mut WindowContext,
272 ) -> ContextMenu {
273 let fs = self.fs.clone();
274
275 if let Some(language) = self.language.clone() {
276 let fs = fs.clone();
277 let language_enabled =
278 language_settings::language_settings(Some(language.name()), None, cx)
279 .show_inline_completions;
280
281 menu = menu.entry(
282 format!(
283 "{} Inline Completions for {}",
284 if language_enabled { "Hide" } else { "Show" },
285 language.name()
286 ),
287 None,
288 move |cx| toggle_inline_completions_for_language(language.clone(), fs.clone(), cx),
289 );
290 }
291
292 let settings = AllLanguageSettings::get_global(cx);
293
294 if let Some(file) = &self.file {
295 let path = file.path().clone();
296 let path_enabled = settings.inline_completions_enabled_for_path(&path);
297
298 menu = menu.entry(
299 format!(
300 "{} Inline Completions for This Path",
301 if path_enabled { "Hide" } else { "Show" }
302 ),
303 None,
304 move |cx| {
305 if let Some(workspace) = cx.window_handle().downcast::<Workspace>() {
306 if let Ok(workspace) = workspace.root_view(cx) {
307 let workspace = workspace.downgrade();
308 cx.spawn(|cx| {
309 configure_disabled_globs(
310 workspace,
311 path_enabled.then_some(path.clone()),
312 cx,
313 )
314 })
315 .detach_and_log_err(cx);
316 }
317 }
318 },
319 );
320 }
321
322 let globally_enabled = settings.inline_completions_enabled(None, None, cx);
323 menu.entry(
324 if globally_enabled {
325 "Hide Inline Completions for All Files"
326 } else {
327 "Show Inline Completions for All Files"
328 },
329 None,
330 move |cx| toggle_inline_completions_globally(fs.clone(), cx),
331 )
332 }
333
334 fn build_copilot_context_menu(&self, cx: &mut ViewContext<Self>) -> View<ContextMenu> {
335 ContextMenu::build(cx, |menu, cx| {
336 self.build_language_settings_menu(menu, cx)
337 .separator()
338 .link(
339 "Go to Copilot Settings",
340 OpenBrowser {
341 url: COPILOT_SETTINGS_URL.to_string(),
342 }
343 .boxed_clone(),
344 )
345 .action("Sign Out", copilot::SignOut.boxed_clone())
346 })
347 }
348
349 fn build_supermaven_context_menu(&self, cx: &mut ViewContext<Self>) -> View<ContextMenu> {
350 ContextMenu::build(cx, |menu, cx| {
351 self.build_language_settings_menu(menu, cx)
352 .separator()
353 .action("Sign Out", supermaven::SignOut.boxed_clone())
354 })
355 }
356
357 fn build_zeta_context_menu(&self, cx: &mut ViewContext<Self>) -> View<ContextMenu> {
358 let workspace = self.workspace.clone();
359 ContextMenu::build(cx, |menu, cx| {
360 self.build_language_settings_menu(menu, cx)
361 .separator()
362 .entry(
363 "Rate Completions",
364 Some(RateCompletions.boxed_clone()),
365 move |cx| {
366 workspace
367 .update(cx, |workspace, cx| {
368 RateCompletionModal::toggle(workspace, cx)
369 })
370 .ok();
371 },
372 )
373 })
374 }
375
376 pub fn update_enabled(&mut self, editor: View<Editor>, cx: &mut ViewContext<Self>) {
377 let editor = editor.read(cx);
378 let snapshot = editor.buffer().read(cx).snapshot(cx);
379 let suggestion_anchor = editor.selections.newest_anchor().start;
380 let language = snapshot.language_at(suggestion_anchor);
381 let file = snapshot.file_at(suggestion_anchor).cloned();
382 self.editor_enabled = {
383 let file = file.as_ref();
384 Some(
385 file.map(|file| !file.is_private()).unwrap_or(true)
386 && all_language_settings(file, cx).inline_completions_enabled(
387 language,
388 file.map(|file| file.path().as_ref()),
389 cx,
390 ),
391 )
392 };
393 self.language = language.cloned();
394 self.file = file;
395
396 cx.notify()
397 }
398}
399
400impl StatusItemView for InlineCompletionButton {
401 fn set_active_pane_item(&mut self, item: Option<&dyn ItemHandle>, cx: &mut ViewContext<Self>) {
402 if let Some(editor) = item.and_then(|item| item.act_as::<Editor>(cx)) {
403 self.editor_subscription = Some((
404 cx.observe(&editor, Self::update_enabled),
405 editor.entity_id().as_u64() as usize,
406 ));
407 self.update_enabled(editor, cx);
408 } else {
409 self.language = None;
410 self.editor_subscription = None;
411 self.editor_enabled = None;
412 }
413 cx.notify();
414 }
415}
416
417impl SupermavenButtonStatus {
418 fn to_icon(&self) -> IconName {
419 match self {
420 SupermavenButtonStatus::Ready => IconName::Supermaven,
421 SupermavenButtonStatus::Errored(_) => IconName::SupermavenError,
422 SupermavenButtonStatus::NeedsActivation(_) => IconName::SupermavenInit,
423 SupermavenButtonStatus::Initializing => IconName::SupermavenInit,
424 }
425 }
426
427 fn to_tooltip(&self) -> String {
428 match self {
429 SupermavenButtonStatus::Ready => "Supermaven is ready".to_string(),
430 SupermavenButtonStatus::Errored(error) => format!("Supermaven error: {}", error),
431 SupermavenButtonStatus::NeedsActivation(_) => "Supermaven needs activation".to_string(),
432 SupermavenButtonStatus::Initializing => "Supermaven initializing".to_string(),
433 }
434 }
435}
436
437async fn configure_disabled_globs(
438 workspace: WeakView<Workspace>,
439 path_to_disable: Option<Arc<Path>>,
440 mut cx: AsyncWindowContext,
441) -> Result<()> {
442 let settings_editor = workspace
443 .update(&mut cx, |_, cx| {
444 create_and_open_local_file(paths::settings_file(), cx, || {
445 settings::initial_user_settings_content().as_ref().into()
446 })
447 })?
448 .await?
449 .downcast::<Editor>()
450 .unwrap();
451
452 settings_editor.downgrade().update(&mut cx, |item, cx| {
453 let text = item.buffer().read(cx).snapshot(cx).text();
454
455 let settings = cx.global::<SettingsStore>();
456 let edits = settings.edits_for_update::<AllLanguageSettings>(&text, |file| {
457 let copilot = file.inline_completions.get_or_insert_with(Default::default);
458 let globs = copilot.disabled_globs.get_or_insert_with(|| {
459 settings
460 .get::<AllLanguageSettings>(None)
461 .inline_completions
462 .disabled_globs
463 .iter()
464 .map(|glob| glob.glob().to_string())
465 .collect()
466 });
467
468 if let Some(path_to_disable) = &path_to_disable {
469 globs.push(path_to_disable.to_string_lossy().into_owned());
470 } else {
471 globs.clear();
472 }
473 });
474
475 if !edits.is_empty() {
476 item.change_selections(Some(Autoscroll::newest()), cx, |selections| {
477 selections.select_ranges(edits.iter().map(|e| e.0.clone()));
478 });
479
480 // When *enabling* a path, don't actually perform an edit, just select the range.
481 if path_to_disable.is_some() {
482 item.edit(edits.iter().cloned(), cx);
483 }
484 }
485 })?;
486
487 anyhow::Ok(())
488}
489
490fn toggle_inline_completions_globally(fs: Arc<dyn Fs>, cx: &mut AppContext) {
491 let show_inline_completions =
492 all_language_settings(None, cx).inline_completions_enabled(None, None, cx);
493 update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
494 file.defaults.show_inline_completions = Some(!show_inline_completions)
495 });
496}
497
498fn set_completion_provider(
499 fs: Arc<dyn Fs>,
500 cx: &mut AppContext,
501 provider: InlineCompletionProvider,
502) {
503 update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
504 file.features
505 .get_or_insert(Default::default())
506 .inline_completion_provider = Some(provider);
507 });
508}
509
510fn toggle_inline_completions_for_language(
511 language: Arc<Language>,
512 fs: Arc<dyn Fs>,
513 cx: &mut AppContext,
514) {
515 let show_inline_completions =
516 all_language_settings(None, cx).inline_completions_enabled(Some(&language), None, cx);
517 update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
518 file.languages
519 .entry(language.name())
520 .or_default()
521 .show_inline_completions = Some(!show_inline_completions);
522 });
523}
524
525fn hide_copilot(fs: Arc<dyn Fs>, cx: &mut AppContext) {
526 update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
527 file.features
528 .get_or_insert(Default::default())
529 .inline_completion_provider = Some(InlineCompletionProvider::None);
530 });
531}