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