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