copilot_button.rs

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