1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
use adw::{prelude::*, subclass::prelude::*};
use gettextrs::gettext;
use gtk::{
    glib,
    glib::{clone, closure_local},
    CompositeTemplate,
};
use tracing::{debug, error};

use super::{CryptoRecoverySetupInitialPage, CryptoRecoverySetupView};
use crate::{
    components::{AuthDialog, AuthError, LoadingButton},
    identity_verification_view::IdentityVerificationView,
    session::model::{
        CryptoIdentityState, IdentityVerification, RecoveryState, Session, SessionVerificationState,
    },
    spawn, toast,
    utils::BoundObjectWeakRef,
};

/// A page of the crypto identity setup navigation stack.
#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::EnumString, strum::AsRefStr, glib::Variant)]
#[strum(serialize_all = "kebab-case")]
enum CryptoIdentitySetupPage {
    /// Choose a verification method.
    ChooseMethod,
    /// In-progress verification.
    Verify,
    /// Bootstrap cross-signing.
    Bootstrap,
    /// Reset cross-signing.
    Reset,
    /// Use recovery or reset cross-signing and recovery.
    Recovery,
}

/// The result of the crypto identity setup.
#[derive(Debug, Clone, Copy, PartialEq, Eq, glib::Enum)]
#[enum_type(name = "CryptoIdentitySetupNextStep")]
pub enum CryptoIdentitySetupNextStep {
    /// No more steps should be needed.
    None,
    /// We should enable the recovery, if it is disabled.
    EnableRecovery,
    /// We should make sure that the recovery is fully set up.
    CompleteRecovery,
}

mod imp {
    use std::cell::{OnceCell, RefCell};

    use glib::subclass::{InitializingObject, Signal};
    use once_cell::sync::Lazy;

    use super::*;

    #[derive(Debug, Default, CompositeTemplate, glib::Properties)]
    #[template(resource = "/org/gnome/Fractal/ui/components/crypto/identity_setup_view.ui")]
    #[properties(wrapper_type = super::CryptoIdentitySetupView)]
    pub struct CryptoIdentitySetupView {
        #[template_child]
        pub navigation: TemplateChild<adw::NavigationView>,
        #[template_child]
        pub send_request_btn: TemplateChild<LoadingButton>,
        #[template_child]
        pub use_recovery_btn: TemplateChild<gtk::Button>,
        #[template_child]
        pub verification_page: TemplateChild<IdentityVerificationView>,
        #[template_child]
        pub bootstrap_btn: TemplateChild<LoadingButton>,
        #[template_child]
        pub reset_btn: TemplateChild<gtk::Button>,
        /// The current session.
        #[property(get, set = Self::set_session, construct_only)]
        pub session: glib::WeakRef<Session>,
        /// The ongoing identity verification, if any.
        #[property(get)]
        pub verification: BoundObjectWeakRef<IdentityVerification>,
        verification_list_handler: RefCell<Option<glib::SignalHandlerId>>,
        /// The recovery view.
        recovery_view: OnceCell<CryptoRecoverySetupView>,
    }

    #[glib::object_subclass]
    impl ObjectSubclass for CryptoIdentitySetupView {
        const NAME: &'static str = "CryptoIdentitySetupView";
        type Type = super::CryptoIdentitySetupView;
        type ParentType = adw::Bin;

        fn class_init(klass: &mut Self::Class) {
            Self::bind_template(klass);
            Self::Type::bind_template_callbacks(klass);

            klass.set_css_name("setup-view");
        }

        fn instance_init(obj: &InitializingObject<Self>) {
            obj.init_template();
        }
    }

    #[glib::derived_properties]
    impl ObjectImpl for CryptoIdentitySetupView {
        fn signals() -> &'static [Signal] {
            static SIGNALS: Lazy<Vec<Signal>> = Lazy::new(|| {
                vec![
                    // The crypto identity setup is done.
                    Signal::builder("completed")
                        .param_types([CryptoIdentitySetupNextStep::static_type()])
                        .build(),
                ]
            });
            SIGNALS.as_ref()
        }

