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
use adw::{prelude::*, subclass::prelude::*};
use gettextrs::gettext;
use gtk::{
    gio,
    glib::{self, clone},
    CompositeTemplate,
};
use tracing::error;

mod change_password_subpage;
mod deactivate_account_subpage;
mod log_out_subpage;

pub use self::{
    change_password_subpage::ChangePasswordSubpage,
    deactivate_account_subpage::DeactivateAccountSubpage, log_out_subpage::LogOutSubpage,
};
use crate::{
    components::{ActionButton, ActionState, ButtonRow, CopyableRow, EditableAvatar},
    prelude::*,
    session::model::Session,
    spawn, spawn_tokio, toast,
    utils::{media::load_file, template_callbacks::TemplateCallbacks, OngoingAsyncAction},
};

mod imp {
    use std::cell::RefCell;

    use glib::subclass::InitializingObject;

    use super::*;

    #[derive(Debug, Default, CompositeTemplate, glib::Properties)]
    #[template(
        resource = "/org/gnome/Fractal/ui/session/view/account_settings/general_page/mod.ui"
    )]
    #[properties(wrapper_type = super::GeneralPage)]
    pub struct GeneralPage {
        /// The current session.
        #[property(get, set = Self::set_session, nullable)]
        pub session: glib::WeakRef<Session>,
        #[template_child]
        pub avatar: TemplateChild<EditableAvatar>,
        #[template_child]
        pub display_name: TemplateChild<adw::EntryRow>,
        #[template_child]
        pub display_name_button: TemplateChild<ActionButton>,
        #[template_child]
        pub change_password_group: TemplateChild<adw::PreferencesGroup>,
        #[template_child]
        pub homeserver: TemplateChild<CopyableRow>,
        #[template_child]
        pub user_id: TemplateChild<CopyableRow>,
        #[template_child]
        pub session_id: TemplateChild<CopyableRow>,
        pub changing_avatar: RefCell<Option<OngoingAsyncAction<String>>>,
        pub changing_display_name: RefCell<Option<OngoingAsyncAction<String>>>,
        pub avatar_uri_handler: RefCell<Option<glib::SignalHandlerId>>,
        pub display_name_handler: RefCell<Option<glib::SignalHandlerId>>,
    }

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

        fn class_init(klass: &mut Self::Class) {
            ButtonRow::ensure_type();

            Self::bind_template(klass);
            Self::Type::bind_template_callbacks(klass);
            TemplateCallbacks::bind_template_callbacks(klass);
        }

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

    #[glib::derived_properties]
    impl ObjectImpl for GeneralPage {}

    impl WidgetImpl for GeneralPage {}
    impl PreferencesPageImpl for GeneralPage {}

    impl GeneralPage {
        /// Set the current session.
        fn set_session(&self, session: Option<Session>) {
            let prev_session = self.session.upgrade();
            if prev_session == session {
                return;
            }
            let obj = self.obj();

            if let Some(session) = prev_session {
                let user = session.user();

                if let Some(handler) = self.avatar_uri_handler.take() {
                    user.avatar_data().image().unwrap().disconnect(handler)
                }
                if let Some(handler) = self.display_name_handler.take() {
                    user.disconnect(handler);
                }
            }

            self.session.set(session.as_ref());
            obj.notify_session();

            let Some(session) = session else {
                return;
            };

            self.user_id.set_subtitle(session.user_id().as_str());
            self.homeserver.set_subtitle(session.homeserver().as_str());
            self.session_id.set_subtitle(session.device_id().as_str());

            let user = session.user();
            let avatar_uri_handler =
                user.avatar_data()
                    .image()
                    .unwrap()
                    .connect_uri_notify(clone!(
                        #[weak]
                        obj,
                        move |avatar_image| {
                            obj.user_avatar_changed(avatar_image.uri());
                        }
                    ));
            self.avatar_uri_handler.replace(Some(avatar_uri_handler));

            let display_name_handler = user.connect_display_name_notify(clone!(
                #[weak]
                obj,
                move |user| {
                    obj.user_display_name_changed(user.display_name());
                }
            ));
            self.display_name_handler
                .replace(Some(display_name_handler));

            spawn!(
                glib::Priority::LOW,
                clone!(
                    #[weak(rename_to = imp)]
                    self,
                    async move {
                        imp.load_can_change_password().await;
                    }
                )
            );
        }

        /// Load whether the user can change their password.
        async fn load_can_change_password(&self) {
            let Some(session) = self.session.upgrade() else {
                return;
            };
            let client = session.client();

            // Check whether the user can change their password.
            let handle = spawn_tokio!(async move { client.get_capabilities().await });
            let can_change_password = match handle.await.unwrap() {
                Ok(capabilities) => capabilities.change_password.enabled,
                Err(error) => {
                    error!("Could not get server capabilities: {error}");
                    false
                }
            };

            self.change_password_group.set_visible(can_change_password);
        }
    }
}

