sign_in.rs

  1use crate::{request::PromptUserDeviceFlow, Copilot, Status};
  2use gpui::{
  3    elements::*,
  4    geometry::rect::RectF,
  5    impl_internal_actions,
  6    platform::{WindowBounds, WindowKind, WindowOptions},
  7    AppContext, ClipboardItem, Element, Entity, View, ViewContext, ViewHandle,
  8};
  9use settings::Settings;
 10use theme::ui::modal;
 11
 12#[derive(PartialEq, Eq, Debug, Clone)]
 13struct ClickedConnect;
 14
 15impl_internal_actions!(copilot_verification, [ClickedConnect]);
 16
 17#[derive(PartialEq, Eq, Debug, Clone)]
 18struct CopyUserCode;
 19
 20#[derive(PartialEq, Eq, Debug, Clone)]
 21struct OpenGithub;
 22
 23const COPILOT_SIGN_UP_URL: &'static str = "https://github.com/features/copilot";
 24
 25pub fn init(cx: &mut AppContext) {
 26    if let Some(copilot) = Copilot::global(cx) {
 27        let mut code_verification: Option<ViewHandle<CopilotCodeVerification>> = None;
 28        cx.observe(&copilot, move |copilot, cx| {
 29            let status = copilot.read(cx).status();
 30
 31            match &status {
 32                crate::Status::SigningIn { prompt } => {
 33                    if let Some(code_verification_handle) = code_verification.as_mut() {
 34                        if cx.has_window(code_verification_handle.window_id()) {
 35                            code_verification_handle.update(cx, |code_verification_view, cx| {
 36                                code_verification_view.set_status(status, cx)
 37                            });
 38                            cx.activate_window(code_verification_handle.window_id());
 39                        } else {
 40                            create_copilot_auth_window(cx, &status, &mut code_verification);
 41                        }
 42                    } else if let Some(_prompt) = prompt {
 43                        create_copilot_auth_window(cx, &status, &mut code_verification);
 44                    }
 45                }
 46                Status::Authorized | Status::Unauthorized => {
 47                    if let Some(code_verification) = code_verification.as_ref() {
 48                        code_verification.update(cx, |code_verification, cx| {
 49                            code_verification.set_status(status, cx)
 50                        });
 51
 52                        cx.platform().activate(true);
 53                        cx.activate_window(code_verification.window_id());
 54                    }
 55                }
 56                _ => {
 57                    if let Some(code_verification) = code_verification.take() {
 58                        cx.remove_window(code_verification.window_id());
 59                    }
 60                }
 61            }
 62        })
 63        .detach();
 64
 65        cx.add_action(
 66            |code_verification: &mut CopilotCodeVerification, _: &ClickedConnect, _| {
 67                code_verification.connect_clicked = true;
 68            },
 69        );
 70    }
 71}
 72
 73fn create_copilot_auth_window(
 74    cx: &mut AppContext,
 75    status: &Status,
 76    code_verification: &mut Option<ViewHandle<CopilotCodeVerification>>,
 77) {
 78    let window_size = cx.global::<Settings>().theme.copilot.modal.dimensions();
 79    let window_options = WindowOptions {
 80        bounds: WindowBounds::Fixed(RectF::new(Default::default(), window_size)),
 81        titlebar: None,
 82        center: true,
 83        focus: true,
 84        kind: WindowKind::Normal,
 85        is_movable: true,
 86        screen: None,
 87    };
 88    let (_, view) = cx.add_window(window_options, |_cx| {
 89        CopilotCodeVerification::new(status.clone())
 90    });
 91    *code_verification = Some(view);
 92}
 93
 94pub struct CopilotCodeVerification {
 95    status: Status,
 96    connect_clicked: bool,
 97}
 98
 99impl CopilotCodeVerification {
100    pub fn new(status: Status) -> Self {
101        Self {
102            status,
103            connect_clicked: false,
104        }
105    }
106
107    pub fn set_status(&mut self, status: Status, cx: &mut ViewContext<Self>) {
108        self.status = status;
109        cx.notify();
110    }
111
112    fn render_device_code(
113        data: &PromptUserDeviceFlow,
114        style: &theme::Copilot,
115        cx: &mut gpui::RenderContext<Self>,
116    ) -> ElementBox {
117        let copied = cx
118            .read_from_clipboard()
119            .map(|item| item.text() == &data.user_code)
120            .unwrap_or(false);
121
122        let device_code_style = &style.auth.prompting.device_code;
123
124        MouseEventHandler::<Self>::new(0, cx, |state, _cx| {
125            Flex::row()
126                .with_children([
127                    Label::new(data.user_code.clone(), device_code_style.text.clone())
128                        .aligned()
129                        .contained()
130                        .with_style(device_code_style.left_container)
131                        .constrained()
132                        .with_width(device_code_style.left)
133                        .boxed(),
134                    Label::new(
135                        if copied { "Copied!" } else { "Copy" },
136                        device_code_style.cta.style_for(state, false).text.clone(),
137                    )
138                    .aligned()
139                    .contained()
140                    .with_style(*device_code_style.right_container.style_for(state, false))
141                    .constrained()
142                    .with_width(device_code_style.right)
143                    .boxed(),
144                ])
145                .contained()
146                .with_style(device_code_style.cta.style_for(state, false).container)
147                .boxed()
148        })
149        .on_click(gpui::platform::MouseButton::Left, {
150            let user_code = data.user_code.clone();
151            move |_, cx| {
152                cx.platform()
153                    .write_to_clipboard(ClipboardItem::new(user_code.clone()));
154                cx.notify();
155            }
156        })
157        .with_cursor_style(gpui::platform::CursorStyle::PointingHand)
158        .boxed()
159    }
160
161    fn render_prompting_modal(
162        connect_clicked: bool,
163        data: &PromptUserDeviceFlow,
164        style: &theme::Copilot,
165        cx: &mut gpui::RenderContext<Self>,
166    ) -> ElementBox {
167        Flex::column()
168            .with_children([
169                Flex::column()
170                    .with_children([
171                        Label::new(
172                            "Enable Copilot by connecting",
173                            style.auth.prompting.subheading.text.clone(),
174                        )
175                        .aligned()
176                        .boxed(),
177                        Label::new(
178                            "your existing license.",
179                            style.auth.prompting.subheading.text.clone(),
180                        )
181                        .aligned()
182                        .boxed(),
183                    ])
184                    .align_children_center()
185                    .contained()
186                    .with_style(style.auth.prompting.subheading.container)
187                    .boxed(),
188                Self::render_device_code(data, &style, cx),
189                Flex::column()
190                    .with_children([
191                        Label::new(
192                            "Paste this code into GitHub after",
193                            style.auth.prompting.hint.text.clone(),
194                        )
195                        .aligned()
196                        .boxed(),
197                        Label::new(
198                            "clicking the button below.",
199                            style.auth.prompting.hint.text.clone(),
200                        )
201                        .aligned()
202                        .boxed(),
203                    ])
204                    .align_children_center()
205                    .contained()
206                    .with_style(style.auth.prompting.hint.container.clone())
207                    .boxed(),
208                theme::ui::cta_button_with_click(
209                    if connect_clicked {
210                        "Waiting for connection..."
211                    } else {
212                        "Connect to GitHub"
213                    },
214                    style.auth.content_width,
215                    &style.auth.cta_button,
216                    cx,
217                    {
218                        let verification_uri = data.verification_uri.clone();
219                        move |_, cx| {
220                            cx.platform().open_url(&verification_uri);
221                            cx.dispatch_action(ClickedConnect)
222                        }
223                    },
224                )
225                .boxed(),
226            ])
227            .align_children_center()
228            .boxed()
229    }
230    fn render_enabled_modal(
231        style: &theme::Copilot,
232        cx: &mut gpui::RenderContext<Self>,
233    ) -> ElementBox {
234        let enabled_style = &style.auth.authorized;
235        Flex::column()
236            .with_children([
237                Label::new("Copilot Enabled!", enabled_style.subheading.text.clone())
238                    .contained()
239                    .with_style(enabled_style.subheading.container)
240                    .aligned()
241                    .boxed(),
242                Flex::column()
243                    .with_children([
244                        Label::new(
245                            "You can update your settings or",
246                            enabled_style.hint.text.clone(),
247                        )
248                        .aligned()
249                        .boxed(),
250                        Label::new(
251                            "sign out from the Copilot menu in",
252                            enabled_style.hint.text.clone(),
253                        )
254                        .aligned()
255                        .boxed(),
256                        Label::new("the status bar.", enabled_style.hint.text.clone())
257                            .aligned()
258                            .boxed(),
259                    ])
260                    .align_children_center()
261                    .contained()
262                    .with_style(enabled_style.hint.container)
263                    .boxed(),
264                theme::ui::cta_button_with_click(
265                    "Done",
266                    style.auth.content_width,
267                    &style.auth.cta_button,
268                    cx,
269                    |_, cx| {
270                        let window_id = cx.window_id();
271                        cx.remove_window(window_id)
272                    },
273                )
274                .boxed(),
275            ])
276            .align_children_center()
277            .boxed()
278    }
279    fn render_unauthorized_modal(
280        style: &theme::Copilot,
281        cx: &mut gpui::RenderContext<Self>,
282    ) -> ElementBox {
283        let unauthorized_style = &style.auth.not_authorized;
284
285        Flex::column()
286            .with_children([
287                Flex::column()
288                    .with_children([
289                        Label::new(
290                            "Enable Copilot by connecting",
291                            unauthorized_style.subheading.text.clone(),
292                        )
293                        .aligned()
294                        .boxed(),
295                        Label::new(
296                            "your existing license.",
297                            unauthorized_style.subheading.text.clone(),
298                        )
299                        .aligned()
300                        .boxed(),
301                    ])
302                    .align_children_center()
303                    .contained()
304                    .with_style(unauthorized_style.subheading.container)
305                    .boxed(),
306                Flex::column()
307                    .with_children([
308                        Label::new(
309                            "You must have an active copilot",
310                            unauthorized_style.warning.text.clone(),
311                        )
312                        .aligned()
313                        .boxed(),
314                        Label::new(
315                            "license to use it in Zed.",
316                            unauthorized_style.warning.text.clone(),
317                        )
318                        .aligned()
319                        .boxed(),
320                    ])
321                    .align_children_center()
322                    .contained()
323                    .with_style(unauthorized_style.warning.container)
324                    .boxed(),
325                theme::ui::cta_button_with_click(
326                    "Subscribe on GitHub",
327                    style.auth.content_width,
328                    &style.auth.cta_button,
329                    cx,
330                    |_, cx| {
331                        let window_id = cx.window_id();
332                        cx.remove_window(window_id);
333                        cx.platform().open_url(COPILOT_SIGN_UP_URL)
334                    },
335                )
336                .boxed(),
337            ])
338            .align_children_center()
339            .boxed()
340    }
341}
342
343impl Entity for CopilotCodeVerification {
344    type Event = ();
345}
346
347impl View for CopilotCodeVerification {
348    fn ui_name() -> &'static str {
349        "CopilotCodeVerification"
350    }
351
352    fn focus_in(&mut self, _: gpui::AnyViewHandle, cx: &mut gpui::ViewContext<Self>) {
353        cx.notify()
354    }
355
356    fn focus_out(&mut self, _: gpui::AnyViewHandle, cx: &mut gpui::ViewContext<Self>) {
357        cx.notify()
358    }
359
360    fn render(&mut self, cx: &mut gpui::RenderContext<'_, Self>) -> gpui::ElementBox {
361        let style = cx.global::<Settings>().theme.clone();
362
363        modal("Connect Copilot to Zed", &style.copilot.modal, cx, |cx| {
364            Flex::column()
365                .with_children([
366                    theme::ui::icon(&style.copilot.auth.header).boxed(),
367                    match &self.status {
368                        Status::SigningIn {
369                            prompt: Some(prompt),
370                        } => Self::render_prompting_modal(
371                            self.connect_clicked,
372                            &prompt,
373                            &style.copilot,
374                            cx,
375                        ),
376                        Status::Unauthorized => {
377                            self.connect_clicked = false;
378                            Self::render_unauthorized_modal(&style.copilot, cx)
379                        }
380                        Status::Authorized => {
381                            self.connect_clicked = false;
382                            Self::render_enabled_modal(&style.copilot, cx)
383                        }
384                        _ => Empty::new().boxed(),
385                    },
386                ])
387                .align_children_center()
388                .boxed()
389        })
390    }
391}