Skip to main content

fprint_backend_libfprint/
device.rs

1// SPDX-FileCopyrightText: 2026 fprintd (pure-Rust) contributors
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5//! [`LibfprintDevice`]: an `fprint-core` [`Device`] backed by a C-libfprint `FpDevice`.
6//!
7//! The `FpDevice` is `!Send` and every libfprint entry point is a blocking `*_sync` call, so the
8//! device lives on a dedicated [worker thread](crate::worker) and this type is only a `Send`
9//! handle to it: a channel of [`Job`]s plus the cached [`DeviceInfo`]. Each operation submits a
10//! job carrying a fresh [`gio::Cancellable`] and awaits the worker's reply; the [`CancelOnDrop`]
11//! guard held across that await fires the cancellable if the future is dropped, cancelling the
12//! `*_sync` on the worker cross-thread (core principle 4). One operation at a time is guaranteed
13//! by `&mut self`, matching libfprint's single-in-flight contract.
14
15use 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/// A fingerprint reader driven through the C libfprint.
35///
36/// Obtained from [`crate::LibfprintBackend`]; call [`Device::open`] before any operation. The
37/// reader itself lives on an internal worker thread — this handle is `Send`, and dropping it
38/// releases the sensor and joins that thread.
39#[derive(Debug)]
40pub struct LibfprintDevice {
41    jobs: Sender<Job>,
42    info: DeviceInfo,
43    /// The sensor's live thermal state, published by the worker after each job and read by
44    /// [`Device::temperature`] without a round-trip to the `!Send` device. Contention is nil — one
45    /// writer at job boundaries, one reader in the getter — so a plain `Mutex` is enough.
46    temperature: Arc<Mutex<Option<Temperature>>>,
47    worker: Option<JoinHandle<()>>,
48}
49
50impl LibfprintDevice {
51    /// Spawn the worker for the device described by `info` and return a handle to it. The worker
52    /// re-finds the device by `info.id` in its own context; `info` is the caller-thread getter
53    /// snapshot, refreshed from the worker on [`Device::open`].
54    ///
55    /// Fails with [`Error::Other`] if the OS refuses the worker thread (resource exhaustion), so a
56    /// device that cannot be given its worker surfaces as a fallible enumeration/open rather than a
57    /// panic out of [`crate::LibfprintBackend`]'s public methods.
58    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    /// Send a job to the worker. Fails only if the worker thread has already stopped.
76    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    /// Build a fresh cancellable and its drop-guard, open a reply channel, and submit the job the
83    /// caller shapes from those. The returned guard must be held across the await so a dropped
84    /// future cancels the in-flight `*_sync`.
85    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    /// [`start`](Self::start) for a streaming operation, adding the progress channel the worker
97    /// pushes reports to.
98    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        // Release the sensor on the worker, then wait for it to finish so the reader is free
118        // before the process moves on. Errors mean the worker already stopped.
119        let _ = self.jobs.send(Job::Shutdown);
120        if let Some(worker) = self.worker.take() {
121            let _ = worker.join();
122        }
123    }
124}
125
126/// Fires its cancellable when dropped. Held across an operation's await so that dropping the
127/// operation future cancels the in-flight `*_sync` on the worker. Fire-and-detach: it never joins
128/// — the worker's `*_sync` returns `Cancelled` and the worker moves on to the next job.
129struct CancelOnDrop(Cancellable);
130
131impl Drop for CancelOnDrop {
132    fn drop(&mut self) {
133        self.0.cancel();
134    }
135}
136
137/// Await a job's reply. A dropped reply sender (the worker was torn down) reads as cancellation.
138async 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
145/// Await a streaming job's reply while draining its progress channel, invoking `on_event` on this
146/// (caller) thread as each report arrives — delivering every report exactly once.
147///
148/// The worker pushes every progress report from inside the `*_sync` call and sends the reply only
149/// after it returns, so once the reply is observable the channel holds all remaining reports. Each
150/// wake drains what has arrived before checking the reply (live progress), and a final drain once
151/// the reply is here catches the last report, which would otherwise race the reply and be lost.
152async 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        // Deliver what has arrived so far. Stops on `Pending` (nothing more yet) or `None` (the
159        // worker dropped the sender when the `*_sync` returned).
160        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                // The reply lands after every report was pushed, so the channel now holds any that
167                // arrived in the gap above; drain them before finishing.
168                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}