fractal/components/camera/linux/
viewfinder.rs

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 ashpd::desktop::camera;
use gtk::{
    glib,
    glib::{clone, subclass::prelude::*},
    prelude::*,
    subclass::prelude::*,
};
use matrix_sdk::encryption::verification::QrVerificationData;
use tokio::task::AbortHandle;
use tracing::{debug, error};

use crate::{
    components::camera::{
        CameraViewfinder, CameraViewfinderExt, CameraViewfinderImpl, CameraViewfinderState,
    },
    spawn_tokio,
};

impl From<aperture::ViewfinderState> for CameraViewfinderState {
    fn from(value: aperture::ViewfinderState) -> Self {
        match value {
            aperture::ViewfinderState::Loading => Self::Loading,
            aperture::ViewfinderState::Ready => Self::Ready,
            aperture::ViewfinderState::NoCameras => Self::NoCameras,
            aperture::ViewfinderState::Error => Self::Error,
        }
    }
}

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

    use matrix_sdk::encryption::verification::DecodingError;

    use super::*;

    #[derive(Debug)]
    pub struct LinuxCameraViewfinder {
        /// The child viewfinder.
        child: aperture::Viewfinder,
        /// The device provider for the viewfinder.
        provider: aperture::DeviceProvider,
        abort_handle: RefCell<Option<AbortHandle>>,
    }

    impl Default for LinuxCameraViewfinder {
        fn default() -> Self {
            Self {
                child: Default::default(),
                provider: aperture::DeviceProvider::instance().clone(),
                abort_handle: Default::default(),
            }
        }
    }

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

        fn class_init(klass: &mut Self::Class) {
            klass.set_layout_manager_type::<gtk::BinLayout>();
        }
    }

    impl ObjectImpl for LinuxCameraViewfinder {
        fn constructed(&self) {
            self.parent_constructed();
            let obj = self.obj();

            self.child.set_parent(&*obj);
            self.child.set_detect_codes(true);

            self.child.connect_state_notify(glib::clone!(
                #[weak(rename_to = imp)]
                self,
                move |_| {
                    imp.update_state();
                }
            ));
            self.update_state();

            self.child.connect_code_detected(clone!(
                #[weak]
                obj,
                move |_, code| {
                    match QrVerificationData::from_bytes(&code) {
                        Ok(data) => obj.emit_qrcode_detected(data),
                        Err(error) => {
                            let code = String::from_utf8_lossy(&code);

                            if matches!(error, DecodingError::Header) {
                                debug!("Detected non-Matrix QR Code: {code}");
                            } else {
                                error!(
                                    "Could not decode Matrix verification QR code {code}: {error}"
                                );
                            }
                        }
                    }
                }
            ));
        }

        fn dispose(&self) {
            self.child.stop_stream();
            self.child.unparent();

            if let Some(abort_handle) = self.abort_handle.take() {
                abort_handle.abort();
            }
        }
    }

    impl WidgetImpl for LinuxCameraViewfinder {}
    impl CameraViewfinderImpl for LinuxCameraViewfinder {}

    impl LinuxCameraViewfinder {
        /// Initialize the viewfinder.
        pub(super) async fn init(&self) -> Result<(), ()> {
            if self.provider.started() {
                return Ok(());
            }

            let handle = spawn_tokio!(camera::request());
            self.set_abort_handle(Some(handle.abort_handle()));

            let Ok(request_result) = handle.await else {
                debug!("Camera request was aborted");
                self.set_abort_handle(None);
                return Err(());
            };

            self.set_abort_handle(None);

            let fd = match request_result {
                Ok(Some(fd)) => fd,
                Ok(None) => {
                    error!("Could not access camera: no camera present");
                    return Err(());
                }
                Err(error) => {
                    error!("Could not access camera: {error}");
                    return Err(());
                }
            };

            if let Err(error) = self.provider.set_fd(fd) {
                error!("Could not access camera: {error}");
                return Err(());
            }

            if let Err(error) = self.provider.start_with_default(|camera| {
                matches!(camera.location(), aperture::CameraLocation::Back)
            }) {
                error!("Could not access camera: {error}");
                return Err(());
            }

            Ok(())
        }

        /// Update the current state.
        fn update_state(&self) {
            self.obj().set_state(self.child.state().into());
        }

        /// Set the current abort handle.
        fn set_abort_handle(&self, abort_handle: Option<AbortHandle>) {
            self.abort_handle.replace(abort_handle);
        }
    }
}

glib::wrapper! {
    /// A camera viewfinder widget for Linux.
    pub struct LinuxCameraViewfinder(ObjectSubclass<imp::LinuxCameraViewfinder>)
        @extends gtk::Widget, CameraViewfinder;
}

impl LinuxCameraViewfinder {
    pub(super) async fn new() -> Option<Self> {
        let obj = glib::Object::new::<Self>();

        obj.imp().init().await.ok()?;

        Some(obj)
    }
}