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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
use std::time::Duration;

use adw::subclass::prelude::*;
use gettextrs::gettext;
use gtk::{
    gdk, gio, glib,
    glib::{clone, closure, closure_local},
    prelude::*,
    CompositeTemplate,
};
use tracing::{debug, error};

use super::{AvatarData, AvatarImage};
use crate::{
    components::{ActionButton, ActionState, AnimatedImagePaintable},
    toast,
    utils::{
        expression,
        media::image::{load_image, ImageDimensions},
        CountedRef,
    },
};

/// The state of the editable avatar.
#[derive(Debug, Default, Hash, Eq, PartialEq, Clone, Copy, glib::Enum)]
#[repr(u32)]
#[enum_type(name = "EditableAvatarState")]
pub enum EditableAvatarState {
    /// Nothing is currently happening.
    #[default]
    Default = 0,
    /// An edit is in progress.
    EditInProgress = 1,
    /// An edit was successful.
    EditSuccessful = 2,
    // A removal is in progress.
    RemovalInProgress = 3,
}

mod imp {
    use std::cell::{Cell, 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/avatar/editable.ui")]
    #[properties(wrapper_type = super::EditableAvatar)]
    pub struct EditableAvatar {
        /// The [`AvatarData`] to display.
        #[property(get, set = Self::set_data, explicit_notify)]
        pub data: RefCell<Option<AvatarData>>,
        /// Whether this avatar is changeable.
        #[property(get, set = Self::set_editable, explicit_notify)]
        pub editable: Cell<bool>,
        /// Whether to prevent the remove button from showing.
        #[property(get, set = Self::set_inhibit_remove, explicit_notify)]
        pub inhibit_remove: Cell<bool>,
        /// The current state of the edit.
        #[property(get, set = Self::set_state, explicit_notify, builder(EditableAvatarState::default()))]
        pub state: Cell<EditableAvatarState>,
        /// The state of the avatar edit.
        pub edit_state: Cell<ActionState>,
        /// Whether the edit button is sensitive.
        pub edit_sensitive: Cell<bool>,
        /// Whether this avatar is removable.
        pub removable: Cell<bool>,
        /// The state of the avatar removal.
        pub remove_state: Cell<ActionState>,
        /// Whether the remove button is sensitive.
        pub remove_sensitive: Cell<bool>,
        /// A temporary paintable to show instead of the avatar.
        #[property(get)]
        pub temp_paintable: RefCell<Option<gdk::Paintable>>,
        temp_paintable_animation_ref: RefCell<Option<CountedRef>>,
        #[template_child]
        pub stack: TemplateChild<gtk::Stack>,
        #[template_child]
        pub temp_avatar: TemplateChild<adw::Avatar>,
        #[template_child]
        pub button_remove: TemplateChild<ActionButton>,
        #[template_child]
        pub button_edit: TemplateChild<ActionButton>,
    }

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

        fn class_init(klass: &mut Self::Class) {
            Self::bind_template(klass);
            klass.set_css_name("editable-avatar");

            klass.install_action_async(
                "editable-avatar.edit-avatar",
                None,
                |obj, _, _| async move {
                    obj.choose_avatar().await;
                },
            );
            klass.install_action("editable-avatar.remove-avatar", None, |obj, _, _| {
                obj.emit_by_name::<()>("remove-avatar", &[]);
            });
        }

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

    #[glib::derived_properties]
    impl ObjectImpl for EditableAvatar {
        fn signals() -> &'static [Signal] {
            static SIGNALS: Lazy<Vec<Signal>> = Lazy::new(|| {
                vec![
                    Signal::builder("edit-avatar")
                        .param_types([gio::File::static_type()])
                        .build(),
                    Signal::builder("remove-avatar").build(),
                ]
            });
            SIGNALS.as_ref()
        }

        fn constructed(&self) {
            self.parent_constructed();

            self.button_remove.set_extra_classes(&["error"]);

            let obj = self.obj();
            let image_present_expr = obj
                .property_expression("data")
                .chain_property::<AvatarData>("image")
                .chain_property::<AvatarImage>("paintable")
                .chain_closure::<bool>(closure!(
                    |_: Option<glib::Object>, image: Option<gdk::Paintable>| { image.is_some() }
                ));

            let editable_expr = obj.property_expression("editable");
            let remove_not_inhibited_expr =
                expression::not(obj.property_expression("inhibit-remove"));
            let can_remove_expr = expression::and(editable_expr, remove_not_inhibited_expr);

            let button_remove_visible = expression::and(can_remove_expr, image_present_expr);
            button_remove_visible.bind(&*self.button_remove, "visible", glib::Object::NONE);

            self.temp_avatar.connect_map(clone!(
                #[weak(rename_to = imp)]
                self,
                move |_| {
                    imp.update_temp_paintable_state();
                }
            ));
            self.temp_avatar.connect_unmap(clone!(
                #[weak(rename_to = imp)]
                self,
                move |_| {
                    imp.update_temp_paintable_state();
                }
            ));
        }
    }

