fprint_backend_libfprint/
device.rs1use std::future::Future;
16use std::pin::Pin;
17use std::sync::mpsc::Sender;
18use std::sync::{Arc, Mutex};
19use std::task::Poll;
20use std::thread::JoinHandle;
21
22use fprint_core::{
23 Device, DeviceFeature, DeviceInfo, EnrollProgress, Error, FingerStatus, IdentifyOutcome, Print,
24 Result, Temperature, VerifyOutcome,
25};
26use futures_channel::mpsc::{self, UnboundedSender};
27use futures_channel::oneshot;
28use futures_core::Stream;
29use gio::prelude::CancellableExt;
30use gio::Cancellable;
31
32use crate::worker::{self, Job};
33
34#[derive(Debug)]
40pub struct LibfprintDevice {
41 jobs: Sender<Job>,
42 info: DeviceInfo,
43 temperature: Arc<Mutex<Option<Temperature>>>,
47 worker: Option<JoinHandle<()>>,
48}
49
50impl LibfprintDevice {
51 pub(crate) fn spawn(info: DeviceInfo) -> Result<Self> {
59 let (jobs, rx) = std::sync::mpsc::channel();
60 let id = info.id.clone();
61 let temperature = Arc::new(Mutex::new(None));
62 let worker_temperature = Arc::clone(&temperature);
63 let worker = std::thread::Builder::new()
64 .name(format!("libfprint-worker-{}", id.as_str()))
65 .spawn(move || worker::run(id, rx, worker_temperature))
66 .map_err(|e| Error::Other(format!("failed to spawn libfprint worker thread: {e}")))?;
67 Ok(LibfprintDevice {
68 jobs,
69 info,
70 temperature,
71 worker: Some(worker),
72 })
73 }
74
75 fn submit(&self, job: Job) -> Result<()> {
77 self.jobs
78 .send(job)
79 .map_err(|_| Error::Other("libfprint worker thread stopped".into()))
80 }
81
82 fn start<T>(
86 &self,
87 job: impl FnOnce(Cancellable, oneshot::Sender<Result<T>>) -> Job,
88 ) -> Result<(CancelOnDrop, oneshot::Receiver<Result<T>>)> {
89 let cancel = Cancellable::new();
90 let guard = CancelOnDrop(cancel.clone());
91 let (reply_tx, reply_rx) = oneshot::channel();
92 self.submit(job(cancel, reply_tx))?;
93 Ok((guard, reply_rx))
94 }
95
96 fn start_streaming<T, P>(
99 &self,
100 job: impl FnOnce(Cancellable, UnboundedSender<P>, oneshot::Sender<Result<T>>) -> Job,
101 ) -> Result<(
102 CancelOnDrop,
103 oneshot::Receiver<Result<T>>,
104 mpsc::UnboundedReceiver<P>,
105 )> {
106 let cancel = Cancellable::new();
107 let guard = CancelOnDrop(cancel.clone());
108 let (event_tx, event_rx) = mpsc::unbounded();
109 let (reply_tx, reply_rx) = oneshot::channel();
110 self.submit(job(cancel, event_tx, reply_tx))?;
111 Ok((guard, reply_rx, event_rx))
112 }
113}
114
115impl Drop for LibfprintDevice {
116 fn drop(&mut self) {
117 let _ = self.jobs.send(Job::Shutdown);
120 if let Some(worker) = self.worker.take() {
121 let _ = worker.join();
122 }
123 }
124}
125
126struct CancelOnDrop(Cancellable);
130
131impl Drop for CancelOnDrop {
132 fn drop(&mut self) {
133 self.0.cancel();
134 }
135}
136
137async fn await_reply<T>(reply: oneshot::Receiver<Result<T>>) -> Result<T> {
139 match reply.await {
140 Ok(outcome) => outcome,
141 Err(oneshot::Canceled) => Err(Error::Cancelled),
142 }
143}
144
145async fn await_streaming<T, P>(
153 mut reply: oneshot::Receiver<Result<T>>,
154 mut events: mpsc::UnboundedReceiver<P>,
155 mut on_event: impl FnMut(P),
156) -> Result<T> {
157 std::future::poll_fn(move |cx| {
158 while let Poll::Ready(Some(event)) = Pin::new(&mut events).poll_next(cx) {
161 on_event(event);
162 }
163 match Pin::new(&mut reply).poll(cx) {
164 Poll::Pending => Poll::Pending,
165 Poll::Ready(reply) => {
166 while let Poll::Ready(Some(event)) = Pin::new(&mut events).poll_next(cx) {
169 on_event(event);
170 }
171 Poll::Ready(match reply {
172 Ok(outcome) => outcome,
173 Err(oneshot::Canceled) => Err(Error::Cancelled),
174 })
175 }
176 }
177 })
178 .await
179}
180
181impl Device for LibfprintDevice {
182 fn info(&self) -> &DeviceInfo {
183 &self.info
184 }
185
186 fn temperature(&self) -> Option<Temperature> {
187 *self.temperature.lock().unwrap()
188 }
189
190 async fn open(&mut self) -> Result<()> {
191 let (_guard, reply) = self.start(|cancel, reply| Job::Open { cancel, reply })?;
192 self.info = await_reply(reply).await?;
193 Ok(())
194 }
195
196 async fn close(&mut self) -> Result<()> {
197 let (_guard, reply) = self.start(|cancel, reply| Job::Close { cancel, reply })?;
198 await_reply(reply).await
199 }
200
201 async fn enroll<F: FnMut(EnrollProgress)>(
202 &mut self,
203 print: Print,
204 on_progress: F,
205 ) -> Result<Print> {
206 let (_guard, reply, progress) =
207 self.start_streaming(|cancel, progress, reply| Job::Enroll {
208 template: print,
209 cancel,
210 progress,
211 reply,
212 })?;
213 await_streaming(reply, progress, on_progress).await
214 }
215
216 async fn verify_with_status<F: FnMut(FingerStatus)>(
217 &mut self,
218 enrolled: &Print,
219 on_status: F,
220 ) -> Result<VerifyOutcome> {
221 let enrolled = enrolled.clone();
222 let (_guard, reply, status) =
223 self.start_streaming(|cancel, status, reply| Job::Verify {
224 enrolled,
225 cancel,
226 status,
227 reply,
228 })?;
229 await_streaming(reply, status, on_status).await
230 }
231
232 async fn identify_with_status<F: FnMut(FingerStatus)>(
233 &mut self,
234 gallery: &[Print],
235 on_status: F,
236 ) -> Result<IdentifyOutcome> {
237 let gallery = gallery.to_vec();
238 let (_guard, reply, status) =
239 self.start_streaming(|cancel, status, reply| Job::Identify {
240 gallery,
241 cancel,
242 status,
243 reply,
244 })?;
245 await_streaming(reply, status, on_status).await
246 }
247
248 async fn list_prints(&mut self) -> Result<Vec<Print>> {
249 if !self.has_feature(DeviceFeature::STORAGE_LIST) {
250 return Err(Error::NotSupported);
251 }
252 let (_guard, reply) = self.start(|cancel, reply| Job::ListPrints { cancel, reply })?;
253 await_reply(reply).await
254 }
255
256 async fn delete_print(&mut self, stored: &Print) -> Result<()> {
257 if !self.has_feature(DeviceFeature::STORAGE_DELETE) {
258 return Err(Error::NotSupported);
259 }
260 let print = stored.clone();
261 let (_guard, reply) = self.start(|cancel, reply| Job::DeletePrint {
262 print,
263 cancel,
264 reply,
265 })?;
266 await_reply(reply).await
267 }
268
269 async fn clear_storage(&mut self) -> Result<()> {
270 if !self.has_feature(DeviceFeature::STORAGE_CLEAR) {
271 return Err(Error::NotSupported);
272 }
273 let (_guard, reply) = self.start(|cancel, reply| Job::ClearStorage { cancel, reply })?;
274 await_reply(reply).await
275 }
276
277 async fn suspend(&mut self) -> Result<()> {
278 let (_guard, reply) = self.start(|cancel, reply| Job::Suspend { cancel, reply })?;
279 await_reply(reply).await
280 }
281
282 async fn resume(&mut self) -> Result<()> {
283 let (_guard, reply) = self.start(|cancel, reply| Job::Resume { cancel, reply })?;
284 await_reply(reply).await
285 }
286}