copilot_button.rs

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