    impl WidgetImpl for EditableAvatar {}
    impl BinImpl for EditableAvatar {}

    impl EditableAvatar {
        /// Set the [`AvatarData`] to display.
        fn set_data(&self, data: Option<AvatarData>) {
            if *self.data.borrow() == data {
                return;
            }

            self.data.replace(data);
            self.obj().notify_data();
        }

        /// Set whether this avatar is editable.
        fn set_editable(&self, editable: bool) {
            if self.editable.get() == editable {
                return;
            }

            self.editable.set(editable);
            self.obj().notify_editable();
        }

        /// Set whether to prevent the remove button from showing..
        fn set_inhibit_remove(&self, inhibit: bool) {
            if self.inhibit_remove.get() == inhibit {
                return;
            }

            self.inhibit_remove.set(inhibit);
            self.obj().notify_inhibit_remove();
        }

        /// Set the state of the edit.
        fn set_state(&self, state: EditableAvatarState) {
            if self.state.get() == state {
                return;
            }
            let obj = self.obj();

            match state {
                EditableAvatarState::Default => {
                    self.show_temp_paintable(false);
                    obj.set_edit_state(ActionState::Default);
                    obj.set_edit_sensitive(true);
                    obj.set_remove_state(ActionState::Default);
                    obj.set_remove_sensitive(true);

                    self.set_temp_paintable(None);
                }
                EditableAvatarState::EditInProgress => {
                    self.show_temp_paintable(true);
                    obj.set_edit_state(ActionState::Loading);
                    obj.set_edit_sensitive(true);
                    obj.set_remove_state(ActionState::Default);
                    obj.set_remove_sensitive(false);
                }
                EditableAvatarState::EditSuccessful => {
                    self.show_temp_paintable(false);
                    obj.set_edit_sensitive(true);
                    obj.set_remove_state(ActionState::Default);
                    obj.set_remove_sensitive(true);

                    self.set_temp_paintable(None);

                    // Animation for success.
                    obj.set_edit_state(ActionState::Success);
                    glib::timeout_add_local_once(
                        Duration::from_secs(2),
                        clone!(
                            #[weak]
                            obj,
                            move || {
                                obj.set_state(EditableAvatarState::Default);
                            }
                        ),
                    );
                }
                EditableAvatarState::RemovalInProgress => {
                    self.show_temp_paintable(true);
                    obj.set_edit_state(ActionState::Default);
                    obj.set_edit_sensitive(false);
                    obj.set_remove_state(ActionState::Loading);
                    obj.set_remove_sensitive(true);
                }
            }

            self.state.set(state);
            obj.notify_state();
        }

        /// The dimensions of the avatar in this widget.
        fn avatar_dimensions(&self) -> ImageDimensions {
            let scale_factor = self.obj().scale_factor();
            let avatar_size = self.temp_avatar.size();
            let size = (avatar_size * scale_factor) as u32;

            ImageDimensions {
                width: size,
                height: size,
            }
        }

        /// Load the temporary paintable from the given file.
        pub(super) async fn set_temp_paintable_from_file(&self, file: gio::File) {
            let paintable = load_image(file, Some(self.avatar_dimensions())).await.ok();
            self.set_temp_paintable(paintable);
        }

        /// Set the temporary paintable.
        fn set_temp_paintable(&self, paintable: Option<gdk::Paintable>) {
            if *self.temp_paintable.borrow() == paintable {
                return;
            }

            self.temp_paintable.replace(paintable);

            self.update_temp_paintable_state();
            self.obj().notify_temp_paintable();
        }

        /// Show the temporary paintable instead of the current avatar.
        fn show_temp_paintable(&self, show: bool) {
            let stack = &self.stack;
            if show {
                stack.set_visible_child_name("temp");
            } else {
                stack.set_visible_child_name("default");
            }
        }

        /// Update the state of the temp paintable.
        fn update_temp_paintable_state(&self) {
            self.temp_paintable_animation_ref.take();

            let Some(paintable) = self
                .temp_paintable
                .borrow()
                .clone()
                .and_downcast::<AnimatedImagePaintable>()
            else {
                return;
            };

            if self.temp_avatar.is_mapped() {
                self.temp_paintable_animation_ref
                    .replace(Some(paintable.animation_ref()));
            }
        }
    }
}

glib::wrapper! {
    /// An `Avatar` that can be edited.
    pub struct EditableAvatar(ObjectSubclass<imp::EditableAvatar>)
        @extends gtk::Widget, adw::Bin, @implements gtk::Accessible;
}

