Skip to main content

openlogi_core/
device.rs

1//! Serializable device-model types.
2//!
3//! These mirror the HID++ types from the `hidpp` crate but live here so the
4//! CLI and any future GUI can depend on them without dragging in the protocol
5//! crate or its async transport.
6
7use serde::{Deserialize, Serialize};
8
9mod light;
10
11pub use light::{LightCapabilities, LightValueRange, LightValueRangeError, LightValueUnit};
12
13/// What a paired peripheral is. Mirrors `hidpp::receiver::bolt::BoltDeviceKind`
14/// but is owned by us so consumers don't depend on `hidpp`.
15///
16/// Several upstream "device type" vocabularies feed this one enum, and they do
17/// **not** agree on numbers: the Bolt pairing register uses `Unknown=0,
18/// Keyboard=1, Mouse=2, …`, while the HID++ `0x0005` feature uses
19/// `Keyboard=0, …, Mouse=3, …` (no `Unknown` at all). The asset registry adds a
20/// third, free-form *string* type (`"mouse"`, case-inconsistently `"MOUSE"`).
21/// They are converted to this enum at their respective boundaries — never by
22/// reinterpreting one source's raw byte with another's table — so the numeric
23/// mismatch can't leak past those mappers.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
25#[serde(rename_all = "lowercase")]
26pub enum DeviceKind {
27    /// Mice — the family OpenLogi's binding/DPI panels primarily target.
28    Mouse,
29    /// Keyboards, including lighting-capable ones.
30    Keyboard,
31    /// Standalone numeric keypads.
32    Numpad,
33    /// Presentation remotes (slide clickers).
34    Presenter,
35    /// Remote controls; the registry's `"remotecontrol"` string also folds here.
36    Remote,
37    /// Trackballs — treated like mice for presumed capabilities.
38    Trackball,
39    /// External touchpads; the registry's `"trackpad"` string also folds here.
40    Touchpad,
41    /// Pen/graphics tablets.
42    Tablet,
43    /// Game controllers, mirrored from the Bolt pairing vocabulary.
44    Gamepad,
45    /// Joysticks, mirrored from the Bolt pairing vocabulary.
46    Joystick,
47    /// Audio headsets paired through a receiver.
48    Headset,
49    /// Logitech webcam (UVC), configured through `openlogi-camera`.
50    Camera,
51    /// Not classified by any source — also the "no asset opinion" value
52    /// [`DeviceKind::from_registry_type`] returns for unmodelled strings.
53    Unknown,
54    /// Standalone light or other illumination device controlled outside HID++.
55    ///
56    /// This is an identity hint only. UI controls are gated by the dedicated
57    /// light capability descriptor, never by this variant alone.
58    Light,
59}
60
61impl DeviceKind {
62    /// Parse the OpenLogi asset registry's `type` string into a [`DeviceKind`].
63    ///
64    /// The registry field is free-form and case-inconsistent (both `"mouse"`
65    /// and `"MOUSE"` ship), so we case-fold before matching. Values we don't
66    /// model map to [`DeviceKind::Unknown`], which callers treat as "no asset
67    /// opinion" and fall back to the HID++ classification.
68    #[must_use]
69    pub fn from_registry_type(raw: &str) -> Self {
70        match raw.trim().to_ascii_lowercase().as_str() {
71            "mouse" => Self::Mouse,
72            "keyboard" => Self::Keyboard,
73            "numpad" => Self::Numpad,
74            "presenter" => Self::Presenter,
75            "remote" | "remotecontrol" => Self::Remote,
76            "trackball" => Self::Trackball,
77            "touchpad" | "trackpad" => Self::Touchpad,
78            "tablet" => Self::Tablet,
79            "gamepad" => Self::Gamepad,
80            "joystick" => Self::Joystick,
81            "headset" => Self::Headset,
82            "camera" => Self::Camera,
83            "light" | "lighting" | "illumination_light" => Self::Light,
84            _ => Self::Unknown,
85        }
86    }
87}
88
89/// What a device can be *configured* to do, derived from the HID++ feature
90/// table it reports (feature `0x0001`). This is the source of truth for which
91/// configuration panels the UI offers — a panel shows iff the device exposes
92/// the feature that drives it. Gating on capability rather than on
93/// [`DeviceKind`] is what keeps a misclassified device from losing its panels
94/// (issue #127): kind is an identity guess, capability is what the firmware
95/// actually announced.
96#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
97#[serde(deny_unknown_fields)]
98#[allow(
99    clippy::struct_excessive_bools,
100    reason = "capabilities is a serialized feature-bit DTO; independent booleans keep the IPC/config shape explicit"
101)]
102pub struct Capabilities {
103    /// Reprogrammable buttons — HID++ `0x1b00`–`0x1b04` (ReprogControls).
104    pub buttons: bool,
105    /// Adjustable pointer resolution — HID++ `0x2201` / `0x2202` (AdjustableDpi).
106    pub pointer: bool,
107    /// Solid-colour RGB the lighting panel can actually drive — HID++
108    /// `ColorLedEffects` (`0x8070`) or `PerKeyLighting` (`0x8080`), the features
109    /// `set_keyboard_color` writes. Backlight-only families aren't driven by the
110    /// panel, so they don't flip this and don't earn an inert Lighting tab.
111    pub lighting: bool,
112    /// Native vertical wheel inversion — HID++ `0x2121 HiResWheel` with the
113    /// firmware-reported `has_invert` capability.
114    pub scroll_inversion: bool,
115    /// HID++ `0x2121 HiResWheel` is present, so the wheel reporting resolution
116    /// can be read and changed independently of inversion support.
117    #[serde(default)]
118    pub hires_wheel: bool,
119    /// A horizontal thumb wheel is available: either the dedicated HID++
120    /// `0x2150 Thumbwheel` feature or a legacy `0x6501 Gestures2` descriptor
121    /// (gesture id 46, used by MX Master 2S).
122    #[serde(default)]
123    pub thumbwheel: bool,
124    /// Programmable haptic feedback — reverse-engineered HID++ `0x19b0`.
125    #[serde(default)]
126    pub haptic_feedback: bool,
127    /// A divertable Haptic Sense Panel control (`0x01a0`) was found in the
128    /// device's `0x1b04` control table.
129    #[serde(default)]
130    pub haptic_panel: bool,
131}
132
133impl Capabilities {
134    /// Derive capabilities from the set of HID++ feature IDs a device reports.
135    /// Membership of a driving feature ID flips the corresponding flag.
136    #[must_use]
137    pub fn from_feature_ids(ids: &[u16]) -> Self {
138        const BUTTONS: [u16; 5] = [0x1b00, 0x1b01, 0x1b02, 0x1b03, 0x1b04];
139        const POINTER: [u16; 2] = [0x2201, 0x2202];
140        // ColorLedEffects (0x8070), PerKeyLighting2 (0x8081) and PerKeyLighting
141        // (0x8080) — all three driven by `set_keyboard_color`, which prefers
142        // 0x8070's fixed effect to override a running onboard profile and falls
143        // back through 0x8081 to 0x8080. Other families (backlight 0x198x) stay
144        // out so they don't earn a tab the panel can't drive.
145        const LIGHTING: [u16; 3] = [0x8080, 0x8070, 0x8081];
146        let has = |family: &[u16]| ids.iter().any(|id| family.contains(id));
147        Self {
148            buttons: has(&BUTTONS),
149            pointer: has(&POINTER),
150            lighting: has(&LIGHTING),
151            scroll_inversion: false,
152            hires_wheel: ids.contains(&0x2121),
153            thumbwheel: ids.contains(&0x2150),
154            haptic_feedback: ids.contains(&0x19b0),
155            haptic_panel: false,
156        }
157    }
158
159    /// Best-effort capabilities for a device we could not probe (offline /
160    /// never reached), guessed from its [`DeviceKind`]. Used only as a fallback
161    /// when no measured [`Capabilities`] exist — a sleeping mouse should still
162    /// show its button/pointer panels so its bindings (host-side) stay
163    /// configurable.
164    #[must_use]
165    pub fn presumed_from_kind(kind: DeviceKind) -> Self {
166        match kind {
167            DeviceKind::Mouse | DeviceKind::Trackball => Self {
168                buttons: true,
169                pointer: true,
170                lighting: false,
171                scroll_inversion: false,
172                hires_wheel: false,
173                thumbwheel: false,
174                haptic_feedback: false,
175                haptic_panel: false,
176            },
177            DeviceKind::Keyboard => Self {
178                lighting: true,
179                ..Self::default()
180            },
181            _ => Self::default(),
182        }
183    }
184}
185
186/// Coarse battery bucket reported by the device firmware.
187#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
188#[serde(rename_all = "lowercase")]
189pub enum BatteryLevel {
190    /// Almost depleted — the firmware's most urgent bucket.
191    Critical,
192    /// Running low; worth surfacing a charge hint.
193    Low,
194    /// Comfortable middle range, no user action needed.
195    Good,
196    /// At or near full charge.
197    Full,
198    /// The firmware did not report a level, or reported one we don't model.
199    Unknown,
200}
201
202/// Charging state. Mirrors `hidpp 0.2`'s `BatteryStatus` plus `Unknown` for
203/// values added in future protocol versions.
204#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
205#[serde(rename_all = "snake_case")]
206pub enum BatteryStatus {
207    /// Running on battery.
208    Discharging,
209    /// Charging at the normal rate.
210    Charging,
211    /// Charging at reduced current (e.g. from a weak power source).
212    ChargingSlow,
213    /// Charge complete while still connected to power.
214    Full,
215    /// The device reported a charging fault.
216    Error,
217    /// A status value this build doesn't model (future protocol additions).
218    Unknown,
219}
220
221/// Battery snapshot for one paired device, as last polled over HID++.
222#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
223pub struct BatteryInfo {
224    /// Reported charge percentage (`0..=100`).
225    pub percentage: u8,
226    /// Coarse bucket for UI that doesn't want the raw percentage.
227    pub level: BatteryLevel,
228    /// Charging state at poll time.
229    pub status: BatteryStatus,
230}
231
232/// Identity of an enumerated receiver — no paired-device state (that lives
233/// in [`DeviceInventory::paired`]). For a direct (Bluetooth/wired) device,
234/// a synthetic entry mirroring the device's own HID identity fills this role.
235#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
236pub struct ReceiverInfo {
237    /// Product string from the HID enumeration (e.g. `"Logi Bolt Receiver"`).
238    pub name: String,
239    /// USB vendor ID (`0x046d` for Logitech).
240    pub vendor_id: u16,
241    /// USB product ID distinguishing the receiver model.
242    pub product_id: u16,
243    /// Platform-reported serial, when one is exposed. Deliberately excluded
244    /// from diagnostics (see [`crate::diagnostics::ReceiverDiag`]).
245    pub unique_id: Option<String>,
246}
247
248/// HID++ `DeviceInformation` (feature 0x0003) snapshot used to identify a
249/// device against external registries (e.g. the OpenLogi asset index).
250///
251/// `model_ids` is the per-transport PID array reported by the firmware,
252/// ordered to match the transports flagged in [`Self::transports`] (USB,
253/// eQuad, BTLE, Bluetooth) — slots that aren't enabled stay `0`. The Logi
254/// Options+ asset registry's `modelId` (e.g. `"6b023"`) is the concatenation
255/// of an extended-model byte and one of these PIDs, so callers usually want
256/// to format `extended_model_id` + `model_ids[N]` to match.
257#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
258#[serde(deny_unknown_fields)]
259pub struct DeviceModelInfo {
260    /// Number of firmware entities (main firmware, bootloader, …) the
261    /// device reports.
262    pub entity_count: u8,
263    /// HID++ DeviceInformation serial number, when the device supports the
264    /// optional serial-number function.
265    pub serial_number: Option<String>,
266    /// Per-unit ID bytes — unique to the physical unit, unlike the
267    /// model-level fields around it.
268    pub unit_id: [u8; 4],
269    /// Which transports the firmware supports; defines the slot order of
270    /// [`Self::model_ids`].
271    pub transports: DeviceTransports,
272    /// Per-transport PIDs ordered to match [`Self::transports`] (USB, eQuad,
273    /// BTLE, Bluetooth); slots for disabled transports stay `0`.
274    pub model_ids: [u16; 3],
275    /// Extra model byte prefixed to a PID to form the asset registry's
276    /// `modelId` — see [`Self::config_key`].
277    pub extended_model_id: u8,
278}
279
280impl DeviceModelInfo {
281    /// Stable identifier used to key per-device configuration (button
282    /// bindings, etc.) and to look up assets in the OpenLogi asset registry.
283    ///
284    /// Format: `{extended_model_id:x}{model_ids[0]:04x}` — the same string
285    /// the depot `manifest.json` uses for its `modelId` field. Example: an
286    /// MX Master 4 with `extended_model_id = 0x02` and `model_ids[0] = 0xb042`
287    /// resolves to `"2b042"`.
288    #[must_use]
289    pub fn config_key(&self) -> String {
290        format!("{:x}{:04x}", self.extended_model_id, self.model_ids[0])
291    }
292}
293
294/// Mirror of hidpp's `DeviceTransport` bitfield — one bool per protocol the
295/// device firmware exposes. The shape is dictated by HID++ feature 0x0003;
296/// a state machine doesn't fit since a single device can announce multiple
297/// transports simultaneously.
298#[allow(
299    clippy::struct_excessive_bools,
300    reason = "bitfield mirroring HID++ DeviceInformation; transports are independent flags"
301)]
302#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
303#[serde(deny_unknown_fields)]
304pub struct DeviceTransports {
305    /// Wired USB.
306    pub usb: bool,
307    /// Logitech eQuad — the Unifying/Bolt receiver RF protocol.
308    pub equad: bool,
309    /// Bluetooth Low Energy.
310    pub btle: bool,
311    /// Classic Bluetooth.
312    pub bluetooth: bool,
313}
314
315/// One device in the agent's inventory snapshot: a receiver pairing slot,
316/// or a direct (Bluetooth/wired) attachment under its synthetic
317/// [`ReceiverInfo`]. Embedded in [`DeviceInventory`], so its field order is
318/// IPC wire format — see that type's contract.
319#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
320pub struct PairedDevice {
321    /// Receiver-assigned slot (1..=6 for Bolt).
322    pub slot: u8,
323    /// Firmware codename (e.g. `"MX Master 3S"`), when reported.
324    pub codename: Option<String>,
325    /// Wireless product ID. `None` for offline / unreachable devices on hidpp 0.2.
326    pub wpid: Option<u16>,
327    /// Best-guess classification. Identity only — panel gating uses
328    /// [`Self::capabilities`] instead, so a misread kind can't hide panels
329    /// (issue #127).
330    pub kind: DeviceKind,
331    /// Whether the device was reachable at enumeration time; offline devices
332    /// keep their slot with reduced detail.
333    pub online: bool,
334    /// Last battery reading, `None` when offline or the device doesn't
335    /// report battery.
336    pub battery: Option<BatteryInfo>,
337    /// Output of HID++ feature 0x0003 — populated for online devices that
338    /// expose the feature. Drives asset-registry lookups in the GUI.
339    pub model_info: Option<DeviceModelInfo>,
340    /// Configuration capabilities derived from the device's HID++ feature
341    /// table. `None` for devices we couldn't probe (offline / unreachable);
342    /// the GUI then falls back to [`Capabilities::presumed_from_kind`].
343    pub capabilities: Option<Capabilities>,
344}
345
346/// Address of a standalone raw-HID interface.
347///
348/// The identity is an opaque transport-generated string. It is deliberately
349/// kept separate from the HID++ receiver/slot address so a raw device cannot
350/// accidentally enter the HID++ `Direct` path.
351#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
352pub struct RawDeviceAddress {
353    /// HID vendor ID.
354    pub vendor_id: u16,
355    /// HID product ID.
356    pub product_id: u16,
357    /// HID usage page.
358    pub usage_page: u16,
359    /// HID usage ID.
360    pub usage_id: u16,
361    /// Identity chosen by the transport: a serial when available, otherwise
362    /// an explicitly transient OS-node identity. It is never an enumeration
363    /// index and a transient value is not persisted as a physical key.
364    pub identity: String,
365}
366
367/// A standalone device that is not a HID++ receiver pairing slot.
368///
369/// This is the inventory bridge for Litra and future non-HID++ categories.
370/// Receiver-backed devices continue to use [`PairedDevice`] inside
371/// [`DeviceInventory`].
372#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
373pub struct StandaloneDevice {
374    /// Raw HID address used to re-find the interface.
375    pub address: RawDeviceAddress,
376    /// Human-readable name supplied by the OS/HID descriptor.
377    pub display_name: String,
378    /// Human-readable manufacturer, when available.
379    pub manufacturer: Option<String>,
380    /// Device serial, when the HID backend exposes one.
381    pub serial_number: Option<String>,
382    /// Stable four-byte identity when the protocol/driver provides one.
383    /// Raw HID drivers may use zeroes when no such field exists.
384    pub unit_id: [u8; 4],
385    /// Identity classification. Capability fields gate controls.
386    pub kind: DeviceKind,
387    /// Whether this interface was present in the latest completed scan.
388    pub online: bool,
389    /// HID++ capabilities are absent for a non-HID++ device.
390    pub capabilities: Option<Capabilities>,
391    /// Standalone capability descriptor, if the selected driver recognizes it.
392    pub light_capabilities: Option<LightCapabilities>,
393    /// Stable identifier of the driver family that owns this raw interface.
394    /// This is deliberately separate from the product ID so a future family
395    /// can share a protocol driver across several product variants.
396    pub driver_id: String,
397    /// Optional model-level identity in the OpenLogi asset registry.
398    ///
399    /// This is deliberately appended: `StandaloneDevice` crosses the
400    /// append-only GUI↔agent bincode wire format.
401    #[serde(default, skip_serializing_if = "Option::is_none")]
402    pub registry_model_id: Option<String>,
403}
404
405/// One receiver and its paired devices — the unit the agent's inventory
406/// snapshot is made of.
407///
408/// Crosses the agent↔GUI IPC (everything it embeds too: [`ReceiverInfo`],
409/// [`PairedDevice`], battery/model-info/capability types). bincode encodes
410/// field and variant *order*, so reordering, retyping, or wrapping any field
411/// in this tree is a wire-format change and requires a `PROTOCOL_VERSION`
412/// bump (guarded by `openlogi-ipc/tests/wire_format.rs`).
413#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
414pub struct DeviceInventory {
415    /// The receiver's identity — synthetic (mirroring the device itself)
416    /// for a direct Bluetooth/wired attachment.
417    pub receiver: ReceiverInfo,
418    /// The devices reached through this receiver; a direct attachment
419    /// carries exactly one entry.
420    pub paired: Vec<PairedDevice>,
421}
422
423#[cfg(test)]
424mod tests {
425    #![allow(
426        clippy::expect_used,
427        reason = "range fixture construction is intentionally asserted in tests"
428    )]
429
430    use super::{
431        BatteryInfo, BatteryLevel, BatteryStatus, Capabilities, DeviceInventory, DeviceKind,
432        DeviceModelInfo, DeviceTransports, LightValueRange, LightValueUnit, PairedDevice,
433        ReceiverInfo,
434    };
435
436    fn inventory(slot: u8, wpid: Option<u16>, battery_percentage: u8) -> DeviceInventory {
437        DeviceInventory {
438            receiver: ReceiverInfo {
439                name: "Logi Bolt Receiver".to_string(),
440                vendor_id: 0x046d,
441                product_id: 0xc548,
442                unique_id: Some("receiver-1".to_string()),
443            },
444            paired: vec![PairedDevice {
445                slot,
446                codename: Some("MX Test".to_string()),
447                wpid,
448                kind: DeviceKind::Mouse,
449                online: true,
450                battery: Some(BatteryInfo {
451                    percentage: battery_percentage,
452                    level: BatteryLevel::Good,
453                    status: BatteryStatus::Discharging,
454                }),
455                model_info: Some(DeviceModelInfo {
456                    entity_count: 1,
457                    serial_number: Some("serial-1".to_string()),
458                    unit_id: [1, 2, 3, 4],
459                    transports: DeviceTransports {
460                        usb: true,
461                        equad: true,
462                        btle: false,
463                        bluetooth: false,
464                    },
465                    model_ids: [0xb023, 0, 0],
466                    extended_model_id: 0x02,
467                }),
468                capabilities: Some(Capabilities {
469                    buttons: true,
470                    pointer: true,
471                    lighting: false,
472                    scroll_inversion: false,
473                    hires_wheel: false,
474                    thumbwheel: false,
475                    haptic_feedback: false,
476                    haptic_panel: false,
477                }),
478            }],
479        }
480    }
481
482    #[test]
483    fn device_inventory_equality_includes_nested_device_fields() {
484        let base = inventory(1, Some(0xb023), 86);
485        assert_eq!(base, base.clone());
486
487        assert_ne!(
488            base,
489            inventory(2, Some(0xb023), 86),
490            "slot changes must affect inventory equality"
491        );
492        assert_ne!(
493            base,
494            inventory(1, Some(0xb024), 86),
495            "wireless product id changes must affect inventory equality"
496        );
497        assert_ne!(
498            base,
499            inventory(1, Some(0xb023), 87),
500            "nested battery changes must affect inventory equality"
501        );
502    }
503
504    #[test]
505    fn registry_type_is_case_folded() {
506        // The registry ships both `"mouse"` and `"MOUSE"`; both must resolve so
507        // the asset cross-check can't silently miss a depot.
508        assert_eq!(DeviceKind::from_registry_type("mouse"), DeviceKind::Mouse);
509        assert_eq!(DeviceKind::from_registry_type("MOUSE"), DeviceKind::Mouse);
510        assert_eq!(
511            DeviceKind::from_registry_type("  Keyboard "),
512            DeviceKind::Keyboard
513        );
514    }
515
516    #[test]
517    fn unknown_registry_type_defers_to_the_caller() {
518        // Unmodelled / empty → Unknown, i.e. "no asset opinion".
519        assert_eq!(
520            DeviceKind::from_registry_type("webcam"),
521            DeviceKind::Unknown
522        );
523        assert_eq!(DeviceKind::from_registry_type(""), DeviceKind::Unknown);
524    }
525
526    #[test]
527    fn capabilities_track_the_driving_feature_ids() {
528        use super::Capabilities;
529        // A typical MX mouse: ReprogControls (0x1b04) + ExtendedAdjustableDpi
530        // (0x2202), no lighting.
531        let mouse =
532            Capabilities::from_feature_ids(&[0x0003, 0x1b04, 0x2121, 0x2150, 0x2202, 0x2110]);
533        assert_eq!(
534            mouse,
535            Capabilities {
536                buttons: true,
537                pointer: true,
538                lighting: false,
539                scroll_inversion: false,
540                hires_wheel: true,
541                thumbwheel: true,
542                haptic_feedback: false,
543                haptic_panel: false,
544            }
545        );
546        assert!(!Capabilities::from_feature_ids(&[0x0003, 0x1b04]).thumbwheel);
547        // A wired G-series keyboard: PerKeyLighting (0x8080), no DPI/buttons.
548        let keyboard = Capabilities::from_feature_ids(&[0x0001, 0x8080]);
549        assert_eq!(
550            keyboard,
551            Capabilities {
552                buttons: false,
553                pointer: false,
554                lighting: true,
555                scroll_inversion: false,
556                hires_wheel: false,
557                thumbwheel: false,
558                haptic_feedback: false,
559                haptic_panel: false,
560            }
561        );
562        // No driving features → nothing offered.
563        assert_eq!(
564            Capabilities::from_feature_ids(&[0x0000, 0x0003]),
565            Capabilities::default()
566        );
567    }
568
569    #[test]
570    fn every_driveable_lighting_family_earns_the_tab() {
571        // `set_keyboard_color` walks 0x8070 → 0x8081 → 0x8080, so a keyboard
572        // exposing any one of them can be coloured and must get the tab.
573        // 0x8081 was missing here, which left such a keyboard with no lighting
574        // UI at all.
575        for id in [0x8070, 0x8080, 0x8081] {
576            assert!(
577                Capabilities::from_feature_ids(&[0x0001, id]).lighting,
578                "0x{id:04x} must offer the lighting tab"
579            );
580        }
581        // Backlight (0x198x) stays out — the panel cannot drive it.
582        assert!(!Capabilities::from_feature_ids(&[0x0001, 0x1982]).lighting);
583    }
584
585    #[test]
586    fn persisted_capabilities_without_appended_wheel_fields_load_as_unsupported()
587    -> Result<(), toml::de::Error> {
588        use super::Capabilities;
589
590        let capabilities: Capabilities = toml::from_str(
591            r"
592                buttons = true
593                pointer = true
594                lighting = false
595                scroll_inversion = true
596            ",
597        )?;
598
599        assert!(!capabilities.hires_wheel);
600        assert!(!capabilities.thumbwheel);
601        assert!(capabilities.scroll_inversion);
602        Ok(())
603    }
604
605    #[test]
606    fn presumed_capabilities_keep_an_unprobed_mouse_configurable() {
607        use super::Capabilities;
608        let mouse = Capabilities::presumed_from_kind(DeviceKind::Mouse);
609        assert!(mouse.buttons && mouse.pointer && !mouse.lighting);
610        assert!(!mouse.thumbwheel);
611        assert!(Capabilities::presumed_from_kind(DeviceKind::Keyboard).lighting);
612        // An unidentified device presumes nothing — it must be measured.
613        assert_eq!(
614            Capabilities::presumed_from_kind(DeviceKind::Unknown),
615            Capabilities::default()
616        );
617    }
618
619    #[test]
620    fn light_ranges_reject_invalid_grids_and_units() {
621        LightValueRange::new(10, 1, 1, LightValueUnit::Lumens)
622            .expect_err("a minimum above the maximum must be rejected");
623        LightValueRange::new(0, 10, 0, LightValueUnit::Lumens)
624            .expect_err("a zero step must be rejected");
625        LightValueRange::new(0, 10, 3, LightValueUnit::Lumens)
626            .expect_err("a step that does not divide the span must be rejected");
627        LightValueRange::new(0, 101, 1, LightValueUnit::Percent)
628            .expect_err("a percent range above 100 must be rejected");
629    }
630
631    #[test]
632    fn light_ranges_quantize_without_leaving_the_advertised_grid() {
633        let range = LightValueRange::new(20, 250, 10, LightValueUnit::Lumens).expect("valid range");
634        assert_eq!(range.native_for_percent(0), Some(20));
635        assert_eq!(range.native_for_percent(50), Some(140));
636        assert_eq!(range.native_for_percent(100), Some(250));
637        assert_eq!(range.quantize(249), 250);
638        assert!(range.contains(range.native_for_percent(65).expect("mapped value")));
639    }
640
641    #[test]
642    fn invalid_light_ranges_fail_toml_deserialization() {
643        let result = toml::from_str::<LightValueRange>(
644            "min = 2700\nmax = 6500\nstep = 0\nunit = 'kelvin'\n",
645        );
646        result.expect_err("a zero step must not survive deserialization");
647    }
648}