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 cx,
205 )
206 .action("Sign Out", SignOut.boxed_clone(), cx)
207 });
208 }
209
210 pub fn update_enabled(&mut self, editor: View<Editor>, cx: &mut ViewContext<Self>) {
211 let editor = editor.read(cx);
212 let snapshot = editor.buffer().read(cx).snapshot(cx);
213 let suggestion_anchor = editor.selections.newest_anchor().start;
214 let language = snapshot.language_at(suggestion_anchor);
215 let file = snapshot.file_at(suggestion_anchor).cloned();
216
217 self.editor_enabled = Some(
218 all_language_settings(self.file.as_ref(), cx)
219 .copilot_enabled(language, file.as_ref().map(|file| file.path().as_ref())),
220 );
221 self.language = language.cloned();
222 self.file = file;
223
224 cx.notify()
225 }
226}
227
228impl StatusItemView for CopilotButton {
229 fn set_active_pane_item(&mut self, item: Option<&dyn ItemHandle>, cx: &mut ViewContext<Self>) {
230 if let Some(editor) = item.map(|item| item.act_as::<Editor>(cx)).flatten() {
231 self.editor_subscription = Some((
232 cx.observe(&editor, Self::update_enabled),
233 editor.entity_id().as_u64() as usize,
234 ));
235 self.update_enabled(editor, cx);
236 } else {
237 self.language = None;
238 self.editor_subscription = None;
239 self.editor_enabled = None;
240 }
241 cx.notify();
242 }
243}
244
245async fn configure_disabled_globs(
246 workspace: WeakView<Workspace>,
247 path_to_disable: Option<Arc<Path>>,
248 mut cx: AsyncWindowContext,
249) -> Result<()> {
250 let settings_editor = workspace
251 .update(&mut cx, |_, cx| {
252 create_and_open_local_file(&paths::SETTINGS, cx, || {
253 settings::initial_user_settings_content().as_ref().into()
254 })
255 })?
256 .await?
257 .downcast::<Editor>()
258 .unwrap();
259
260 settings_editor.downgrade().update(&mut cx, |item, cx| {
261 let text = item.buffer().read(cx).snapshot(cx).text();
262
263 let settings = cx.global::<SettingsStore>();
264 let edits = settings.edits_for_update::<AllLanguageSettings>(&text, |file| {
265 let copilot = file.copilot.get_or_insert_with(Default::default);
266 let globs = copilot.disabled_globs.get_or_insert_with(|| {
267 settings
268 .get::<AllLanguageSettings>(None)
269 .copilot
270 .disabled_globs
271 .iter()
272 .map(|glob| glob.glob().to_string())
273 .collect()
274 });
275
276 if let Some(path_to_disable) = &path_to_disable {
277 globs.push(path_to_disable.to_string_lossy().into_owned());
278 } else {
279 globs.clear();
280 }
281 });
282
283 if !edits.is_empty() {
284 item.change_selections(Some(Autoscroll::newest()), cx, |selections| {
285 selections.select_ranges(edits.iter().map(|e| e.0.clone()));
286 });
287
288 // When *enabling* a path, don't actually perform an edit, just select the range.
289 if path_to_disable.is_some() {
290 item.edit(edits.iter().cloned(), cx);
291 }
292 }
293 })?;
294
295 anyhow::Ok(())
296}
297
298fn toggle_copilot_globally(fs: Arc<dyn Fs>, cx: &mut AppContext) {
299 let show_copilot_suggestions = all_language_settings(None, cx).copilot_enabled(None, None);
300 update_settings_file::<AllLanguageSettings>(fs, cx, move |file| {
301 file.defaults.show_copilot_suggestions = Some((!show_copilot_suggestions).into())
302 });
303}
304
305fn toggle_copilot_for_language(language: Arc<Language>, fs: Arc<dyn Fs>, cx: &mut AppContext) {
306 let show_copilot_suggestions =
307 all_language_settings(None, cx).copilot_enabled(Some(&language), None);
308 update_settings_file::<AllLanguageSettings>(fs, cx, move |file| {
309 file.languages
310 .entry(language.name())
311 .or_default()
312 .show_copilot_suggestions = Some(!show_copilot_suggestions);
313 });
314}
315
316fn hide_copilot(fs: Arc<dyn Fs>, cx: &mut AppContext) {
317 update_settings_file::<AllLanguageSettings>(fs, cx, move |file| {
318 file.features.get_or_insert(Default::default()).copilot = Some(false);
319 });
320}
321
322fn initiate_sign_in(cx: &mut WindowContext) {
323 let Some(copilot) = Copilot::global(cx) else {
324 return;
325 };
326 let status = copilot.read(cx).status();
327
328 match status {
329 Status::Starting { task } => {
330 let Some(workspace) = cx.window_handle().downcast::<Workspace>() else {
331 return;
332 };
333
334 let Ok(workspace) = workspace.update(cx, |workspace, cx| {
335 workspace.show_toast(
336 Toast::new(COPILOT_STARTING_TOAST_ID, "Copilot is starting..."),
337 cx,
338 );
339 workspace.weak_handle()
340 }) else {
341 return;
342 };
343
344 cx.spawn(|mut cx| async move {
345 task.await;
346 if let Some(copilot) = cx.update(|_, cx| Copilot::global(cx)).ok().flatten() {
347 workspace
348 .update(&mut cx, |workspace, cx| match copilot.read(cx).status() {
349 Status::Authorized => workspace.show_toast(
350 Toast::new(COPILOT_STARTING_TOAST_ID, "Copilot has started!"),
351 cx,
352 ),
353 _ => {
354 workspace.dismiss_toast(COPILOT_STARTING_TOAST_ID, cx);
355 copilot
356 .update(cx, |copilot, cx| copilot.sign_in(cx))
357 .detach_and_log_err(cx);
358 }
359 })
360 .log_err();
361 }
362 })
363 .detach();
364 }
365 _ => {
366 copilot
367 .update(cx, |copilot, cx| copilot.sign_in(cx))
368 .detach_and_log_err(cx);
369 }
370 }
371}