copilot_button.rs

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