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", initiate_sign_in)
137                .entry("Disable Copilot", move |cx| hide_copilot(fs.clone(), cx))
138        })
139    }
140
141    pub fn build_copilot_menu(&mut self, cx: &mut ViewContext<Self>) -> View<ContextMenu> {
142        let fs = self.fs.clone();
143
144        return ContextMenu::build(cx, move |mut menu, cx| {
145            if let Some(language) = self.language.clone() {
146                let fs = fs.clone();
147                let language_enabled =
148                    language_settings::language_settings(Some(&language), None, cx)
149                        .show_copilot_suggestions;
150
151                menu = menu.entry(
152                    format!(
153                        "{} Suggestions for {}",
154                        if language_enabled { "Hide" } else { "Show" },
155                        language.name()
156                    ),
157                    move |cx| toggle_copilot_for_language(language.clone(), fs.clone(), cx),
158                );
159            }
160
161            let settings = AllLanguageSettings::get_global(cx);
162
163            if let Some(file) = &self.file {
164                let path = file.path().clone();
165                let path_enabled = settings.copilot_enabled_for_path(&path);
166
167                menu = menu.entry(
168                    format!(
169                        "{} Suggestions for This Path",
170                        if path_enabled { "Hide" } else { "Show" }
171                    ),
172                    move |cx| {
173                        if let Some(workspace) = cx.window_handle().downcast::<Workspace>() {
174                            if let Ok(workspace) = workspace.root_view(cx) {
175                                let workspace = workspace.downgrade();
176                                cx.spawn(|cx| {
177                                    configure_disabled_globs(
178                                        workspace,
179                                        path_enabled.then_some(path.clone()),
180                                        cx,
181                                    )
182                                })
183                                .detach_and_log_err(cx);
184                            }
185                        }
186                    },
187                );
188            }
189
190            let globally_enabled = settings.copilot_enabled(None, None);
191            menu.entry(
192                if globally_enabled {
193                    "Hide Suggestions for All Files"
194                } else {
195                    "Show Suggestions for All Files"
196                },
197                move |cx| toggle_copilot_globally(fs.clone(), cx),
198            )
199            .separator()
200            .link(
201                "Copilot Settings",
202                OpenBrowser {
203                    url: COPILOT_SETTINGS_URL.to_string(),
204                }
205                .boxed_clone(),
206            )
207            .action("Sign Out", SignOut.boxed_clone())
208        });
209    }
210
211    pub fn update_enabled(&mut self, editor: View<Editor>, cx: &mut ViewContext<Self>) {
212        let editor = editor.read(cx);
213        let snapshot = editor.buffer().read(cx).snapshot(cx);
214        let suggestion_anchor = editor.selections.newest_anchor().start;
215        let language = snapshot.language_at(suggestion_anchor);
216        let file = snapshot.file_at(suggestion_anchor).cloned();
217
218        self.editor_enabled = Some(
219            all_language_settings(self.file.as_ref(), cx)
220                .copilot_enabled(language, file.as_ref().map(|file| file.path().as_ref())),
221        );
222        self.language = language.cloned();
223        self.file = file;
224
225        cx.notify()
226    }
227}
228
229impl StatusItemView for CopilotButton {
230    fn set_active_pane_item(&mut self, item: Option<&dyn ItemHandle>, cx: &mut ViewContext<Self>) {
231        if let Some(editor) = item.map(|item| item.act_as::<Editor>(cx)).flatten() {
232            self.editor_subscription = Some((
233                cx.observe(&editor, Self::update_enabled),
234                editor.entity_id().as_u64() as usize,
235            ));
236            self.update_enabled(editor, cx);
237        } else {
238            self.language = None;
239            self.editor_subscription = None;
240            self.editor_enabled = None;
241        }
242        cx.notify();
243    }
244}
245
246async fn configure_disabled_globs(
247    workspace: WeakView<Workspace>,
248    path_to_disable: Option<Arc<Path>>,
249    mut cx: AsyncWindowContext,
250) -> Result<()> {
251    let settings_editor = workspace
252        .update(&mut cx, |_, cx| {
253            create_and_open_local_file(&paths::SETTINGS, cx, || {
254                settings::initial_user_settings_content().as_ref().into()
255            })
256        })?
257        .await?
258        .downcast::<Editor>()
259        .unwrap();
260
261    settings_editor.downgrade().update(&mut cx, |item, cx| {
262        let text = item.buffer().read(cx).snapshot(cx).text();
263
264        let settings = cx.global::<SettingsStore>();
265        let edits = settings.edits_for_update::<AllLanguageSettings>(&text, |file| {
266            let copilot = file.copilot.get_or_insert_with(Default::default);
267            let globs = copilot.disabled_globs.get_or_insert_with(|| {
268                settings
269                    .get::<AllLanguageSettings>(None)
270                    .copilot
271                    .disabled_globs
272                    .iter()
273                    .map(|glob| glob.glob().to_string())
274                    .collect()
275            });
276
277            if let Some(path_to_disable) = &path_to_disable {
278                globs.push(path_to_disable.to_string_lossy().into_owned());
279            } else {
280                globs.clear();
281            }
282        });
283
284        if !edits.is_empty() {
285            item.change_selections(Some(Autoscroll::newest()), cx, |selections| {
286                selections.select_ranges(edits.iter().map(|e| e.0.clone()));
287            });
288
289            // When *enabling* a path, don't actually perform an edit, just select the range.
290            if path_to_disable.is_some() {
291                item.edit(edits.iter().cloned(), cx);
292            }
293        }
294    })?;
295
296    anyhow::Ok(())
297}
298
299fn toggle_copilot_globally(fs: Arc<dyn Fs>, cx: &mut AppContext) {
300    let show_copilot_suggestions = all_language_settings(None, cx).copilot_enabled(None, None);
301    update_settings_file::<AllLanguageSettings>(fs, cx, move |file| {
302        file.defaults.show_copilot_suggestions = Some((!show_copilot_suggestions).into())
303    });
304}
305
306fn toggle_copilot_for_language(language: Arc<Language>, fs: Arc<dyn Fs>, cx: &mut AppContext) {
307    let show_copilot_suggestions =
308        all_language_settings(None, cx).copilot_enabled(Some(&language), None);
309    update_settings_file::<AllLanguageSettings>(fs, cx, move |file| {
310        file.languages
311            .entry(language.name())
312            .or_default()
313            .show_copilot_suggestions = Some(!show_copilot_suggestions);
314    });
315}
316
317fn hide_copilot(fs: Arc<dyn Fs>, cx: &mut AppContext) {
318    update_settings_file::<AllLanguageSettings>(fs, cx, move |file| {
319        file.features.get_or_insert(Default::default()).copilot = Some(false);
320    });
321}
322
323fn initiate_sign_in(cx: &mut WindowContext) {
324    let Some(copilot) = Copilot::global(cx) else {
325        return;
326    };
327    let status = copilot.read(cx).status();
328
329    match status {
330        Status::Starting { task } => {
331            let Some(workspace) = cx.window_handle().downcast::<Workspace>() else {
332                return;
333            };
334
335            let Ok(workspace) = workspace.update(cx, |workspace, cx| {
336                workspace.show_toast(
337                    Toast::new(COPILOT_STARTING_TOAST_ID, "Copilot is starting..."),
338                    cx,
339                );
340                workspace.weak_handle()
341            }) else {
342                return;
343            };
344
345            cx.spawn(|mut cx| async move {
346                task.await;
347                if let Some(copilot) = cx.update(|_, cx| Copilot::global(cx)).ok().flatten() {
348                    workspace
349                        .update(&mut cx, |workspace, cx| match copilot.read(cx).status() {
350                            Status::Authorized => workspace.show_toast(
351                                Toast::new(COPILOT_STARTING_TOAST_ID, "Copilot has started!"),
352                                cx,
353                            ),
354                            _ => {
355                                workspace.dismiss_toast(COPILOT_STARTING_TOAST_ID, cx);
356                                copilot
357                                    .update(cx, |copilot, cx| copilot.sign_in(cx))
358                                    .detach_and_log_err(cx);
359                            }
360                        })
361                        .log_err();
362                }
363            })
364            .detach();
365        }
366        _ => {
367            copilot
368                .update(cx, |copilot, cx| copilot.sign_in(cx))
369                .detach_and_log_err(cx);
370        }
371    }
372}