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
use std::{cell::Cell, rc::Rc};

use adw::subclass::{navigation_page::*, prelude::*};
use anyhow::Result;
use gtk::{
    gio,
    glib::{self, clone},
    prelude::*,
};
use tokio::{
    select,
    sync::oneshot,
    time::{sleep, Duration},
};

use crate::{utils::spawn_tokio, widgets::Camera};

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

    use super::*;

    #[derive(Default, gtk::CompositeTemplate, glib::Properties)]
    #[template(resource = "/com/belmoussaoui/Authenticator/preferences_camera_page.ui")]
    #[properties(wrapper_type = super::CameraPage)]
    pub struct CameraPage {
        #[property(get, set, construct_only)]
        pub actions: OnceCell<gio::SimpleActionGroup>,
        #[template_child]
        pub camera: TemplateChild<Camera>,
    }

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

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

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

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

    impl WidgetImpl for CameraPage {}
    impl NavigationPageImpl for CameraPage {}
}

glib::wrapper! {
    pub struct CameraPage(ObjectSubclass<imp::CameraPage>)
        @extends gtk::Widget, adw::NavigationPage;
}

#[gtk::template_callbacks]
impl CameraPage {
    pub fn new(actions: &gio::SimpleActionGroup) -> Self {
        glib::Object::builder().property("actions", actions).build()
    }

    pub async fn scan_from_camera(&self) -> Result<String> {
        let imp = self.imp();

        let (tx, rx) = oneshot::channel();

        // This is required because for whatever reason `glib::clone!` wouldn't let it
        // be moved into the closure.
        let tx = Rc::new(Cell::new(Some(tx)));

        // This is to make it safe to access `src` inside of the connected closure to
        // disconnect it after being called.
        let src = Rc::new(Cell::new(None));

        src.set(Some(imp.camera.connect_code_detected(clone!(
            @weak self as camera_page, @strong src, @strong tx
            => move |_, code| {
                match tx.take().unwrap().send(code) {
                    Ok(()) => (),
                    Err(_) => {
                        tracing::error!(concat!(
                            "CameraPage::scan_from_camera failed to send the resulting QR ",
                            "code to the recipient because the recipient already received a ",
                            "QR code or was dropped. This should never occur.",
                        ));
                    }
                }
                camera_page.imp().camera.disconnect(src.take().unwrap());
            }
        ))));

        drop(tx);
        drop(src);

        imp.camera.scan_from_camera().await;

        match rx.await {
            Ok(code) => Ok(code),
            Err(error) => {
                tracing::error!(concat!(
                    "CameraPage::scan_from_camera failed to receive the resulting QR code from ",
                    "the sender because the sender was dropped without sending a QR code. This ",
                    "should never occur."
                ));
                Err(error.into())
            }
        }
    }

    pub async fn scan_from_screenshot(&self) -> Result<String> {
        let imp = self.imp();

        let (tx, rx) = oneshot::channel();

        // This is required because for whatever reason `glib::clone!` wouldn't let it
        // be moved into the closure.
        let tx = Rc::new(Cell::new(Some(tx)));

        // This is to make it safe to access `src` inside of the connected closure to
        // disconnect it after being called.
        let src = Rc::new(Cell::new(None));

        src.set(Some(imp.camera.connect_code_detected(clone!(
            @weak self as camera_page, @strong src, @strong tx
            => move |_, code| {
                match tx.take().unwrap().send(code) {
                    Ok(()) => (),
                    Err(_) => {
                        tracing::error!(concat!(
                            "CameraPage::scan_from_screenshot failed to send the resulting QR ",
                            "code to the recipient because the recipient already received a ",
                            "QR code or was dropped. This should never occur.",
                        ));
                    }
                }
                camera_page.imp().camera.disconnect(src.take().unwrap());
            }
        ))));

        drop(tx);

        select! {
            biased;
            result = rx => result.map_err(|error| {
                tracing::error!(concat!(
                    "CameraPage::scan_from_screenshot failed to receive the resulting QR code ",
                    "from the sender because the sender was dropped without sending a QR ",
                    "code. This should never occur.",
                ));

                error.into()
            }),
            result = async move {
                imp.camera.scan_from_screenshot().await?;

                // Give the GLib event loop a whole 2.5 seconds to dispatch the "code-detected"
                // action before we assume that its not going to be dispatched at all.
                spawn_tokio(async { sleep(Duration::from_millis(2500)).await; }).await;

                // Disconnect the signal handler.
                imp.camera.disconnect(src.take().unwrap());

                anyhow::bail!(concat!(
                    "CameraPage::scan_from_screenshot failed to receive the resulting QR code in ",
                    "a reasonable amount of time."
                ));
            } => result.map_err(From::from),
        }
    }

    #[template_callback]
    fn on_camera_close(&self) {
        self.actions().activate_action("close_page", None);
    }
}