copilot_button.rs

  1use crate::sign_in::CopilotCodeVerification;
  2use anyhow::Result;
  3use copilot::{Copilot, SignOut, Status};
  4use editor::{scroll::autoscroll::Autoscroll, Editor};
  5use fs::Fs;
  6use gpui::{
  7    div, Action, AnchorCorner, AppContext, AsyncWindowContext, Entity, IntoElement, ParentElement,
  8    Render, Subscription, View, ViewContext, WeakView, WindowContext,
  9};
 10use language::{
 11    language_settings::{self, all_language_settings, AllLanguageSettings},
 12    File, Language,
 13};
 14use settings::{update_settings_file, Settings, SettingsStore};
 15use std::{path::Path, sync::Arc};
 16use util::{paths, ResultExt};
 17use workspace::{
 18    create_and_open_local_file,
 19    item::ItemHandle,
 20    ui::{popover_menu, ButtonCommon, Clickable, ContextMenu, Icon, IconButton, IconSize, Tooltip},
 21    StatusItemView, Toast, Workspace,
 22};
 23use zed_actions::OpenBrowser;
 24
 25const COPILOT_SETTINGS_URL: &str = "https://github.com/settings/copilot";
 26const COPILOT_STARTING_TOAST_ID: usize = 1337;
 27const COPILOT_ERROR_TOAST_ID: usize = 1338;
 28
 29pub struct CopilotButton {
 30    editor_subscription: Option<(Subscription, usize)>,
 31    editor_enabled: Option<bool>,
 32    language: Option<Arc<Language>>,
 33    file: Option<Arc<dyn File>>,
 34    fs: Arc<dyn Fs>,
 35}
 36
 37impl Render for CopilotButton {
 38    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
 39        let all_language_settings = all_language_settings(None, cx);
 40        if !all_language_settings.copilot.feature_enabled {
 41            return div();
 42        }
 43
 44        let Some(copilot) = Copilot::global(cx) else {
 45            return div();
 46        };
 47        let status = copilot.read(cx).status();
 48
 49        let enabled = self
 50            .editor_enabled
 51            .unwrap_or_else(|| all_language_settings.copilot_enabled(None, None));
 52
 53        let icon = match status {
 54            Status::Error(_) => Icon::CopilotError,
 55            Status::Authorized => {
 56                if enabled {
 57                    Icon::Copilot
 58                } else {
 59                    Icon::CopilotDisabled
 60                }
 61            }
 62            _ => Icon::CopilotInit,
 63        };
 64
 65        if let Status::Error(e) = status {
 66            return div().child(
 67                IconButton::new("copilot-error", icon)
 68                    .icon_size(IconSize::Small)
 69                    .on_click(cx.listener(move |_, _, cx| {
 70                        if let Some(workspace) = cx.window_handle().downcast::<Workspace>() {
 71                            workspace
 72                                .update(cx, |workspace, cx| {
 73                                    workspace.show_toast(
 74                                        Toast::new(
 75                                            COPILOT_ERROR_TOAST_ID,
 76                                            format!("Copilot can't be started: {}", e),
 77                                        )
 78                                        .on_click(
 79                                            "Reinstall Copilot",
 80                                            |cx| {
 81                                                if let Some(copilot) = Copilot::global(cx) {
 82                                                    copilot
 83                                                        .update(cx, |copilot, cx| {
 84                                                            copilot.reinstall(cx)
 85                                                        })
 86                                                        .detach();
 87                                                }
 88                                            },
 89                                        ),
 90                                        cx,
 91                                    );
 92                                })
 93                                .ok();
 94                        }
 95                    }))
 96                    .tooltip(|cx| Tooltip::text("GitHub Copilot", cx)),
 97            );
 98        }
 99        let this = cx.view().clone();
100
101        div().child(
102            popover_menu("copilot")
103                .menu(move |cx| match status {
104                    Status::Authorized => {
105                        Some(this.update(cx, |this, cx| this.build_copilot_menu(cx)))
106                    }
107                    _ => Some(this.update(cx, |this, cx| this.build_copilot_start_menu(cx))),
108                })
109                .anchor(AnchorCorner::BottomRight)
110                .trigger(
111                    IconButton::new("copilot-icon", icon)
112                        .tooltip(|cx| Tooltip::text("GitHub Copilot", cx)),
113                ),
114        )
115    }
116}
117
118impl CopilotButton {
119    pub fn new(fs: Arc<dyn Fs>, cx: &mut ViewContext<Self>) -> Self {
120        Copilot::global(cx).map(|copilot| cx.observe(&copilot, |_, _, cx| cx.notify()).detach());
121
122        cx.observe_global::<SettingsStore>(move |_, cx| cx.notify())
123            .detach();
124
125        Self {
126            editor_subscription: None,
127            editor_enabled: None,
128            language: None,
129            file: None,
130            fs,
131        }
132    }
133
134    pub fn build_copilot_start_menu(&mut self, cx: &mut ViewContext<Self>) -> View<ContextMenu> {
135        let fs = self.fs.clone();
136        ContextMenu::build(cx, |menu, _| {
137            menu.entry("Sign In", None, initiate_sign_in).entry(
138                "Disable Copilot",
139                None,
140                move |cx| hide_copilot(fs.clone(), cx),
141            )
142        })
143    }
144
145    pub fn build_copilot_menu(&mut self, cx: &mut ViewContext<Self>) -> View<ContextMenu> {
146        let fs = self.fs.clone();
147
148        return ContextMenu::build(cx, move |mut menu, cx| {
149            if let Some(language) = self.language.clone() {
150                let fs = fs.clone();
151                let language_enabled =
152                    language_settings::language_settings(Some(&language), None, cx)
153                        .show_copilot_suggestions;
154
155                menu = menu.entry(
156                    format!(
157                        "{} Suggestions for {}",
158                        if language_enabled { "Hide" } else { "Show" },
159                        language.name()
160                    ),
161                    None,
162                    move |cx| toggle_copilot_for_language(language.clone(), fs.clone(), cx),
163                );
164            }
165
166            let settings = AllLanguageSettings::get_global(cx);
167
168            if let Some(file) = &self.file {
169                let path = file.path().clone();
170                let path_enabled = settings.copilot_enabled_for_path(&path);
171
172                menu = menu.entry(
173                    format!(
174                        "{} Suggestions for This Path",
175                        if path_enabled { "Hide" } else { "Show" }
176                    ),
177                    None,
178                    move |cx| {
179                        if let Some(workspace) = cx.window_handle().downcast::<Workspace>() {
180                            if let Ok(workspace) = workspace.root_view(cx) {
181                                let workspace = workspace.downgrade();
182                                cx.spawn(|cx| {
183                                    configure_disabled_globs(
184                                        workspace,
185                                        path_enabled.then_some(path.clone()),
186                                        cx,
187                                    )
188                                })
189                                .detach_and_log_err(cx);
190                            }
191                        }
192                    },
193                );
194            }
195
196            let globally_enabled = settings.copilot_enabled(None, None);
197            menu.entry(
198                if globally_enabled {
199                    "Hide Suggestions for All Files"
200                } else {
201                    "Show Suggestions for All Files"
202                },
203                None,
204                move |cx| toggle_copilot_globally(fs.clone(), cx),
205            )
206            .separator()
207            .link(
208                "Copilot Settings",
209                OpenBrowser {
210                    url: COPILOT_SETTINGS_URL.to_string(),
211                }
212                .boxed_clone(),
213            )
214            .action("Sign Out", SignOut.boxed_clone())
215        });
216    }
217
218    pub fn update_enabled(&mut self, editor: View<Editor>, cx: &mut ViewContext<Self>) {
219        let editor = editor.read(cx);
220        let snapshot = editor.buffer().read(cx).snapshot(cx);
221        let suggestion_anchor = editor.selections.newest_anchor().start;
222        let language = snapshot.language_at(suggestion_anchor);
223        let file = snapshot.file_at(suggestion_anchor).cloned();
224
225        self.editor_enabled = Some(
226            all_language_settings(self.file.as_ref(), cx)
227                .copilot_enabled(language, file.as_ref().map(|file| file.path().as_ref())),
228        );
229        self.language = language.cloned();
230        self.file = file;
231
232        cx.notify()
233    }
234}
235
236impl StatusItemView for CopilotButton {
237    fn set_active_pane_item(&mut self, item: Option<&dyn ItemHandle>, cx: &mut ViewContext<Self>) {
238        if let Some(editor) = item.map(|item| item.act_as::<Editor>(cx)).flatten() {
239            self.editor_subscription = Some((
240                cx.observe(&editor, Self::update_enabled),
241                editor.entity_id().as_u64() as usize,
242            ));
243            self.update_enabled(editor, cx);
244        } else {
245            self.language = None;
246            self.editor_subscription = None;
247            self.editor_enabled = None;
248        }
249        cx.notify();
250    }
251}
252
253async fn configure_disabled_globs(
254    workspace: WeakView<Workspace>,
255    path_to_disable: Option<Arc<Path>>,
256    mut cx: AsyncWindowContext,
257) -> Result<()> {
258    let settings_editor = workspace
259        .update(&mut cx, |_, cx| {
260            create_and_open_local_file(&paths::SETTINGS, cx, || {
261                settings::initial_user_settings_content().as_ref().into()
262            })
263        })?
264        .await?
265        .downcast::<Editor>()
266        .unwrap();
267
268    settings_editor.downgrade().update(&mut cx, |item, cx| {
269        let text = item.buffer().read(cx).snapshot(cx).text();
270
271        let settings = cx.global::<SettingsStore>();
272        let edits = settings.edits_for_update::<AllLanguageSettings>(&text, |file| {
273            let copilot = file.copilot.get_or_insert_with(Default::default);
274            let globs = copilot.disabled_globs.get_or_insert_with(|| {
275                settings
276                    .get::<AllLanguageSettings>(None)
277                    .copilot
278                    .disabled_globs
279                    .iter()
280                    .map(|glob| glob.glob().to_string())
281                    .collect()
282            });
283
284            if let Some(path_to_disable) = &path_to_disable {
285                globs.push(path_to_disable.to_string_lossy().into_owned());
286            } else {
287                globs.clear();
288            }
289        });
290
291        if !edits.is_empty() {
292            item.change_selections(Some(Autoscroll::newest()), cx, |selections| {
293                selections.select_ranges(edits.iter().map(|e| e.0.clone()));
294            });
295
296            // When *enabling* a path, don't actually perform an edit, just select the range.
297            if path_to_disable.is_some() {
298                item.edit(edits.iter().cloned(), cx);
299            }
300        }
301    })?;
302
303    anyhow::Ok(())
304}
305
306fn toggle_copilot_globally(fs: Arc<dyn Fs>, cx: &mut AppContext) {
307    let show_copilot_suggestions = all_language_settings(None, cx).copilot_enabled(None, None);
308    update_settings_file::<AllLanguageSettings>(fs, cx, move |file| {
309        file.defaults.show_copilot_suggestions = Some((!show_copilot_suggestions).into())
310    });
311}
312
313fn toggle_copilot_for_language(language: Arc<Language>, fs: Arc<dyn Fs>, cx: &mut AppContext) {
314    let show_copilot_suggestions =
315        all_language_settings(None, cx).copilot_enabled(Some(&language), None);
316    update_settings_file::<AllLanguageSettings>(fs, cx, move |file| {
317        file.languages
318            .entry(language.name())
319            .or_default()
320            .show_copilot_suggestions = Some(!show_copilot_suggestions);
321    });
322}
323
324fn hide_copilot(fs: Arc<dyn Fs>, cx: &mut AppContext) {
325    update_settings_file::<AllLanguageSettings>(fs, cx, move |file| {
326        file.features.get_or_insert(Default::default()).copilot = Some(false);
327    });
328}
329
330fn initiate_sign_in(cx: &mut WindowContext) {
331    let Some(copilot) = Copilot::global(cx) else {
332        return;
333    };
334    let status = copilot.read(cx).status();
335    let Some(workspace) = cx.window_handle().downcast::<Workspace>() else {
336        return;
337    };
338    match status {
339        Status::Starting { task } => {
340            let Some(workspace) = cx.window_handle().downcast::<Workspace>() else {
341                return;
342            };
343
344            let Ok(workspace) = workspace.update(cx, |workspace, cx| {
345                workspace.show_toast(
346                    Toast::new(COPILOT_STARTING_TOAST_ID, "Copilot is starting..."),
347                    cx,
348                );
349                workspace.weak_handle()
350            }) else {
351                return;
352            };
353
354            cx.spawn(|mut cx| async move {
355                task.await;
356                if let Some(copilot) = cx.update(|_, cx| Copilot::global(cx)).ok().flatten() {
357                    workspace
358                        .update(&mut cx, |workspace, cx| match copilot.read(cx).status() {
359                            Status::Authorized => workspace.show_toast(
360                                Toast::new(COPILOT_STARTING_TOAST_ID, "Copilot has started!"),
361                                cx,
362                            ),
363                            _ => {
364                                workspace.dismiss_toast(COPILOT_STARTING_TOAST_ID, cx);
365                                copilot
366                                    .update(cx, |copilot, cx| copilot.sign_in(cx))
367                                    .detach_and_log_err(cx);
368                            }
369                        })
370                        .log_err();
371                }
372            })
373            .detach();
374        }
375        _ => {
376            copilot.update(cx, |this, cx| this.sign_in(cx)).detach();
377            workspace
378                .update(cx, |this, cx| {
379                    this.toggle_modal(cx, |cx| CopilotCodeVerification::new(&copilot, cx));
380                })
381                .ok();
382        }
383    }
384}