Skip to main content

fprint_backend_libfprint/
convert.rs

1// SPDX-FileCopyrightText: 2026 fprintd (pure-Rust) contributors
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5//! Edge translation between libfprint's glib vocabulary and the pure `fprint-core` model.
6//!
7//! Everything wire/quirk-specific about the C library — the `GQuark` error domains, the
8//! `FpDeviceError`/`FpDeviceRetry` code tables, the `FpFinger`/`FpScanType`/`FpDeviceFeature`
9//! enum discriminants — is confined here so it never leaks into the domain model
10//! (`ARCHITECTURE.md` principle 3). These are interoperability *facts* (enum values, quark
11//! strings), not copyrightable expression, so documenting and matching them is clean. The raw
12//! object access lives in [`crate::ffi`]; this module reads the primitive values it returns.
13
14use fprint_core::{
15    DeviceFeature, DeviceId, DeviceInfo, DriverId, Error, Finger, FingerStatus, RetryReason,
16    ScanType, Temperature,
17};
18use fprint_fp3::Fp3Error;
19use glib::error::ErrorDomain;
20use glib::Quark;
21
22use crate::ffi::FpDevice;
23
24// --- libfprint error domains, expressed as glib `ErrorDomain`s ------------------------
25//
26// libfprint ships `FpDeviceError`/`FpDeviceRetry` as plain C enums under two `GQuark` domains,
27// not as typed glib error domains, so these zero-cost markers stand in.
28// `glib::Error::kind::<T>()` returns the code iff the error's `GQuark` domain equals
29// `T::domain()`, giving safe, allocation-free classification with no raw-pointer access to the
30// `GError`. The quark strings come from libfprint's `G_DEFINE_QUARK (fp - device - error - quark,
31// …)` / `(fp - device - retry - quark, …)`.
32
33#[derive(Clone, Copy)]
34struct FpDeviceErrorCode(i32);
35
36impl ErrorDomain for FpDeviceErrorCode {
37    fn domain() -> Quark {
38        Quark::from_str("fp-device-error-quark")
39    }
40    fn code(self) -> i32 {
41        self.0
42    }
43    fn from(code: i32) -> Option<Self> {
44        Some(FpDeviceErrorCode(code))
45    }
46}
47
48#[derive(Clone, Copy)]
49struct FpDeviceRetryCode(i32);
50
51impl ErrorDomain for FpDeviceRetryCode {
52    fn domain() -> Quark {
53        Quark::from_str("fp-device-retry-quark")
54    }
55    fn code(self) -> i32 {
56        self.0
57    }
58    fn from(code: i32) -> Option<Self> {
59        Some(FpDeviceRetryCode(code))
60    }
61}
62
63// `FpDeviceError` enum values (fp-device.h). Named locally so the mapping reads as a spec.
64// (GENERAL = 0 and TOO_HOT = 0x101 are intentionally absent: they fall through to `Other`.)
65const FP_ERR_NOT_SUPPORTED: i32 = 1;
66const FP_ERR_NOT_OPEN: i32 = 2;
67const FP_ERR_ALREADY_OPEN: i32 = 3;
68const FP_ERR_BUSY: i32 = 4;
69const FP_ERR_PROTO: i32 = 5;
70const FP_ERR_DATA_INVALID: i32 = 6;
71const FP_ERR_DATA_NOT_FOUND: i32 = 7;
72const FP_ERR_DATA_FULL: i32 = 8;
73const FP_ERR_DATA_DUPLICATE: i32 = 9;
74const FP_ERR_REMOVED: i32 = 0x100;
75
76// `FpDeviceRetry` enum values (fp-device.h). (GENERAL = 0 falls through to the general reason.)
77const FP_RETRY_TOO_SHORT: i32 = 1;
78const FP_RETRY_CENTER_FINGER: i32 = 2;
79const FP_RETRY_REMOVE_FINGER: i32 = 3;
80const FP_RETRY_TOO_FAST: i32 = 4;
81
82/// Classify a `glib::Error` from any libfprint sync call into the core [`Error`] vocabulary.
83pub(crate) fn from_gerror(err: glib::Error) -> Error {
84    if let Some(retry) = err.kind::<FpDeviceRetryCode>() {
85        return Error::RetryScan(map_retry(retry.0));
86    }
87    if let Some(dev_err) = err.kind::<FpDeviceErrorCode>() {
88        return map_device_error(dev_err.0, &err);
89    }
90    if err.matches(gio::IOErrorEnum::Cancelled) {
91        return Error::Cancelled;
92    }
93    Error::Other(err.message().to_owned())
94}
95
96fn map_device_error(code: i32, err: &glib::Error) -> Error {
97    match code {
98        FP_ERR_NOT_SUPPORTED => Error::NotSupported,
99        FP_ERR_NOT_OPEN | FP_ERR_ALREADY_OPEN => Error::ProtoState,
100        FP_ERR_BUSY => Error::Busy,
101        FP_ERR_PROTO | FP_ERR_DATA_INVALID => Error::Protocol(err.message().to_owned()),
102        FP_ERR_DATA_NOT_FOUND => Error::DataNotFound,
103        FP_ERR_DATA_FULL => Error::DataFull,
104        FP_ERR_DATA_DUPLICATE => Error::DataDuplicate,
105        FP_ERR_REMOVED => Error::NotFound,
106        // FP_ERR_GENERAL, FP_ERR_TOO_HOT and any future code carry the human-readable message.
107        _ => Error::Other(err.message().to_owned()),
108    }
109}
110
111fn map_retry(code: i32) -> RetryReason {
112    match code {
113        FP_RETRY_TOO_SHORT => RetryReason::TooShort,
114        FP_RETRY_CENTER_FINGER => RetryReason::NotCentered,
115        FP_RETRY_REMOVE_FINGER => RetryReason::RemoveAndRetry,
116        FP_RETRY_TOO_FAST => RetryReason::TooFast,
117        // FP_RETRY_GENERAL and anything unrecognised degrade to the general retry reason.
118        _ => RetryReason::General,
119    }
120}
121
122/// A retry reason for a failed enroll capture, or `None` if `err` is not a retry-class error.
123pub(crate) fn gerror_retry(err: &glib::Error) -> Option<RetryReason> {
124    err.kind::<FpDeviceRetryCode>().map(|c| map_retry(c.0))
125}
126
127/// Map a failure of the FP3 codec (round-tripping templates through the shim) to [`Error`].
128pub(crate) fn from_fp3(err: Fp3Error) -> Error {
129    Error::Protocol(err.to_string())
130}
131
132// --- Enum translation -----------------------------------------------------------------
133
134// Note: the reverse (`FpFinger` → `Finger`) is deliberately absent. A decoded print's finger
135// comes from the FP3 blob via `fprint-fp3` (the single source of truth, per the D1 decision in
136// `print.rs`), so no separate live-getter translation is needed.
137
138/// core [`Finger`] → libfprint's raw `FpFinger` value.
139pub(crate) fn finger_to_fp(f: Finger) -> libfprint_sys::FpFinger {
140    match f {
141        Finger::Unknown => libfprint_sys::FpFinger_FP_FINGER_UNKNOWN,
142        Finger::LeftThumb => libfprint_sys::FpFinger_FP_FINGER_LEFT_THUMB,
143        Finger::LeftIndex => libfprint_sys::FpFinger_FP_FINGER_LEFT_INDEX,
144        Finger::LeftMiddle => libfprint_sys::FpFinger_FP_FINGER_LEFT_MIDDLE,
145        Finger::LeftRing => libfprint_sys::FpFinger_FP_FINGER_LEFT_RING,
146        Finger::LeftLittle => libfprint_sys::FpFinger_FP_FINGER_LEFT_LITTLE,
147        Finger::RightThumb => libfprint_sys::FpFinger_FP_FINGER_RIGHT_THUMB,
148        Finger::RightIndex => libfprint_sys::FpFinger_FP_FINGER_RIGHT_INDEX,
149        Finger::RightMiddle => libfprint_sys::FpFinger_FP_FINGER_RIGHT_MIDDLE,
150        Finger::RightRing => libfprint_sys::FpFinger_FP_FINGER_RIGHT_RING,
151        Finger::RightLittle => libfprint_sys::FpFinger_FP_FINGER_RIGHT_LITTLE,
152    }
153}
154
155/// Read the device's scan type. `FpScanType`'s discriminants *are* libfprint's raw
156/// `FP_SCAN_TYPE_*` values.
157pub(crate) fn scan_type(dev: &FpDevice) -> ScanType {
158    if dev.scan_type() == libfprint_sys::FpScanType_FP_SCAN_TYPE_PRESS {
159        ScanType::Press
160    } else {
161        ScanType::Swipe
162    }
163}
164
165/// Fold the device's capability set into a core [`DeviceFeature`] bitmask.
166///
167/// libfprint's `FpDeviceFeature` bit positions are mirrored exactly by [`DeviceFeature`], so the
168/// raw bitmask reconstructs the same mask.
169pub(crate) fn features(dev: &FpDevice) -> DeviceFeature {
170    DeviceFeature::from_bits_truncate(dev.features())
171}
172
173/// Read the device's sensor temperature (`FpTemperature`) as a core [`Temperature`], or `None`
174/// for an unrecognised value. The worker publishes this after each job to the device handle's
175/// shared cell, which the live [`Device::temperature`](fprint_core::Device::temperature) getter
176/// reads without a round-trip to the `!Send` device.
177pub(crate) fn temperature(dev: &FpDevice) -> Option<Temperature> {
178    match dev.temperature() {
179        libfprint_sys::FpTemperature_FP_TEMPERATURE_COLD => Some(Temperature::Cold),
180        libfprint_sys::FpTemperature_FP_TEMPERATURE_WARM => Some(Temperature::Warm),
181        libfprint_sys::FpTemperature_FP_TEMPERATURE_HOT => Some(Temperature::Hot),
182        _ => None,
183    }
184}
185
186/// Read the device's live finger-presence status (`FpFingerStatusFlags`) as a core
187/// [`FingerStatus`] bitmask.
188pub(crate) fn finger_status(dev: &FpDevice) -> FingerStatus {
189    let bits = dev.finger_status();
190    let mut status = FingerStatus::NONE;
191    if bits & libfprint_sys::FpFingerStatusFlags_FP_FINGER_STATUS_NEEDED != 0 {
192        status |= FingerStatus::NEEDED;
193    }
194    if bits & libfprint_sys::FpFingerStatusFlags_FP_FINGER_STATUS_PRESENT != 0 {
195        status |= FingerStatus::PRESENT;
196    }
197    status
198}
199
200/// Build the static [`DeviceInfo`] from a device's getters.
201///
202/// The virtual (and some real) devices report an empty `device_id`; we fall back to the
203/// driver id so the identifier is still stable and non-empty for [`crate::LibfprintBackend`]'s
204/// open-by-id lookup. Thermal state is *not* part of this static shape — it is a live reading via
205/// [`Device::temperature`](fprint_core::Device::temperature), published from the worker by
206/// [`temperature`].
207pub(crate) fn device_info(dev: &FpDevice) -> DeviceInfo {
208    let driver = dev.driver();
209    let device_id = dev.device_id();
210    let id = if device_id.is_empty() {
211        driver.clone()
212    } else {
213        device_id
214    };
215    DeviceInfo::new(
216        DeviceId::new(id),
217        DriverId::new(driver.clone()),
218        dev.name().unwrap_or(driver),
219        scan_type(dev),
220        features(dev),
221        dev.nr_enroll_stages().max(0) as u32,
222    )
223}