1use anyhow::Result;
2use context_menu::{ContextMenu, ContextMenuItem};
3use copilot::{Copilot, SignOut, Status};
4use editor::{scroll::autoscroll::Autoscroll, Editor};
5use gpui::{
6 elements::*,
7 platform::{CursorStyle, MouseButton},
8 AnyElement, AppContext, AsyncAppContext, Element, Entity, MouseState, Subscription, View,
9 ViewContext, ViewHandle, WeakViewHandle, WindowContext,
10};
11use settings::{settings_file::SettingsFile, Settings};
12use std::{path::Path, sync::Arc};
13use util::{paths, ResultExt};
14use workspace::{
15 create_and_open_local_file, item::ItemHandle,
16 notifications::simple_message_notification::OsOpen, StatusItemView, Toast, Workspace,
17};
18
19const COPILOT_SETTINGS_URL: &str = "https://github.com/settings/copilot";
20const COPILOT_STARTING_TOAST_ID: usize = 1337;
21const COPILOT_ERROR_TOAST_ID: usize = 1338;
22
23pub struct CopilotButton {
24 popup_menu: ViewHandle<ContextMenu>,
25 editor_subscription: Option<(Subscription, usize)>,
26 editor_enabled: Option<bool>,
27 language: Option<Arc<str>>,
28 path: Option<Arc<Path>>,
29}
30
31impl Entity for CopilotButton {
32 type Event = ();
33}
34
35impl View for CopilotButton {
36 fn ui_name() -> &'static str {
37 "CopilotButton"
38 }
39
40 fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
41 let settings = cx.global::<Settings>();
42
43 if !settings.features.copilot {
44 return Empty::new().into_any();
45 }
46
47 let theme = settings.theme.clone();
48 let active = self.popup_menu.read(cx).visible();
49 let Some(copilot) = Copilot::global(cx) else {
50 return Empty::new().into_any();
51 };
52 let status = copilot.read(cx).status();
53
54 let enabled = self
55 .editor_enabled
56 .unwrap_or(settings.show_copilot_suggestions(None, None));
57
58 Stack::new()
59 .with_child(
60 MouseEventHandler::<Self, _>::new(0, cx, {
61 let theme = theme.clone();
62 let status = status.clone();
63 move |state, _cx| {
64 let style = theme
65 .workspace
66 .status_bar
67 .sidebar_buttons
68 .item
69 .style_for(state, active);
70
71 Flex::row()
72 .with_child(
73 Svg::new({
74 match status {
75 Status::Error(_) => "icons/copilot_error_16.svg",
76 Status::Authorized => {
77 if enabled {
78 "icons/copilot_16.svg"
79 } else {
80 "icons/copilot_disabled_16.svg"
81 }
82 }
83 _ => "icons/copilot_init_16.svg",
84 }
85 })
86 .with_color(style.icon_color)
87 .constrained()
88 .with_width(style.icon_size)
89 .aligned()
90 .into_any_named("copilot-icon"),
91 )
92 .constrained()
93 .with_height(style.icon_size)
94 .contained()
95 .with_style(style.container)
96 }
97 })
98 .with_cursor_style(CursorStyle::PointingHand)
99 .on_click(MouseButton::Left, {
100 let status = status.clone();
101 move |_, this, cx| match status {
102 Status::Authorized => this.deploy_copilot_menu(cx),
103 Status::Error(ref e) => {
104 if let Some(workspace) = cx.root_view().clone().downcast::<Workspace>()
105 {
106 workspace.update(cx, |workspace, cx| {
107 workspace.show_toast(
108 Toast::new(
109 COPILOT_ERROR_TOAST_ID,
110 format!("Copilot can't be started: {}", e),
111 )
112 .on_click(
113 "Reinstall Copilot",
114 |cx| {
115 if let Some(copilot) = Copilot::global(cx) {
116 copilot
117 .update(cx, |copilot, cx| {
118 copilot.reinstall(cx)
119 })
120 .detach();
121 }
122 },
123 ),
124 cx,
125 );
126 });
127 }
128 }
129 _ => this.deploy_copilot_start_menu(cx),
130 }
131 })
132 .with_tooltip::<Self>(
133 0,
134 "GitHub Copilot".into(),
135 None,
136 theme.tooltip.clone(),
137 cx,
138 ),
139 )
140 .with_child(ChildView::new(&self.popup_menu, cx).aligned().top().right())
141 .into_any()
142 }
143}
144
145impl CopilotButton {
146 pub fn new(cx: &mut ViewContext<Self>) -> Self {
147 let button_view_id = cx.view_id();
148 let menu = cx.add_view(|cx| {
149 let mut menu = ContextMenu::new(button_view_id, cx);
150 menu.set_position_mode(OverlayPositionMode::Local);
151 menu
152 });
153
154 cx.observe(&menu, |_, _, cx| cx.notify()).detach();
155
156 Copilot::global(cx).map(|copilot| cx.observe(&copilot, |_, _, cx| cx.notify()).detach());
157
158 cx.observe_global::<Settings, _>(move |_, cx| cx.notify())
159 .detach();
160
161 Self {
162 popup_menu: menu,
163 editor_subscription: None,
164 editor_enabled: None,
165 language: None,
166 path: None,
167 }
168 }
169
170 pub fn deploy_copilot_start_menu(&mut self, cx: &mut ViewContext<Self>) {
171 let mut menu_options = Vec::with_capacity(2);
172
173 menu_options.push(ContextMenuItem::handler("Sign In", |cx| {
174 initiate_sign_in(cx)
175 }));
176 menu_options.push(ContextMenuItem::handler("Disable Copilot", |cx| {
177 hide_copilot(cx)
178 }));
179
180 self.popup_menu.update(cx, |menu, cx| {
181 menu.show(
182 Default::default(),
183 AnchorCorner::BottomRight,
184 menu_options,
185 cx,
186 );
187 });
188 }
189
190 pub fn deploy_copilot_menu(&mut self, cx: &mut ViewContext<Self>) {
191 let settings = cx.global::<Settings>();
192
193 let mut menu_options = Vec::with_capacity(8);
194
195 if let Some(language) = self.language.clone() {
196 let language_enabled = settings.copilot_enabled_for_language(Some(language.as_ref()));
197 menu_options.push(ContextMenuItem::handler(
198 format!(
199 "{} Suggestions for {}",
200 if language_enabled { "Hide" } else { "Show" },
201 language
202 ),
203 move |cx| toggle_copilot_for_language(language.clone(), cx),
204 ));
205 }
206
207 if let Some(path) = self.path.as_ref() {
208 let path_enabled = settings.copilot_enabled_for_path(path);
209 let path = path.clone();
210 menu_options.push(ContextMenuItem::handler(
211 format!(
212 "{} Suggestions for This Path",
213 if path_enabled { "Hide" } else { "Show" }
214 ),
215 move |cx| {
216 if let Some(workspace) = cx.root_view().clone().downcast::<Workspace>() {
217 let workspace = workspace.downgrade();
218 cx.spawn(|_, cx| {
219 configure_disabled_globs(
220 workspace,
221 path_enabled.then_some(path.clone()),
222 cx,
223 )
224 })
225 .detach_and_log_err(cx);
226 }
227 },
228 ));
229 }
230
231 let globally_enabled = cx.global::<Settings>().features.copilot;
232 menu_options.push(ContextMenuItem::handler(
233 if globally_enabled {
234 "Hide Suggestions for All Files"
235 } else {
236 "Show Suggestions for All Files"
237 },
238 |cx| toggle_copilot_globally(cx),
239 ));
240
241 menu_options.push(ContextMenuItem::Separator);
242
243 let icon_style = settings.theme.copilot.out_link_icon.clone();
244 menu_options.push(ContextMenuItem::action(
245 move |state: &mut MouseState, style: &theme::ContextMenuItem| {
246 Flex::row()
247 .with_child(Label::new("Copilot Settings", style.label.clone()))
248 .with_child(theme::ui::icon(icon_style.style_for(state, false)))
249 .align_children_center()
250 .into_any()
251 },
252 OsOpen::new(COPILOT_SETTINGS_URL),
253 ));
254
255 menu_options.push(ContextMenuItem::action("Sign Out", SignOut));
256
257 self.popup_menu.update(cx, |menu, cx| {
258 menu.show(
259 Default::default(),
260 AnchorCorner::BottomRight,
261 menu_options,
262 cx,
263 );
264 });
265 }
266
267 pub fn update_enabled(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
268 let editor = editor.read(cx);
269
270 let snapshot = editor.buffer().read(cx).snapshot(cx);
271 let settings = cx.global::<Settings>();
272 let suggestion_anchor = editor.selections.newest_anchor().start;
273
274 let language_name = snapshot
275 .language_at(suggestion_anchor)
276 .map(|language| language.name());
277 let path = snapshot
278 .file_at(suggestion_anchor)
279 .map(|file| file.path().clone());
280
281 self.editor_enabled =
282 Some(settings.show_copilot_suggestions(language_name.as_deref(), path.as_deref()));
283 self.language = language_name;
284 self.path = path;
285
286 cx.notify()
287 }
288}
289
290impl StatusItemView for CopilotButton {
291 fn set_active_pane_item(&mut self, item: Option<&dyn ItemHandle>, cx: &mut ViewContext<Self>) {
292 if let Some(editor) = item.map(|item| item.act_as::<Editor>(cx)).flatten() {
293 self.editor_subscription =
294 Some((cx.observe(&editor, Self::update_enabled), editor.id()));
295 self.update_enabled(editor, cx);
296 } else {
297 self.language = None;
298 self.editor_subscription = None;
299 self.editor_enabled = None;
300 }
301 cx.notify();
302 }
303}
304
305async fn configure_disabled_globs(
306 workspace: WeakViewHandle<Workspace>,
307 path_to_disable: Option<Arc<Path>>,
308 mut cx: AsyncAppContext,
309) -> Result<()> {
310 let settings_editor = workspace
311 .update(&mut cx, |_, cx| {
312 create_and_open_local_file(&paths::SETTINGS, cx, || {
313 Settings::initial_user_settings_content(&assets::Assets)
314 .as_ref()
315 .into()
316 })
317 })?
318 .await?
319 .downcast::<Editor>()
320 .unwrap();
321
322 settings_editor.downgrade().update(&mut cx, |item, cx| {
323 let text = item.buffer().read(cx).snapshot(cx).text();
324
325 let edits = SettingsFile::update_unsaved(&text, cx, |file| {
326 let copilot = file.copilot.get_or_insert_with(Default::default);
327 let globs = copilot.disabled_globs.get_or_insert_with(|| {
328 cx.global::<Settings>()
329 .copilot
330 .disabled_globs
331 .clone()
332 .iter()
333 .map(|glob| glob.as_str().to_string())
334 .collect::<Vec<_>>()
335 });
336
337 if let Some(path_to_disable) = &path_to_disable {
338 globs.push(path_to_disable.to_string_lossy().into_owned());
339 } else {
340 globs.clear();
341 }
342 });
343
344 if !edits.is_empty() {
345 item.change_selections(Some(Autoscroll::newest()), cx, |selections| {
346 selections.select_ranges(edits.iter().map(|e| e.0.clone()));
347 });
348
349 // When *enabling* a path, don't actually perform an edit, just select the range.
350 if path_to_disable.is_some() {
351 item.edit(edits.iter().cloned(), cx);
352 }
353 }
354 })?;
355
356 anyhow::Ok(())
357}
358
359fn toggle_copilot_globally(cx: &mut AppContext) {
360 let show_copilot_suggestions = cx.global::<Settings>().show_copilot_suggestions(None, None);
361 SettingsFile::update(cx, move |file_contents| {
362 file_contents.editor.show_copilot_suggestions = Some((!show_copilot_suggestions).into())
363 });
364}
365
366fn toggle_copilot_for_language(language: Arc<str>, cx: &mut AppContext) {
367 let show_copilot_suggestions = cx
368 .global::<Settings>()
369 .show_copilot_suggestions(Some(&language), None);
370
371 SettingsFile::update(cx, move |file_contents| {
372 file_contents.languages.insert(
373 language,
374 settings::EditorSettings {
375 show_copilot_suggestions: Some((!show_copilot_suggestions).into()),
376 ..Default::default()
377 },
378 );
379 });
380}
381
382fn hide_copilot(cx: &mut AppContext) {
383 SettingsFile::update(cx, move |file_contents| {
384 file_contents.features.copilot = Some(false)
385 });
386}
387
388fn initiate_sign_in(cx: &mut WindowContext) {
389 let Some(copilot) = Copilot::global(cx) else {
390 return;
391 };
392 let status = copilot.read(cx).status();
393
394 match status {
395 Status::Starting { task } => {
396 let Some(workspace) = cx.root_view().clone().downcast::<Workspace>() else {
397 return;
398 };
399
400 workspace.update(cx, |workspace, cx| {
401 workspace.show_toast(
402 Toast::new(COPILOT_STARTING_TOAST_ID, "Copilot is starting..."),
403 cx,
404 )
405 });
406 let workspace = workspace.downgrade();
407 cx.spawn(|mut cx| async move {
408 task.await;
409 if let Some(copilot) = cx.read(Copilot::global) {
410 workspace
411 .update(&mut cx, |workspace, cx| match copilot.read(cx).status() {
412 Status::Authorized => workspace.show_toast(
413 Toast::new(COPILOT_STARTING_TOAST_ID, "Copilot has started!"),
414 cx,
415 ),
416 _ => {
417 workspace.dismiss_toast(COPILOT_STARTING_TOAST_ID, cx);
418 copilot
419 .update(cx, |copilot, cx| copilot.sign_in(cx))
420 .detach_and_log_err(cx);
421 }
422 })
423 .log_err();
424 }
425 })
426 .detach();
427 }
428 _ => {
429 copilot
430 .update(cx, |copilot, cx| copilot.sign_in(cx))
431 .detach_and_log_err(cx);
432 }
433 }
434}