copilot_button.rs

  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((_, view_id)) = self.editor_subscription.as_ref() {
253            let locally_enabled = self.editor_enabled.unwrap_or(settings.copilot_on(None));
254            menu_options.push(ContextMenuItem::item_for_view(
255                if locally_enabled {
256                    "Pause Copilot for this file"
257                } else {
258                    "Resume Copilot for this file"
259                },
260                *view_id,
261                copilot::Toggle,
262            ));
263        }
264
265        if let Some(language) = &self.language {
266            let language_enabled = settings.copilot_on(Some(language.as_ref()));
267
268            menu_options.push(ContextMenuItem::item(
269                format!(
270                    "{} Copilot for {}",
271                    if language_enabled {
272                        "Disable"
273                    } else {
274                        "Enable"
275                    },
276                    language
277                ),
278                ToggleCopilotForLanguage {
279                    language: language.to_owned(),
280                },
281            ));
282        }
283
284        let globally_enabled = cx.global::<Settings>().copilot_on(None);
285        menu_options.push(ContextMenuItem::item(
286            if globally_enabled {
287                "Disable Copilot Globally"
288            } else {
289                "Enable Copilot Locally"
290            },
291            ToggleCopilotGlobally,
292        ));
293
294        menu_options.push(ContextMenuItem::Separator);
295
296        let icon_style = settings.theme.copilot.out_link_icon.clone();
297        menu_options.push(ContextMenuItem::element_item(
298            Box::new(
299                move |state: &mut MouseState, style: &theme::ContextMenuItem| {
300                    Flex::row()
301                        .with_children([
302                            Label::new("Copilot Settings", style.label.clone()).boxed(),
303                            theme::ui::icon(icon_style.style_for(state, false)).boxed(),
304                        ])
305                        .align_children_center()
306                        .boxed()
307                },
308            ),
309            OsOpen::new(COPILOT_SETTINGS_URL),
310        ));
311
312        menu_options.push(ContextMenuItem::item("Sign Out", SignOut));
313
314        self.popup_menu.update(cx, |menu, cx| {
315            menu.show(
316                Default::default(),
317                AnchorCorner::BottomRight,
318                menu_options,
319                cx,
320            );
321        });
322    }
323
324    pub fn update_enabled(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
325        let editor = editor.read(cx);
326
327        let snapshot = editor.buffer().read(cx).snapshot(cx);
328        let settings = cx.global::<Settings>();
329        let suggestion_anchor = editor.selections.newest_anchor().start;
330
331        let language_name = snapshot
332            .language_at(suggestion_anchor)
333            .map(|language| language.name());
334
335        self.language = language_name.clone();
336
337        if let Some(enabled) = editor.copilot_state.user_enabled {
338            self.editor_enabled = Some(enabled);
339        } else {
340            self.editor_enabled = Some(settings.copilot_on(language_name.as_deref()));
341        }
342
343        cx.notify()
344    }
345}
346
347impl StatusItemView for CopilotButton {
348    fn set_active_pane_item(&mut self, item: Option<&dyn ItemHandle>, cx: &mut ViewContext<Self>) {
349        if let Some(editor) = item.map(|item| item.act_as::<Editor>(cx)).flatten() {
350            self.editor_subscription =
351                Some((cx.observe(&editor, Self::update_enabled), editor.id()));
352            self.update_enabled(editor, cx);
353        } else {
354            self.language = None;
355            self.editor_subscription = None;
356            self.editor_enabled = None;
357        }
358        cx.notify();
359    }
360}