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

use crate::{
    components::LoadingButton,
    gettext_f,
    prelude::*,
    session::model::{IdentityVerification, VerificationState},
    toast,
    utils::BoundObjectWeakRef,
    Window,
};

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/content/room_history/verification_info_bar.ui"
    )]
    #[properties(wrapper_type = super::VerificationInfoBar)]
    pub struct VerificationInfoBar {
        #[template_child]
        pub revealer: TemplateChild<gtk::Revealer>,
        #[template_child]
        pub label: TemplateChild<gtk::Label>,
        #[template_child]
        pub accept_btn: TemplateChild<LoadingButton>,
        #[template_child]
        pub cancel_btn: TemplateChild<LoadingButton>,
        /// The identity verification presented by this info bar.
        #[property(get, set = Self::set_verification, explicit_notify)]
        pub verification: BoundObjectWeakRef<IdentityVerification>,
        pub user_handler: RefCell<Option<glib::SignalHandlerId>>,
    }

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

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

            klass.set_css_name("infobar");
            klass.set_accessible_role(gtk::AccessibleRole::Group);

            klass.install_action_async("verification.accept", None, |obj, _, _| async move {
                let Some(window) = obj.root().and_downcast::<Window>() else {
                    return;
                };
                let Some(verification) = obj.verification() else {
                    return;
                };
                let imp = obj.imp();

                if verification.state() == VerificationState::Requested {
                    imp.accept_btn.set_is_loading(true);

                    if verification.accept().await.is_err() {
                        toast!(obj, gettext("Could not accept verification"));
                        imp.accept_btn.set_is_loading(false);
                        return;
                    }
                }

                window
                    .session_view()
                    .select_identity_verification(verification);
                imp.accept_btn.set_is_loading(false);
            });

            klass.install_action_async("verification.decline", None, |obj, _, _| async move {
                let Some(verification) = obj.verification() else {
                    return;
                };
                let imp = obj.imp();

                imp.cancel_btn.set_is_loading(true);

                if verification.cancel().await.is_err() {
                    toast!(obj, gettext("Could not decline verification"));
                }

                imp.cancel_btn.set_is_loading(false);
            });
        }

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

    #[glib::derived_properties]
    impl ObjectImpl for VerificationInfoBar {
        fn dispose(&self) {
            if let Some(verification) = self.verification.obj() {
                if let Some(handler) = self.user_handler.take() {
                    verification.user().disconnect(handler);
                }
            }
        }
    }

    impl WidgetImpl for VerificationInfoBar {}
    impl BinImpl for VerificationInfoBar {}

    impl VerificationInfoBar {
        /// Set the identity verification presented by this info bar.
        fn set_verification(&self, verification: Option<IdentityVerification>) {
            let prev_verification = self.verification.obj();

            if prev_verification == verification {
                return;
            }

            if let Some(verification) = prev_verification {
                if let Some(handler) = self.user_handler.take() {
                    verification.user().disconnect(handler);
                }
            }
            self.verification.disconnect_signals();

            if let Some(verification) = &verification {
                let user_handler = verification.user().connect_display_name_notify(
                    clone!(@weak self as imp => move |_| {
                        imp.update_bar();
                    }),
                );
                self.user_handler.replace(Some(user_handler));

                let state_handler =
                    verification.connect_state_notify(clone!(@weak self as imp => move |_| {
                        imp.update_bar();
                    }));

                self.verification.set(verification, vec![state_handler]);
            }

            self.update_bar();
            self.obj().notify_verification();
        }

        /// Update the bar for the current verification state.
        fn update_bar(&self) {
            let Some(verification) = self.verification.obj().filter(|v| !v.is_finished()) else {
                self.revealer.set_reveal_child(false);
                return;
            };

            if matches!(verification.state(), VerificationState::Requested) {
                self.label.set_markup(&gettext_f(
                    // Translators: Do NOT translate the content between '{' and '}', this is a
                    // variable name.
                    "{user_name} wants to be verified",
                    &[(
                        "user_name",
                        &format!("<b>{}</b>", verification.user().display_name()),
                    )],
                ));
                self.accept_btn.set_label(&gettext("Verify"));
                self.cancel_btn.set_label(&gettext("Decline"));
            } else {
                self.label.set_label(&gettext("Verification in progress"));
                self.accept_btn.set_label(&gettext("Continue"));
                self.cancel_btn.set_label(&gettext("Cancel"));
            }

            self.revealer.set_reveal_child(true);
        }
    }
}

glib::wrapper! {
    /// An info bar presenting an ongoing identity verification.
    pub struct VerificationInfoBar(ObjectSubclass<imp::VerificationInfoBar>)
        @extends gtk::Widget, adw::Bin, @implements gtk::Accessible;
}

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