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