        fn dispose(&self) {
            if let Some(verification) = self.verification.obj() {
                spawn!(clone!(@strong verification => async move {
                    let _ = verification.cancel().await;
                }));
            }

            if let Some(session) = self.session.upgrade() {
                if let Some(handler) = self.verification_list_handler.take() {
                    session.verification_list().disconnect(handler);
                }
            }
        }
    }

    impl WidgetImpl for CryptoIdentitySetupView {
        fn grab_focus(&self) -> bool {
            match self.visible_page() {
                CryptoIdentitySetupPage::ChooseMethod => self.send_request_btn.grab_focus(),
                CryptoIdentitySetupPage::Verify => self.verification_page.grab_focus(),
                CryptoIdentitySetupPage::Bootstrap => self.bootstrap_btn.grab_focus(),
                CryptoIdentitySetupPage::Reset => self.reset_btn.grab_focus(),
                CryptoIdentitySetupPage::Recovery => self.recovery_view().grab_focus(),
            }
        }
    }

    impl BinImpl for CryptoIdentitySetupView {}

    impl CryptoIdentitySetupView {
        /// The visible page of the view.
        fn visible_page(&self) -> CryptoIdentitySetupPage {
            self.navigation
                .visible_page()
                .and_then(|p| p.tag())
                .and_then(|t| t.as_str().try_into().ok())
                .unwrap()
        }

        /// The recovery view.
        fn recovery_view(&self) -> &CryptoRecoverySetupView {
            self.recovery_view.get_or_init(|| {
                let session = self
                    .session
                    .upgrade()
                    .expect("Session should still have a strong reference");
                let recovery_view = CryptoRecoverySetupView::new(&session);

                let obj = self.obj();
                recovery_view.connect_completed(clone!(@weak obj => move |_| {
                    obj.emit_completed(CryptoIdentitySetupNextStep::None);
                }));

                recovery_view
            })
        }

        /// Set the current session.
        fn set_session(&self, session: &Session) {
            self.session.set(Some(session));

            // Use received verification requests too.
            let verification_list = session.verification_list();
            let verification_list_handler = verification_list.connect_items_changed(
                clone!(@weak self as imp => move |verification_list, _, _, _| {
                    if imp.verification.obj().is_some() {
                        // We don't want to override the current verification.
                        return;
                    }

                    if let Some(verification) = verification_list.ongoing_session_verification() {
                        imp.set_verification(Some(verification));
                    }
                }),
            );
            self.verification_list_handler
                .replace(Some(verification_list_handler));

            self.init();
        }

        /// Initialize the view.
        fn init(&self) {
            let Some(session) = self.session.upgrade() else {
                return;
            };

            // If the session is already verified, offer to reset it.
            let verification_state = session.verification_state();
            if verification_state == SessionVerificationState::Verified {
                self.navigation
                    .replace_with_tags(&[CryptoIdentitySetupPage::Reset.as_ref()]);
                return;
            }

            let crypto_identity_state = session.crypto_identity_state();
            let recovery_state = session.recovery_state();

            // If there is no crypto identity, we need to bootstrap it.
            if crypto_identity_state == CryptoIdentityState::Missing {
                self.navigation
                    .replace_with_tags(&[CryptoIdentitySetupPage::Bootstrap.as_ref()]);
                return;
            }

            // If there is no other session available, we can only use recovery or reset.
            if crypto_identity_state == CryptoIdentityState::LastManStanding {
                let recovery_view = if recovery_state == RecoveryState::Disabled {
                    // If recovery is disabled, we can only reset.
                    self.recovery_page(CryptoRecoverySetupInitialPage::Reset)
                } else {
                    // We can recover or reset.
                    self.recovery_page(CryptoRecoverySetupInitialPage::Recover)
                };

                self.navigation.replace(&[recovery_view]);

                return;
            }

            if let Some(verification) = session.verification_list().ongoing_session_verification() {
                self.set_verification(Some(verification));
            }

            // Choose methods is the default page.
            self.update_choose_methods();
        }

        /// Update the choose methods page for the current state.
        fn update_choose_methods(&self) {
            let Some(session) = self.session.upgrade() else {
                return;
            };

            let can_recover = session.recovery_state() != RecoveryState::Disabled;
            self.use_recovery_btn.set_visible(can_recover);
        }

        /// Set the ongoing identity verification.
        ///
        /// Cancels the previous verification if it's not finished.
        pub(super) fn set_verification(&self, verification: Option<IdentityVerification>) {
            let prev_verification = self.verification.obj();

            if prev_verification == verification {
                return;
            }
            let obj = self.obj();

            if let Some(verification) = prev_verification {
                if !verification.is_finished() {
                    spawn!(clone!(@strong verification => async move {
                        let _ = verification.cancel().await;
                    }));
                }

                self.verification.disconnect_signals();
            }

            if let Some(verification) = &verification {
                let replaced_handler = verification.connect_replaced(
                    clone!(@weak self as imp => move |_, new_verification| {
                        imp.set_verification(Some(new_verification.clone()));
                    }),
                );
                let done_handler = verification.connect_done(
                    clone!(@weak obj => @default-return glib::Propagation::Stop, move |verification| {
                        obj.emit_completed(CryptoIdentitySetupNextStep::EnableRecovery);
                        obj.imp().set_verification(None);
                        verification.remove_from_list();

                        glib::Propagation::Stop
                    }),
                );
                let remove_handler =
                    verification.connect_dismiss(clone!(@weak self as imp => move |_| {
                        imp.navigation.pop();
                        imp.set_verification(None);
                    }));

                self.verification.set(
                    verification,
                    vec![replaced_handler, done_handler, remove_handler],
                );
            }

            let has_verification = verification.is_some();
            self.verification_page.set_verification(verification);

            if has_verification
                && !self
                    .navigation
                    .visible_page()
                    .and_then(|p| p.tag())
                    .is_some_and(|t| t == CryptoIdentitySetupPage::Verify.as_ref())
            {
                self.navigation
                    .push_by_tag(CryptoIdentitySetupPage::Verify.as_ref());
            }

            obj.notify_verification();
        }

        /// Construct the recovery view and wrap it into a navigation page.
        pub(super) fn recovery_page(
            &self,
            initial_page: CryptoRecoverySetupInitialPage,
        ) -> adw::NavigationPage {
            let recovery_view = self.recovery_view();
            recovery_view.set_initial_page(initial_page);

            let page = adw::NavigationPage::builder()
                .tag(CryptoIdentitySetupPage::Recovery.as_ref())
                .child(recovery_view)
                .build();
            page.connect_shown(clone!(@weak recovery_view => move |_| {
                recovery_view.grab_focus();
            }));

            page
        }
    }
}

