1use anyhow::Result;
2use copilot::{Copilot, SignOut, Status};
3use editor::{scroll::autoscroll::Autoscroll, Editor};
4use fs::Fs;
5use gpui::{
6 div, Action, AnchorCorner, AppContext, AsyncWindowContext, Div, Entity, ParentElement, Render,
7 Subscription, View, ViewContext, WeakView, WindowContext,
8};
9use language::{
10 language_settings::{self, all_language_settings, AllLanguageSettings},
11 File, Language,
12};
13use settings::{update_settings_file, Settings, SettingsStore};
14use std::{path::Path, sync::Arc};
15use util::{paths, ResultExt};
16use workspace::{
17 create_and_open_local_file,
18 item::ItemHandle,
19 ui::{popover_menu, ButtonCommon, Clickable, ContextMenu, Icon, IconButton, IconSize, Tooltip},
20 StatusItemView, Toast, Workspace,
21};
22use zed_actions::OpenBrowser;
23
24const COPILOT_SETTINGS_URL: &str = "https://github.com/settings/copilot";
25const COPILOT_STARTING_TOAST_ID: usize = 1337;
26const COPILOT_ERROR_TOAST_ID: usize = 1338;
27
28pub struct CopilotButton {
29 editor_subscription: Option<(Subscription, usize)>,
30 editor_enabled: Option<bool>,
31 language: Option<Arc<Language>>,
32 file: Option<Arc<dyn File>>,
33 fs: Arc<dyn Fs>,
34}
35
36impl Render for CopilotButton {
37 type Element = Div;
38
39 fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
40 let all_language_settings = all_language_settings(None, cx);
41 if !all_language_settings.copilot.feature_enabled {
42 return div();
43 }
44
45 let Some(copilot) = Copilot::global(cx) else {
46 return div();
47 };
48 let status = copilot.read(cx).status();
49
50 let enabled = self
51 .editor_enabled
52 .unwrap_or_else(|| all_language_settings.copilot_enabled(None, None));
53
54 let icon = match status {
55 Status::Error(_) => Icon::CopilotError,
56 Status::Authorized => {
57 if enabled {
58 Icon::Copilot
59 } else {
60 Icon::CopilotDisabled
61 }
62 }
63 _ => Icon::CopilotInit,
64 };
65
66 if let Status::Error(e) = status {
67 return div().child(
68 IconButton::new("copilot-error", icon)
69 .icon_size(IconSize::Small)
70 .on_click(cx.listener(move |_, _, cx| {
71 if let Some(workspace) = cx.window_handle().downcast::<Workspace>() {
72 workspace
73 .update(cx, |workspace, cx| {
74 workspace.show_toast(
75 Toast::new(
76 COPILOT_ERROR_TOAST_ID,
77 format!("Copilot can't be started: {}", e),
78 )
79 .on_click(
80 "Reinstall Copilot",
81 |cx| {
82 if let Some(copilot) = Copilot::global(cx) {
83 copilot
84 .update(cx, |copilot, cx| {
85 copilot.reinstall(cx)
86 })
87 .detach();
88 }
89 },
90 ),
91 cx,
92 );
93 })
94 .ok();
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, _| {
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}