1use crate::sign_in::CopilotCodeVerification;
2use anyhow::Result;
3use copilot::{Copilot, SignOut, Status};
4use editor::{scroll::Autoscroll, Editor};
5use fs::Fs;
6use gpui::{
7 div, Action, AnchorCorner, AppContext, AsyncWindowContext, Entity, IntoElement, ParentElement,
8 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::notifications::NotificationId;
18use workspace::{
19 create_and_open_local_file,
20 item::ItemHandle,
21 ui::{
22 popover_menu, ButtonCommon, Clickable, ContextMenu, IconButton, IconName, IconSize, Tooltip,
23 },
24 StatusItemView, Toast, Workspace,
25};
26use zed_actions::OpenBrowser;
27
28const COPILOT_SETTINGS_URL: &str = "https://github.com/settings/copilot";
29
30struct CopilotStartingToast;
31
32struct CopilotErrorToast;
33
34pub struct CopilotButton {
35 editor_subscription: Option<(Subscription, usize)>,
36 editor_enabled: Option<bool>,
37 language: Option<Arc<Language>>,
38 file: Option<Arc<dyn File>>,
39 fs: Arc<dyn Fs>,
40}
41
42impl Render for CopilotButton {
43 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
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(_) => IconName::CopilotError,
60 Status::Authorized => {
61 if enabled {
62 IconName::Copilot
63 } else {
64 IconName::CopilotDisabled
65 }
66 }
67 _ => IconName::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 |_, _, cx| {
75 if let Some(workspace) = cx.window_handle().downcast::<Workspace>() {
76 workspace
77 .update(cx, |workspace, cx| {
78 workspace.show_toast(
79 Toast::new(
80 NotificationId::unique::<CopilotErrorToast>(),
81 format!("Copilot can't be started: {}", e),
82 )
83 .on_click(
84 "Reinstall Copilot",
85 |cx| {
86 if let Some(copilot) = Copilot::global(cx) {
87 copilot
88 .update(cx, |copilot, cx| {
89 copilot.reinstall(cx)
90 })
91 .detach();
92 }
93 },
94 ),
95 cx,
96 );
97 })
98 .ok();
99 }
100 }))
101 .tooltip(|cx| Tooltip::text("GitHub Copilot", cx)),
102 );
103 }
104 let this = cx.view().clone();
105
106 div().child(
107 popover_menu("copilot")
108 .menu(move |cx| match status {
109 Status::Authorized => {
110 Some(this.update(cx, |this, cx| this.build_copilot_menu(cx)))
111 }
112 _ => Some(this.update(cx, |this, cx| this.build_copilot_start_menu(cx))),
113 })
114 .anchor(AnchorCorner::BottomRight)
115 .trigger(
116 IconButton::new("copilot-icon", icon)
117 .tooltip(|cx| Tooltip::text("GitHub Copilot", cx)),
118 ),
119 )
120 }
121}
122
123impl CopilotButton {
124 pub fn new(fs: Arc<dyn Fs>, cx: &mut ViewContext<Self>) -> Self {
125 if let Some(copilot) = Copilot::global(cx) {
126 cx.observe(&copilot, |_, _, cx| cx.notify()).detach()
127 }
128
129 cx.observe_global::<SettingsStore>(move |_, cx| cx.notify())
130 .detach();
131
132 Self {
133 editor_subscription: None,
134 editor_enabled: None,
135 language: None,
136 file: None,
137 fs,
138 }
139 }
140
141 pub fn build_copilot_start_menu(&mut self, cx: &mut ViewContext<Self>) -> View<ContextMenu> {
142 let fs = self.fs.clone();
143 ContextMenu::build(cx, |menu, _| {
144 menu.entry("Sign In", None, initiate_sign_in).entry(
145 "Disable Copilot",
146 None,
147 move |cx| hide_copilot(fs.clone(), cx),
148 )
149 })
150 }
151
152 pub fn build_copilot_menu(&mut self, cx: &mut ViewContext<Self>) -> View<ContextMenu> {
153 let fs = self.fs.clone();
154
155 ContextMenu::build(cx, move |mut menu, cx| {
156 if let Some(language) = self.language.clone() {
157 let fs = fs.clone();
158 let language_enabled =
159 language_settings::language_settings(Some(&language), None, cx)
160 .show_copilot_suggestions;
161
162 menu = menu.entry(
163 format!(
164 "{} Suggestions for {}",
165 if language_enabled { "Hide" } else { "Show" },
166 language.name()
167 ),
168 None,
169 move |cx| toggle_copilot_for_language(language.clone(), fs.clone(), cx),
170 );
171 }
172
173 let settings = AllLanguageSettings::get_global(cx);
174
175 if let Some(file) = &self.file {
176 let path = file.path().clone();
177 let path_enabled = settings.copilot_enabled_for_path(&path);
178
179 menu = menu.entry(
180 format!(
181 "{} Suggestions for This Path",
182 if path_enabled { "Hide" } else { "Show" }
183 ),
184 None,
185 move |cx| {
186 if let Some(workspace) = cx.window_handle().downcast::<Workspace>() {
187 if let Ok(workspace) = workspace.root_view(cx) {
188 let workspace = workspace.downgrade();
189 cx.spawn(|cx| {
190 configure_disabled_globs(
191 workspace,
192 path_enabled.then_some(path.clone()),
193 cx,
194 )
195 })
196 .detach_and_log_err(cx);
197 }
198 }
199 },
200 );
201 }
202
203 let globally_enabled = settings.copilot_enabled(None, None);
204 menu.entry(
205 if globally_enabled {
206 "Hide Suggestions for All Files"
207 } else {
208 "Show Suggestions for All Files"
209 },
210 None,
211 move |cx| toggle_copilot_globally(fs.clone(), cx),
212 )
213 .separator()
214 .link(
215 "Copilot Settings",
216 OpenBrowser {
217 url: COPILOT_SETTINGS_URL.to_string(),
218 }
219 .boxed_clone(),
220 )
221 .action("Sign Out", SignOut.boxed_clone())
222 })
223 }
224
225 pub fn update_enabled(&mut self, editor: View<Editor>, cx: &mut ViewContext<Self>) {
226 let editor = editor.read(cx);
227 let snapshot = editor.buffer().read(cx).snapshot(cx);
228 let suggestion_anchor = editor.selections.newest_anchor().start;
229 let language = snapshot.language_at(suggestion_anchor);
230 let file = snapshot.file_at(suggestion_anchor).cloned();
231 self.editor_enabled = {
232 let file = file.as_ref();
233 Some(
234 file.map(|file| !file.is_private()).unwrap_or(true)
235 && all_language_settings(file, cx)
236 .copilot_enabled(language, file.map(|file| file.path().as_ref())),
237 )
238 };
239 self.language = language.cloned();
240 self.file = file;
241
242 cx.notify()
243 }
244}
245
246impl StatusItemView for CopilotButton {
247 fn set_active_pane_item(&mut self, item: Option<&dyn ItemHandle>, cx: &mut ViewContext<Self>) {
248 if let Some(editor) = item.and_then(|item| item.act_as::<Editor>(cx)) {
249 self.editor_subscription = Some((
250 cx.observe(&editor, Self::update_enabled),
251 editor.entity_id().as_u64() as usize,
252 ));
253 self.update_enabled(editor, cx);
254 } else {
255 self.language = None;
256 self.editor_subscription = None;
257 self.editor_enabled = None;
258 }
259 cx.notify();
260 }
261}
262
263async fn configure_disabled_globs(
264 workspace: WeakView<Workspace>,
265 path_to_disable: Option<Arc<Path>>,
266 mut cx: AsyncWindowContext,
267) -> Result<()> {
268 let settings_editor = workspace
269 .update(&mut cx, |_, cx| {
270 create_and_open_local_file(&paths::SETTINGS, cx, || {
271 settings::initial_user_settings_content().as_ref().into()
272 })
273 })?
274 .await?
275 .downcast::<Editor>()
276 .unwrap();
277
278 settings_editor.downgrade().update(&mut cx, |item, cx| {
279 let text = item.buffer().read(cx).snapshot(cx).text();
280
281 let settings = cx.global::<SettingsStore>();
282 let edits = settings.edits_for_update::<AllLanguageSettings>(&text, |file| {
283 let copilot = file.copilot.get_or_insert_with(Default::default);
284 let globs = copilot.disabled_globs.get_or_insert_with(|| {
285 settings
286 .get::<AllLanguageSettings>(None)
287 .copilot
288 .disabled_globs
289 .iter()
290 .map(|glob| glob.glob().to_string())
291 .collect()
292 });
293
294 if let Some(path_to_disable) = &path_to_disable {
295 globs.push(path_to_disable.to_string_lossy().into_owned());
296 } else {
297 globs.clear();
298 }
299 });
300
301 if !edits.is_empty() {
302 item.change_selections(Some(Autoscroll::newest()), cx, |selections| {
303 selections.select_ranges(edits.iter().map(|e| e.0.clone()));
304 });
305
306 // When *enabling* a path, don't actually perform an edit, just select the range.
307 if path_to_disable.is_some() {
308 item.edit(edits.iter().cloned(), cx);
309 }
310 }
311 })?;
312
313 anyhow::Ok(())
314}
315
316fn toggle_copilot_globally(fs: Arc<dyn Fs>, cx: &mut AppContext) {
317 let show_copilot_suggestions = all_language_settings(None, cx).copilot_enabled(None, None);
318 update_settings_file::<AllLanguageSettings>(fs, cx, move |file| {
319 file.defaults.show_copilot_suggestions = Some(!show_copilot_suggestions)
320 });
321}
322
323fn toggle_copilot_for_language(language: Arc<Language>, fs: Arc<dyn Fs>, cx: &mut AppContext) {
324 let show_copilot_suggestions =
325 all_language_settings(None, cx).copilot_enabled(Some(&language), None);
326 update_settings_file::<AllLanguageSettings>(fs, cx, move |file| {
327 file.languages
328 .entry(language.name())
329 .or_default()
330 .show_copilot_suggestions = Some(!show_copilot_suggestions);
331 });
332}
333
334fn hide_copilot(fs: Arc<dyn Fs>, cx: &mut AppContext) {
335 update_settings_file::<AllLanguageSettings>(fs, cx, move |file| {
336 file.features.get_or_insert(Default::default()).copilot = Some(false);
337 });
338}
339
340pub fn initiate_sign_in(cx: &mut WindowContext) {
341 let Some(copilot) = Copilot::global(cx) else {
342 return;
343 };
344 let status = copilot.read(cx).status();
345 let Some(workspace) = cx.window_handle().downcast::<Workspace>() else {
346 return;
347 };
348 match status {
349 Status::Starting { task } => {
350 let Some(workspace) = cx.window_handle().downcast::<Workspace>() else {
351 return;
352 };
353
354 let Ok(workspace) = workspace.update(cx, |workspace, cx| {
355 workspace.show_toast(
356 Toast::new(
357 NotificationId::unique::<CopilotStartingToast>(),
358 "Copilot is starting...",
359 ),
360 cx,
361 );
362 workspace.weak_handle()
363 }) else {
364 return;
365 };
366
367 cx.spawn(|mut cx| async move {
368 task.await;
369 if let Some(copilot) = cx.update(|cx| Copilot::global(cx)).ok().flatten() {
370 workspace
371 .update(&mut cx, |workspace, cx| match copilot.read(cx).status() {
372 Status::Authorized => workspace.show_toast(
373 Toast::new(
374 NotificationId::unique::<CopilotStartingToast>(),
375 "Copilot has started!",
376 ),
377 cx,
378 ),
379 _ => {
380 workspace.dismiss_toast(
381 &NotificationId::unique::<CopilotStartingToast>(),
382 cx,
383 );
384 copilot
385 .update(cx, |copilot, cx| copilot.sign_in(cx))
386 .detach_and_log_err(cx);
387 }
388 })
389 .log_err();
390 }
391 })
392 .detach();
393 }
394 _ => {
395 copilot.update(cx, |this, cx| this.sign_in(cx)).detach();
396 workspace
397 .update(cx, |this, cx| {
398 this.toggle_modal(cx, |cx| CopilotCodeVerification::new(&copilot, cx));
399 })
400 .ok();
401 }
402 }
403}