impl EditableAvatar {
    pub fn new() -> Self {
        glib::Object::new()
    }

    /// Reset the state of the avatar.
    pub fn reset(&self) {
        self.set_state(EditableAvatarState::Default);
    }

    /// Show that an edit is in progress.
    pub fn edit_in_progress(&self) {
        self.set_state(EditableAvatarState::EditInProgress);
    }

    /// Show that a removal is in progress.
    pub fn removal_in_progress(&self) {
        self.set_state(EditableAvatarState::RemovalInProgress);
    }

    /// Show that the current ongoing action was successful.
    ///
    /// This is has no effect if no action is ongoing.
    pub fn success(&self) {
        if self.edit_state() == ActionState::Loading {
            self.set_state(EditableAvatarState::EditSuccessful);
        } else if self.remove_state() == ActionState::Loading {
            // The remove button is hidden as soon as the avatar is gone so we
            // don't need a state when it succeeds.
            self.set_state(EditableAvatarState::Default);
        }
    }

    /// The state of the avatar edit.
    fn edit_state(&self) -> ActionState {
        self.imp().edit_state.get()
    }

    /// Set the state of the avatar edit.
    fn set_edit_state(&self, state: ActionState) {
        if self.edit_state() == state {
            return;
        }

        self.imp().edit_state.set(state);
    }

    /// Whether the edit button is sensitive.
    fn edit_sensitive(&self) -> bool {
        self.imp().edit_sensitive.get()
    }

    /// Set whether the edit button is sensitive.
    fn set_edit_sensitive(&self, sensitive: bool) {
        if self.edit_sensitive() == sensitive {
            return;
        }

        self.imp().edit_sensitive.set(sensitive);
    }

    /// The state of the avatar removal.
    fn remove_state(&self) -> ActionState {
        self.imp().remove_state.get()
    }

    /// Set the state of the avatar removal.
    fn set_remove_state(&self, state: ActionState) {
        if self.remove_state() == state {
            return;
        }

        self.imp().remove_state.set(state);
    }

    /// Whether the remove button is sensitive.
    fn remove_sensitive(&self) -> bool {
        self.imp().remove_sensitive.get()
    }

    /// Set whether the remove button is sensitive.
    fn set_remove_sensitive(&self, sensitive: bool) {
        if self.remove_sensitive() == sensitive {
            return;
        }

        self.imp().remove_sensitive.set(sensitive);
    }

    async fn choose_avatar(&self) {
        let filters = gio::ListStore::new::<gtk::FileFilter>();

        let image_filter = gtk::FileFilter::new();
        image_filter.set_name(Some(&gettext("Images")));
        image_filter.add_mime_type("image/*");
        filters.append(&image_filter);

        let dialog = gtk::FileDialog::builder()
            .title(gettext("Choose Avatar"))
            .modal(true)
            .accept_label(gettext("Choose"))
            .filters(&filters)
            .build();

        let file = match dialog
            .open_future(self.root().and_downcast_ref::<gtk::Window>())
            .await
        {
            Ok(file) => file,
            Err(error) => {
                if error.matches(gtk::DialogError::Dismissed) {
                    debug!("File dialog dismissed by user");
                } else {
                    error!("Could not open avatar file: {error:?}");
                    toast!(self, gettext("Could not open avatar file"));
                }
                return;
            }
        };

        if let Some(content_type) = file
            .query_info_future(
                gio::FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE,
                gio::FileQueryInfoFlags::NONE,
                glib::Priority::LOW,
            )
            .await
            .ok()
            .and_then(|info| info.content_type())
        {
            if gio::content_type_is_a(&content_type, "image/*") {
                self.imp().set_temp_paintable_from_file(file.clone()).await;
                self.emit_by_name::<()>("edit-avatar", &[&file]);
            } else {
                error!("The chosen file is not an image");
                toast!(self, gettext("The chosen file is not an image"));
            }
        } else {
            error!("Could not get the content type of the file");
            toast!(
                self,
                gettext("Could not determine the type of the chosen file")
            );
        }
    }

    pub fn connect_edit_avatar<F: Fn(&Self, gio::File) + 'static>(
        &self,
        f: F,
    ) -> glib::SignalHandlerId {
        self.connect_closure(
            "edit-avatar",
            true,
            closure_local!(|obj: Self, file: gio::File| {
                f(&obj, file);
            }),
        )
    }

    pub fn connect_remove_avatar<F: Fn(&Self) + 'static>(&self, f: F) -> glib::SignalHandlerId {
        self.connect_closure(
            "remove-avatar",
            true,
            closure_local!(|obj: Self| {
                f(&obj);
            }),
        )
    }
}