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