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
use adw::{prelude::*, subclass::prelude::*};
use gtk::{
    glib,
    glib::{clone, closure_local},
    CompositeTemplate,
};

use crate::{
    components::crypto::{
        CryptoIdentitySetupNextStep, CryptoIdentitySetupView, CryptoRecoverySetupView,
    },
    session::model::{CryptoIdentityState, RecoveryState, Session, SessionVerificationState},
    spawn, spawn_tokio,
};

/// A page of the session setup stack.
#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::EnumString, strum::AsRefStr)]
#[strum(serialize_all = "kebab-case")]
enum SessionSetupPage {
    /// The loading page.
    Loading,
    /// The crypto identity setup view.
    CryptoIdentity,
    /// The recovery view.
    Recovery,
}

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/login/session_setup_view.ui")]
    #[properties(wrapper_type = super::SessionSetupView)]
    pub struct SessionSetupView {
        #[template_child]
        pub stack: TemplateChild<gtk::Stack>,
        /// The current session.
        #[property(get, set = Self::set_session, construct_only)]
        pub session: glib::WeakRef<Session>,
        /// The crypto identity view.
        crypto_identity_view: OnceCell<CryptoIdentitySetupView>,
        /// The recovery view.
        recovery_view: OnceCell<CryptoRecoverySetupView>,
        session_handler: RefCell<Option<glib::SignalHandlerId>>,
    }

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

        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 SessionSetupView {
        fn signals() -> &'static [Signal] {
            static SIGNALS: Lazy<Vec<Signal>> = Lazy::new(|| {
                vec![
                    // The session setup is done.
                    Signal::builder("completed").build(),
                ]
            });
            SIGNALS.as_ref()
        }

        fn dispose(&self) {
            if let Some(session) = self.session.upgrade() {
                if let Some(handler) = self.session_handler.take() {
                    session.disconnect(handler);
                }
            }
        }
    }

    impl WidgetImpl for SessionSetupView {
        fn grab_focus(&self) -> bool {
            match self.visible_stack_page() {
                SessionSetupPage::Loading => false,
                SessionSetupPage::CryptoIdentity => self.crypto_identity_view().grab_focus(),
                SessionSetupPage::Recovery => self.recovery_view().grab_focus(),
            }
        }
    }

    impl NavigationPageImpl for SessionSetupView {
        fn shown(&self) {
            self.grab_focus();
        }
    }

    impl SessionSetupView {
        /// The visible page of the stack.
        fn visible_stack_page(&self) -> SessionSetupPage {
            self.stack
                .visible_child_name()
                .and_then(|n| n.as_str().try_into().ok())
                .unwrap()
        }

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

                crypto_identity_view.connect_completed(clone!(@weak self as imp => move |_, next| {
                    match next {
                        CryptoIdentitySetupNextStep::None => imp.obj().emit_completed(),
                        CryptoIdentitySetupNextStep::EnableRecovery => imp.check_recovery(true),
                        CryptoIdentitySetupNextStep::CompleteRecovery => imp.check_recovery(false),
                    }
                }));

                crypto_identity_view
            })
        }

        /// 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();
                }));

                recovery_view
            })
        }

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

            let ready_handler = session.connect_ready(clone!(@weak self as imp => move |_| {
                spawn!(async move {
                    imp.load().await;
                });
            }));
            self.session_handler.replace(Some(ready_handler));
        }

        /// Load the session state.
        async fn load(&self) {
            let Some(session) = self.session.upgrade() else {
                return;
            };

            // Make sure the encryption API is ready.
            let encryption = session.client().encryption();
            spawn_tokio!(async move {
                encryption.wait_for_e2ee_initialization_tasks().await;
            })
            .await
            .unwrap();

            self.check_session_setup();
        }

        /// Check whether we need to show the session setup.
        fn check_session_setup(&self) {
            let Some(session) = self.session.upgrade() else {
                return;
            };

            // Stop listening to notifications.
            if let Some(handler) = self.session_handler.take() {
                session.disconnect(handler);
            }

            // Wait if we don't know the crypto identity state.
            let crypto_identity_state = session.crypto_identity_state();
            if crypto_identity_state == CryptoIdentityState::Unknown {
                let handler = session.connect_crypto_identity_state_notify(
                    clone!(@weak self as imp => move |_| {
                        imp.check_session_setup();
                    }),
                );
                self.session_handler.replace(Some(handler));
                return;
            }

            // Wait if we don't know the verification state.
            let verification_state = session.verification_state();
            if verification_state == SessionVerificationState::Unknown {
                let handler = session.connect_verification_state_notify(
                    clone!(@weak self as imp => move |_| {
                        imp.check_session_setup();
                    }),
                );
                self.session_handler.replace(Some(handler));
                return;
            }

            // Wait if we don't know the recovery state.
            let recovery_state = session.recovery_state();
            if recovery_state == RecoveryState::Unknown {
                let handler =
                    session.connect_recovery_state_notify(clone!(@weak self as imp => move |_| {
                        imp.check_session_setup();
                    }));
                self.session_handler.replace(Some(handler));
                return;
            }

            if verification_state == SessionVerificationState::Verified
                && recovery_state == RecoveryState::Enabled
            {
                // No need for setup.
                self.obj().emit_completed();
                return;
            }

            self.init();
        }

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

            let verification_state = session.verification_state();
            if verification_state == SessionVerificationState::Unverified {
                let crypto_identity_view = self.crypto_identity_view();

                self.stack.add_named(
                    crypto_identity_view,
                    Some(SessionSetupPage::CryptoIdentity.as_ref()),
                );
                self.stack
                    .set_visible_child_name(SessionSetupPage::CryptoIdentity.as_ref());
            } else {
                self.switch_to_recovery();
            }
        }

        /// Check whether we need to enable or set up recovery.
        pub(super) fn check_recovery(&self, enable_only: bool) {
            let Some(session) = self.session.upgrade() else {
                return;
            };

            match session.recovery_state() {
                RecoveryState::Disabled => {
                    self.switch_to_recovery();
                }
                RecoveryState::Incomplete if !enable_only => {
                    self.switch_to_recovery();
                }
                _ => {
                    self.obj().emit_completed();
                }
            }
        }

        /// Switch to the recovery view.
        fn switch_to_recovery(&self) {
            let recovery_view = self.recovery_view();

            self.stack
                .add_named(recovery_view, Some(SessionSetupPage::Recovery.as_ref()));
            self.stack
                .set_visible_child_name(SessionSetupPage::Recovery.as_ref());
        }
    }
}

glib::wrapper! {
    /// A view with the different flows to verify a session.
    pub struct SessionSetupView(ObjectSubclass<imp::SessionSetupView>)
        @extends gtk::Widget, adw::NavigationPage, @implements gtk::Accessible;
}

#[gtk::template_callbacks]
impl SessionSetupView {
    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) {
        let imp = self.imp();

        if !imp.stack.is_transition_running() {
            // Focus the default widget when the transition has ended.
            imp.grab_focus();
        }
    }

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

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