glib::wrapper! {
    /// Account settings page about the user and the session.
    pub struct GeneralPage(ObjectSubclass<imp::GeneralPage>)
        @extends gtk::Widget, adw::PreferencesPage, @implements gtk::Accessible;
}

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

    /// Update the view when the user's avatar changed.
    fn user_avatar_changed(&self, uri: Option<String>) {
        let imp = self.imp();

        if let Some(action) = imp.changing_avatar.borrow().as_ref() {
            if uri.as_ref() != action.as_value() {
                // This is not the change we expected, maybe another device did a change too.
                // Let's wait for another change.
                return;
            }
        } else {
            // No action is ongoing, we don't need to do anything.
            return;
        };

        // Reset the state.
        imp.changing_avatar.take();
        imp.avatar.success();
        if uri.is_none() {
            toast!(self, gettext("Avatar removed successfully"));
        } else {
            toast!(self, gettext("Avatar changed successfully"));
        }
    }

    /// Change the avatar of the user with the one in the given file.
    #[template_callback]
    async fn change_avatar(&self, file: gio::File) {
        let Some(session) = self.session() else {
            return;
        };

        let imp = self.imp();
        let avatar = &imp.avatar;
        avatar.edit_in_progress();

        let (data, info) = match load_file(&file).await {
            Ok(res) => res,
            Err(error) => {
                error!("Could not load user avatar file: {error}");
                toast!(self, gettext("Could not load file"));
                avatar.reset();
                return;
            }
        };

        let client = session.client();
        let client_clone = client.clone();
        let handle =
            spawn_tokio!(async move { client_clone.media().upload(&info.mime, data).await });

        let uri = match handle.await.unwrap() {
            Ok(res) => res.content_uri,
            Err(error) => {
                error!("Could not upload user avatar: {error}");
                toast!(self, gettext("Could not upload avatar"));
                avatar.reset();
                return;
            }
        };

        let (action, weak_action) = OngoingAsyncAction::set(uri.to_string());
        imp.changing_avatar.replace(Some(action));

        let uri_clone = uri.clone();
        let handle =
            spawn_tokio!(async move { client.account().set_avatar_url(Some(&uri_clone)).await });

        match handle.await.unwrap() {
            Ok(_) => {
                // If the user is in no rooms, we won't receive the update via sync, so change
                // the avatar manually if this request succeeds before the avatar is updated.
                // Because this action can finish in user_avatar_changed, we must only act if
                // this is still the current action.
                if weak_action.is_ongoing() {
                    session.user().set_avatar_url(Some(uri))
                }
            }
            Err(error) => {
                // Because this action can finish in user_avatar_changed, we must only act if
                // this is still the current action.
                if weak_action.is_ongoing() {
                    imp.changing_avatar.take();
                    error!("Could not change user avatar: {error}");
                    toast!(self, gettext("Could not change avatar"));
                    avatar.reset();
                }
            }
        }
    }

    /// Remove the current avatar of the user.
    #[template_callback]
    async fn remove_avatar(&self) {
        let Some(session) = self.session() else {
            return;
        };

        // Ask for confirmation.
        let confirm_dialog = adw::AlertDialog::builder()
            .default_response("cancel")
            .heading(gettext("Remove Avatar?"))
            .body(gettext("Do you really want to remove your avatar?"))
            .build();
        confirm_dialog.add_responses(&[
            ("cancel", &gettext("Cancel")),
            ("remove", &gettext("Remove")),
        ]);
        confirm_dialog.set_response_appearance("remove", adw::ResponseAppearance::Destructive);

        if confirm_dialog.choose_future(self).await != "remove" {
            return;
        }

        let imp = self.imp();
        let avatar = &*imp.avatar;
        avatar.removal_in_progress();

        let (action, weak_action) = OngoingAsyncAction::remove();
        imp.changing_avatar.replace(Some(action));

        let client = session.client();
        let handle = spawn_tokio!(async move { client.account().set_avatar_url(None).await });

        match handle.await.unwrap() {
            Ok(_) => {
                // If the user is in no rooms, we won't receive the update via sync, so change
                // the avatar manually if this request succeeds before the avatar is updated.
                // Because this action can finish in avatar_changed, we must only act if this is
                // still the current action.
                if weak_action.is_ongoing() {
                    session.user().set_avatar_url(None)
                }
            }
            Err(error) => {
                // Because this action can finish in avatar_changed, we must only act if this is
                // still the current action.
                if weak_action.is_ongoing() {
                    imp.changing_avatar.take();
                    error!("Could not remove user avatar: {error}");
                    toast!(self, gettext("Could not remove avatar"));
                    avatar.reset();
                }
            }
        }
    }

    /// Update the view when the text of the display name changed.
    #[template_callback]
    fn display_name_changed(&self) {
        self.imp()
            .display_name_button
            .set_visible(self.has_display_name_changed());
    }

    /// Whether the display name in the entry row is different than the user's.
    fn has_display_name_changed(&self) -> bool {
        let Some(session) = self.session() else {
            return false;
        };
        let imp = self.imp();
        let text = imp.display_name.text();
        let display_name = session.user().display_name();

        text != display_name
    }

    /// Update the view when the user's display name changed.
    fn user_display_name_changed(&self, name: String) {
        let imp = self.imp();

        if let Some(action) = imp.changing_display_name.borrow().as_ref() {
            if action.as_value() == Some(&name) {
                // This is not the change we expected, maybe another device did a change too.
                // Let's wait for another change.
                return;
            }
        } else {
            // No action is ongoing, we don't need to do anything.
            return;
        }

        // Reset state.
        imp.changing_display_name.take();

        let entry = &imp.display_name;
        let button = &imp.display_name_button;

        entry.remove_css_class("error");
        entry.set_sensitive(true);
        button.set_visible(false);
        button.set_state(ActionState::Confirm);
        toast!(self, gettext("Name changed successfully"));
    }

    /// Change the display name of the user.
    #[template_callback]
    async fn change_display_name(&self) {
        if !self.has_display_name_changed() {
            // Nothing to do.
            return;
        }
        let Some(session) = self.session() else {
            return;
        };

        let imp = self.imp();
        let entry = &imp.display_name;
        let button = &imp.display_name_button;

        entry.set_sensitive(false);
        button.set_state(ActionState::Loading);

        let display_name = entry.text().trim().to_string();

        let (action, weak_action) = OngoingAsyncAction::set(display_name.clone());
        imp.changing_display_name.replace(Some(action));

        let client = session.client();
        let display_name_clone = display_name.clone();
        let handle = spawn_tokio!(async move {
            client
                .account()
                .set_display_name(Some(&display_name_clone))
                .await
        });

        match handle.await.unwrap() {
            Ok(_) => {
                // If the user is in no rooms, we won't receive the update via sync, so change
                // the avatar manually if this request succeeds before the avatar is updated.
                // Because this action can finish in user_display_name_changed, we must only act
                // if this is still the current action.
                if weak_action.is_ongoing() {
                    session.user().set_name(Some(display_name));
                }
            }
            Err(error) => {
                // Because this action can finish in user_display_name_changed, we must only act
                // if this is still the current action.
                if weak_action.is_ongoing() {
                    imp.changing_display_name.take();
                    error!("Could not change user display name: {error}");
                    toast!(self, gettext("Could not change display name"));
                    button.set_state(ActionState::Retry);
                    entry.add_css_class("error");
                    entry.set_sensitive(true);
                }
            }
        }
    }
}