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
use std::cell::OnceCell;

use adw::prelude::*;
use gettextrs::gettext;
use gtk::{
    gio,
    glib::{self, clone},
    subclass::prelude::*,
};

use crate::{
    application::Application,
    config,
    models::{keyring, Account, OTPUri, ProvidersModel, SETTINGS},
    utils::spawn_tokio_blocking,
    widgets::{
        accounts::AccountDetailsPage,
        providers::{ProvidersList, ProvidersListView},
        AccountAddDialog, ErrorRevealer,
    },
};

pub enum View {
    Login,
    Accounts,
    Account(Account),
}

mod imp {
    use adw::subclass::prelude::*;
    use glib::subclass;

    use super::*;

    #[derive(Default, gtk::CompositeTemplate, glib::Properties)]
    #[template(resource = "/com/belmoussaoui/Authenticator/window.ui")]
    #[properties(wrapper_type = super::Window)]
    pub struct Window {
        #[property(get, set, construct_only)]
        pub model: OnceCell<ProvidersModel>,
        #[template_child]
        pub main_stack: TemplateChild<gtk::Stack>,
        #[template_child]
        pub providers: TemplateChild<ProvidersList>,
        #[template_child]
        pub account_details: TemplateChild<AccountDetailsPage>,
        #[template_child]
        pub search_entry: TemplateChild<gtk::SearchEntry>,
        #[template_child]
        pub navigation_view: TemplateChild<adw::NavigationView>,
        #[template_child]
        pub error_revealer: TemplateChild<ErrorRevealer>,
        #[template_child]
        pub search_btn: TemplateChild<gtk::ToggleButton>,
        #[template_child]
        pub password_entry: TemplateChild<gtk::PasswordEntry>,
        #[template_child]
        pub locked_status_page: TemplateChild<adw::StatusPage>,
        #[template_child]
        pub accounts_stack: TemplateChild<gtk::Stack>,
        #[template_child]
        pub empty_status_page: TemplateChild<adw::StatusPage>,
        #[template_child]
        pub title_stack: TemplateChild<gtk::Stack>,
        #[template_child]
        pub unlock_button: TemplateChild<gtk::Button>,
        #[template_child]
        pub toast_overlay: TemplateChild<adw::ToastOverlay>,
    }

    #[glib::object_subclass]
    impl ObjectSubclass for Window {
        const NAME: &'static str = "Window";
        type Type = super::Window;
        type ParentType = adw::ApplicationWindow;
        type Interfaces = (gio::Initable,);

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

            klass.install_action("win.search", None, |win, _, _| {
                let search_btn = &win.imp().search_btn;
                search_btn.set_active(!search_btn.is_active());
            });

            klass.install_action("win.add_account", None, |win, _, _| {
                win.open_add_account(None);
            });

            klass.install_action("win.back", None, |win, _, _| {
                // Always return back to accounts list
                win.set_view(View::Accounts);
            });

            klass.install_action("win.unlock", None, |win, _, _| {
                let imp = win.imp();
                let app = win.app();
                let password = imp.password_entry.text();
                let is_current_password = spawn_tokio_blocking(async move {
                    keyring::is_current_password(&password)
                        .await
                        .unwrap_or_else(|err| {
                            tracing::debug!("Could not verify password: {:?}", err);
                            false
                        })
                });
                if is_current_password {
                    imp.password_entry.set_text("");
                    app.set_is_locked(false);
                    app.restart_lock_timeout();
                    win.set_view(View::Accounts);
                    win.model().load();
                } else {
                    imp.error_revealer.popup(&gettext("Wrong Password"));
                }
            });
        }

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

    #[glib::derived_properties]
    impl ObjectImpl for Window {
        fn constructed(&self) {
            self.parent_constructed();
            let win = self.obj();
            self.providers.set_model(win.model());

            self.providers
                .model()
                .connect_items_changed(clone!(@weak win => move |_, _,_,_| {
                // We do a check on set_view to ensure we always use the right page
                if !win.app().is_locked() {
                    win.set_view(View::Accounts);
                }
                }));

            win.set_icon_name(Some(config::APP_ID));
            self.empty_status_page.set_icon_name(Some(config::APP_ID));
            self.locked_status_page.set_icon_name(Some(config::APP_ID));

            // load latest window state
            let width = SETTINGS.window_width();
            let height = SETTINGS.window_height();

            if width > -1 && height > -1 {
                win.set_default_size(width, height);
            }

            let is_maximized = SETTINGS.is_maximized();
            if is_maximized {
                win.maximize();
            }
            self.account_details.set_providers_model(win.model());

            if config::PROFILE == "Devel" {
                win.add_css_class("devel");
            }
            win.set_view(View::Accounts);
        }
    }
    impl WidgetImpl for Window {}
    impl WindowImpl for Window {
        fn enable_debugging(&self, toggle: bool) -> bool {
            if config::PROFILE != "Devel" {
                tracing::warn!("Inspector is disabled for non development builds");
                false
            } else {
                self.parent_enable_debugging(toggle)
            }
        }

        fn close_request(&self) -> glib::Propagation {
            if let Err(err) = self.obj().save_window_state() {
                tracing::warn!("Failed to save window state {:#?}", err);
            }
            self.parent_close_request()
        }
    }

