1use std::sync::Arc;
2
3use context_menu::{ContextMenu, ContextMenuItem};
4use editor::Editor;
5use gpui::{
6 elements::*, impl_internal_actions, CursorStyle, Element, ElementBox, Entity, MouseButton,
7 MouseState, MutableAppContext, RenderContext, Subscription, View, ViewContext, ViewHandle,
8};
9use settings::{settings_file::SettingsFile, Settings};
10use workspace::{
11 item::ItemHandle, notifications::simple_message_notification::OsOpen, DismissToast,
12 StatusItemView,
13};
14
15use copilot::{Copilot, Reinstall, SignIn, SignOut, Status};
16
17const COPILOT_SETTINGS_URL: &str = "https://github.com/settings/copilot";
18const COPILOT_STARTING_TOAST_ID: usize = 1337;
19const COPILOT_ERROR_TOAST_ID: usize = 1338;
20
21#[derive(Clone, PartialEq)]
22pub struct DeployCopilotMenu;
23
24#[derive(Clone, PartialEq)]
25pub struct ToggleCopilotForLanguage {
26 language: Arc<str>,
27}
28
29#[derive(Clone, PartialEq)]
30pub struct ToggleCopilotGlobally;
31
32// TODO: Make the other code path use `get_or_insert` logic for this modal
33#[derive(Clone, PartialEq)]
34pub struct DeployCopilotModal;
35
36impl_internal_actions!(
37 copilot,
38 [
39 DeployCopilotMenu,
40 DeployCopilotModal,
41 ToggleCopilotForLanguage,
42 ToggleCopilotGlobally,
43 ]
44);
45
46pub fn init(cx: &mut MutableAppContext) {
47 cx.add_action(CopilotButton::deploy_copilot_menu);
48 cx.add_action(
49 |_: &mut CopilotButton, action: &ToggleCopilotForLanguage, cx| {
50 let language = action.language.to_owned();
51
52 let current_langauge = cx.global::<Settings>().copilot_on(Some(&language));
53
54 SettingsFile::update(cx, move |file_contents| {
55 file_contents.languages.insert(
56 language.to_owned(),
57 settings::EditorSettings {
58 copilot: Some((!current_langauge).into()),
59 ..Default::default()
60 },
61 );
62 })
63 },
64 );
65
66 cx.add_action(|_: &mut CopilotButton, _: &ToggleCopilotGlobally, cx| {
67 let copilot_on = cx.global::<Settings>().copilot_on(None);
68
69 SettingsFile::update(cx, move |file_contents| {
70 file_contents.editor.copilot = Some((!copilot_on).into())
71 })
72 });
73}
74
75pub struct CopilotButton {
76 popup_menu: ViewHandle<ContextMenu>,
77 editor_subscription: Option<(Subscription, usize)>,
78 editor_enabled: Option<bool>,
79 language: Option<Arc<str>>,
80}
81
82impl Entity for CopilotButton {
83 type Event = ();
84}
85
86impl View for CopilotButton {
87 fn ui_name() -> &'static str {
88 "CopilotButton"
89 }
90
91 fn render(&mut self, cx: &mut RenderContext<'_, Self>) -> ElementBox {
92 let settings = cx.global::<Settings>();
93
94 if !settings.enable_copilot_integration {
95 return Empty::new().boxed();
96 }
97
98 let theme = settings.theme.clone();
99 let active = self.popup_menu.read(cx).visible();
100 let Some(copilot) = Copilot::global(cx) else {
101 return Empty::new().boxed();
102 };
103 let status = copilot.read(cx).status();
104
105 let enabled = self.editor_enabled.unwrap_or(settings.copilot_on(None));
106
107 let view_id = cx.view_id();
108
109 Stack::new()
110 .with_child(
111 MouseEventHandler::<Self>::new(0, cx, {
112 let theme = theme.clone();
113 let status = status.clone();
114 move |state, _cx| {
115 let style = theme
116 .workspace
117 .status_bar
118 .sidebar_buttons
119 .item
120 .style_for(state, active);
121
122 Flex::row()
123 .with_child(
124 Svg::new({
125 match status {
126 Status::Error(_) => "icons/copilot_error_16.svg",
127 Status::Authorized => {
128 if enabled {
129 "icons/copilot_16.svg"
130 } else {
131 "icons/copilot_disabled_16.svg"
132 }
133 }
134 _ => "icons/copilot_init_16.svg",
135 }
136 })
137 .with_color(style.icon_color)
138 .constrained()
139 .with_width(style.icon_size)
140 .aligned()
141 .named("copilot-icon"),
142 )
143 .constrained()
144 .with_height(style.icon_size)
145 .contained()
146 .with_style(style.container)
147 .boxed()
148 }
149 })
150 .with_cursor_style(CursorStyle::PointingHand)
151 .on_click(MouseButton::Left, {
152 let status = status.clone();
153 move |_, cx| match status {
154 Status::Authorized => cx.dispatch_action(DeployCopilotMenu),
155 Status::Starting { ref task } => {
156 cx.dispatch_action(workspace::Toast::new(
157 COPILOT_STARTING_TOAST_ID,
158 "Copilot is starting...",
159 ));
160 let window_id = cx.window_id();
161 let task = task.to_owned();
162 cx.spawn(|mut cx| async move {
163 task.await;
164 cx.update(|cx| {
165 if let Some(copilot) = Copilot::global(cx) {
166 let status = copilot.read(cx).status();
167 match status {
168 Status::Authorized => cx.dispatch_action_at(
169 window_id,
170 view_id,
171 workspace::Toast::new(
172 COPILOT_STARTING_TOAST_ID,
173 "Copilot has started!",
174 ),
175 ),
176 _ => {
177 cx.dispatch_action_at(
178 window_id,
179 view_id,
180 DismissToast::new(COPILOT_STARTING_TOAST_ID),
181 );
182 cx.dispatch_global_action(SignIn)
183 }
184 }
185 }
186 })
187 })
188 .detach();
189 }
190 Status::Error(ref e) => cx.dispatch_action(workspace::Toast::new_action(
191 COPILOT_ERROR_TOAST_ID,
192 format!("Copilot can't be started: {}", e),
193 "Reinstall Copilot",
194 Reinstall,
195 )),
196 _ => cx.dispatch_action(SignIn),
197 }
198 })
199 .with_tooltip::<Self, _>(
200 0,
201 "GitHub Copilot".into(),
202 None,
203 theme.tooltip.clone(),
204 cx,
205 )
206 .boxed(),
207 )
208 .with_child(
209 ChildView::new(&self.popup_menu, cx)
210 .aligned()
211 .top()
212 .right()
213 .boxed(),
214 )
215 .boxed()
216 }
217}
218
219impl CopilotButton {
220 pub fn new(cx: &mut ViewContext<Self>) -> Self {
221 let menu = cx.add_view(|cx| {
222 let mut menu = ContextMenu::new(cx);
223 menu.set_position_mode(OverlayPositionMode::Local);
224 menu
225 });
226
227 cx.observe(&menu, |_, _, cx| cx.notify()).detach();
228
229 Copilot::global(cx).map(|copilot| cx.observe(&copilot, |_, _, cx| cx.notify()).detach());
230
231 let this_handle = cx.handle().downgrade();
232 cx.observe_global::<Settings, _>(move |cx| {
233 if let Some(handle) = this_handle.upgrade(cx) {
234 handle.update(cx, |_, cx| cx.notify())
235 }
236 })
237 .detach();
238
239 Self {
240 popup_menu: menu,
241 editor_subscription: None,
242 editor_enabled: None,
243 language: None,
244 }
245 }
246
247 pub fn deploy_copilot_menu(&mut self, _: &DeployCopilotMenu, cx: &mut ViewContext<Self>) {
248 let settings = cx.global::<Settings>();
249
250 let mut menu_options = Vec::with_capacity(6);
251
252 if let Some(language) = &self.language {
253 let language_enabled = settings.copilot_on(Some(language.as_ref()));
254
255 menu_options.push(ContextMenuItem::item(
256 format!(
257 "{} Copilot for {}",
258 if language_enabled {
259 "Disable"
260 } else {
261 "Enable"
262 },
263 language
264 ),
265 ToggleCopilotForLanguage {
266 language: language.to_owned(),
267 },
268 ));
269 }
270
271 let globally_enabled = cx.global::<Settings>().copilot_on(None);
272 menu_options.push(ContextMenuItem::item(
273 if globally_enabled {
274 "Disable Copilot Globally"
275 } else {
276 "Enable Copilot Globally"
277 },
278 ToggleCopilotGlobally,
279 ));
280
281 menu_options.push(ContextMenuItem::Separator);
282
283 let icon_style = settings.theme.copilot.out_link_icon.clone();
284 menu_options.push(ContextMenuItem::element_item(
285 Box::new(
286 move |state: &mut MouseState, style: &theme::ContextMenuItem| {
287 Flex::row()
288 .with_children([
289 Label::new("Copilot Settings", style.label.clone()).boxed(),
290 theme::ui::icon(icon_style.style_for(state, false)).boxed(),
291 ])
292 .align_children_center()
293 .boxed()
294 },
295 ),
296 OsOpen::new(COPILOT_SETTINGS_URL),
297 ));
298
299 menu_options.push(ContextMenuItem::item("Sign Out", SignOut));
300
301 self.popup_menu.update(cx, |menu, cx| {
302 menu.show(
303 Default::default(),
304 AnchorCorner::BottomRight,
305 menu_options,
306 cx,
307 );
308 });
309 }
310
311 pub fn update_enabled(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
312 let editor = editor.read(cx);
313
314 let snapshot = editor.buffer().read(cx).snapshot(cx);
315 let settings = cx.global::<Settings>();
316 let suggestion_anchor = editor.selections.newest_anchor().start;
317
318 let language_name = snapshot
319 .language_at(suggestion_anchor)
320 .map(|language| language.name());
321
322 self.language = language_name.clone();
323
324 self.editor_enabled = Some(settings.copilot_on(language_name.as_deref()));
325
326 cx.notify()
327 }
328}
329
330impl StatusItemView for CopilotButton {
331 fn set_active_pane_item(&mut self, item: Option<&dyn ItemHandle>, cx: &mut ViewContext<Self>) {
332 if let Some(editor) = item.map(|item| item.act_as::<Editor>(cx)).flatten() {
333 self.editor_subscription =
334 Some((cx.observe(&editor, Self::update_enabled), editor.id()));
335 self.update_enabled(editor, cx);
336 } else {
337 self.language = None;
338 self.editor_subscription = None;
339 self.editor_enabled = None;
340 }
341 cx.notify();
342 }
343}