glib::wrapper! {
    /// A view with the different flows to setup a crypto identity.
    pub struct CryptoIdentitySetupView(ObjectSubclass<imp::CryptoIdentitySetupView>)
        @extends gtk::Widget, adw::Bin, @implements gtk::Accessible;
}

#[gtk::template_callbacks]
impl CryptoIdentitySetupView {
    pub fn new(session: &Session) -> Self {
        glib::Object::builder().property("session", session).build()
    }

    /// Focus the proper widget for the current page.
    #[template_callback]
    fn grab_focus(&self) {
        self.imp().grab_focus();
    }

    /// Create a new verification request.
    #[template_callback]
    async fn send_request(&self) {
        let Some(session) = self.session() else {
            return;
        };

        let imp = self.imp();
        imp.send_request_btn.set_is_loading(true);

        match session.verification_list().create(None).await {
            Ok(_) => {
                // The verification should be shown automatically.
            }
            Err(()) => {
                toast!(self, gettext("Could not send a new verification request"));
            }
        }

        imp.send_request_btn.set_is_loading(false);
    }

    /// Reset cross-signing and optionally recovery.
    #[template_callback]
    fn reset(&self) {
        let Some(session) = self.session() else {
            return;
        };

        let imp = self.imp();
        let can_recover = session.recovery_state() != RecoveryState::Disabled;

        if can_recover {
            let recovery_view = imp.recovery_page(CryptoRecoverySetupInitialPage::Reset);
            imp.navigation.push(&recovery_view);
        } else {
            imp.navigation
                .push_by_tag(CryptoIdentitySetupPage::Bootstrap.as_ref());
        }
    }

    /// Create a new crypto user identity.
    #[template_callback]
    async fn bootstrap_cross_signing(&self) {
        let Some(session) = self.session() else {
            return;
        };

        let imp = self.imp();
        imp.bootstrap_btn.set_is_loading(true);

        let dialog = AuthDialog::new(&session);

        let result = dialog
            .authenticate(self, move |client, auth| async move {
                client.encryption().bootstrap_cross_signing(auth).await
            })
            .await;

        match result {
            Ok(_) => self.emit_completed(CryptoIdentitySetupNextStep::CompleteRecovery),
            Err(AuthError::UserCancelled) => {
                debug!("User cancelled authentication for cross-signing bootstrap");
            }
            Err(error) => {
                error!("Could not bootstrap cross-signing: {error:?}");
                toast!(self, gettext("Could not create the crypto identity",));
            }
        }

        imp.bootstrap_btn.set_is_loading(false);
    }

    /// Recover the data.
    #[template_callback]
    fn recover(&self) {
        let imp = self.imp();

        let recovery_view = imp.recovery_page(CryptoRecoverySetupInitialPage::Recover);
        imp.navigation.push(&recovery_view);
    }

    // Emit the `completed` signal.
    #[template_callback]
    fn emit_completed(&self, next: CryptoIdentitySetupNextStep) {
        self.emit_by_name::<()>("completed", &[&next]);
    }

    /// Connect to the signal emitted when the setup is completed.
    pub fn connect_completed<F: Fn(&Self, CryptoIdentitySetupNextStep) + 'static>(
        &self,
        f: F,
    ) -> glib::SignalHandlerId {
        self.connect_closure(
            "completed",
            true,
            closure_local!(move |obj: Self, next: CryptoIdentitySetupNextStep| {
                f(&obj, next);
            }),
        )
    }
}