    impl ApplicationWindowImpl for Window {}
    impl AdwApplicationWindowImpl for Window {}
    impl InitableImpl for Window {
        // As the application property on gtk::ApplicationWindow is not marked
        // as CONSTRUCT, we need to implement Initable so we can run code once all the
        // object properties are set.
        fn init(&self, _cancellable: Option<&gio::Cancellable>) -> Result<(), glib::Error> {
            let win = self.obj();
            let app = win.app();
            win.action_set_enabled("win.add_account", !app.is_locked());
            app.connect_is_locked_notify(clone!(@weak win => move |app| {
                let is_locked = app.is_locked();
                win.action_set_enabled("win.add_account", !is_locked);
                if is_locked{
                    win.set_view(View::Login);
                } else {
                    win.set_view(View::Accounts);
                };
            }));
            if app.is_locked() {
                win.set_view(View::Login);
            }
            Ok(())
        }
    }
}

glib::wrapper! {
    pub struct Window(ObjectSubclass<imp::Window>)
        @extends gtk::Widget, gtk::Window, gtk::ApplicationWindow, adw::ApplicationWindow,
        @implements gio::Initable, gio::ActionMap, gio::ActionGroup, gtk::Native, gtk::Root;
}

#[gtk::template_callbacks]
impl Window {
    pub fn new(model: &ProvidersModel, app: &Application) -> Self {
        gio::Initable::builder()
            .property("application", app)
            .property("model", model)
            .build(gio::Cancellable::NONE)
            .unwrap()
    }

    pub fn set_view(&self, view: View) {
        let imp = self.imp();
        match view {
            View::Login => {
                self.set_default_widget(Some(&*imp.unlock_button));
                imp.main_stack.set_visible_child_name("login");
                imp.search_entry.set_key_capture_widget(gtk::Widget::NONE);
                imp.password_entry.grab_focus();
            }
            View::Accounts => {
                self.set_default_widget(gtk::Widget::NONE);
                imp.main_stack.set_visible_child_name("unlocked");
                imp.navigation_view.pop();
                if imp.providers.model().n_items() == 0 {
                    if self.model().has_providers() {
                        // We do have at least one provider
                        // the 0 items comes from the search filter, so let's show an empty search
                        // page instead
                        imp.providers.set_view(ProvidersListView::NoSearchResults);
                    } else {
                        imp.accounts_stack.set_visible_child_name("empty");
                        imp.search_entry.set_key_capture_widget(gtk::Widget::NONE);
                    }
                } else {
                    imp.providers.set_view(ProvidersListView::List);
                    imp.accounts_stack.set_visible_child_name("accounts");
                    imp.search_entry.set_key_capture_widget(Some(self));
                }
            }
            View::Account(account) => {
                self.set_default_widget(gtk::Widget::NONE);
                imp.search_entry.set_key_capture_widget(gtk::Widget::NONE);
                imp.main_stack.set_visible_child_name("unlocked");
                imp.navigation_view.push_by_tag("account");
                imp.account_details.set_account(&account);
            }
        }
    }

    pub fn add_toast(&self, toast: adw::Toast) {
        self.imp().toast_overlay.add_toast(toast);
    }

    pub fn open_add_account(&self, otp_uri: Option<&OTPUri>) {
        let model = self.model();
        let dialog = AccountAddDialog::new(&model);
        if let Some(uri) = otp_uri {
            dialog.set_from_otp_uri(uri);
        }

        dialog.connect_added(clone!(@weak self as win => move |_| {
            win.providers().refilter();
        }));
        dialog.present(self);
    }

    pub fn providers(&self) -> ProvidersList {
        self.imp().providers.clone()
    }

    fn app(&self) -> Application {
        self.application().and_downcast::<Application>().unwrap()
    }

    fn save_window_state(&self) -> anyhow::Result<()> {
        let size = self.default_size();
        SETTINGS.set_window_width(size.0)?;
        SETTINGS.set_window_height(size.1)?;
        SETTINGS.set_is_maximized(self.is_maximized())?;
        Ok(())
    }

    #[template_callback]
    fn on_password_entry_activate(&self) {
        WidgetExt::activate_action(self, "win.unlock", None).unwrap();
    }

    #[template_callback]
    fn on_account_removed(&self, account: Account) {
        let provider = account.provider();
        account.delete().unwrap();
        provider.remove_account(&account);
        self.providers().refilter();
        self.set_view(View::Accounts);
    }

    #[template_callback]
    fn on_provider_changed(&self) {
        self.providers().refilter();
    }

    #[template_callback]
    fn on_account_shared(&self, account: Account) {
        self.set_view(View::Account(account));
    }

    #[template_callback]
    fn on_gesture_click_pressed(&self) {
        self.app().restart_lock_timeout();
    }

    #[template_callback]
    fn on_key_pressed(&self) -> glib::Propagation {
        self.app().restart_lock_timeout();
        glib::Propagation::Proceed
    }

    #[template_callback]
    fn on_search_changed(&self, entry: &gtk::SearchEntry) {
        let text = entry.text().to_string();
        self.imp().providers.search(text);
    }

    #[template_callback]
    fn on_search_started(&self, _entry: &gtk::SearchEntry) {
        self.imp().search_btn.set_active(true);
    }

    #[template_callback]
    fn on_search_stopped(&self, _entry: &gtk::SearchEntry) {
        self.imp().search_btn.set_active(false);
    }

    #[template_callback]
    fn on_search_btn_toggled(&self, btn: &gtk::ToggleButton) {
        let imp = self.imp();
        if btn.is_active() {
            imp.title_stack.set_visible_child_name("search");
            imp.search_entry.grab_focus();
        } else {
            imp.search_entry.set_text("");
            imp.title_stack.set_visible_child_name("title");
        }
    }
}