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#[expect(
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 for the transports enabled in [`Self::transports`],
273 /// packed from the front in ascending HID++ transport-bit order:
274 /// Bluetooth (bit 0), BTLE (bit 1), eQuad (bit 2), USB (bit 3). Only
275 /// enabled transports take a slot — a disabled transport is skipped, not
276 /// zero-filled — so unused trailing slots stay `0` and the array holds at
277 /// most three PIDs.
278 ///
279 /// Note this is the reverse of the field order of [`DeviceTransports`],
280 /// which lists `usb` first. A device with `usb + equad` reports
281 /// `[eQuad PID, USB PID, 0]`; one with `equad + btle` reports
282 /// `[BTLE PID, eQuad PID, 0]`.
283 pub model_ids: [u16; 3],
284 /// Extra model byte prefixed to a PID to form the asset registry's
285 /// `modelId` — see [`Self::config_key`].
286 pub extended_model_id: u8,
287}
288
289impl DeviceModelInfo {
290 /// Stable identifier used to key per-device configuration (button
291 /// bindings, etc.) and to look up assets in the OpenLogi asset registry.
292 ///
293 /// Format: `{extended_model_id:x}{model_ids[0]:04x}` — the same string
294 /// the depot `manifest.json` uses for its `modelId` field. Example: an
295 /// MX Master 4 with `extended_model_id = 0x02` and `model_ids[0] = 0xb042`
296 /// resolves to `"2b042"`.
297 #[must_use]
298 pub fn config_key(&self) -> String {
299 format!("{:x}{:04x}", self.extended_model_id, self.model_ids[0])
300 }
301}
302
303/// Mirror of hidpp's `DeviceTransport` bitfield — one bool per protocol the
304/// device firmware exposes. The shape is dictated by HID++ feature 0x0003;
305/// a state machine doesn't fit since a single device can announce multiple
306/// transports simultaneously.
307#[expect(
308 clippy::struct_excessive_bools,
309 reason = "bitfield mirroring HID++ DeviceInformation; transports are independent flags"
310)]
311#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
312#[serde(deny_unknown_fields)]
313pub struct DeviceTransports {
314 /// Wired USB.
315 pub usb: bool,
316 /// Logitech eQuad — the Unifying/Bolt receiver RF protocol.
317 pub equad: bool,
318 /// Bluetooth Low Energy.
319 pub btle: bool,
320 /// Classic Bluetooth.
321 pub bluetooth: bool,
322}
323
324/// One device in the agent's inventory snapshot: a receiver pairing slot,
325/// or a direct (Bluetooth/wired) attachment under its synthetic
326/// [`ReceiverInfo`]. Embedded in [`DeviceInventory`], so its field order is
327/// IPC wire format — see that type's contract.
328#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
329pub struct PairedDevice {
330 /// Receiver-assigned slot (1..=6 for Bolt).
331 pub slot: u8,
332 /// Firmware codename (e.g. `"MX Master 3S"`), when reported.
333 pub codename: Option<String>,
334 /// Wireless product ID. `None` for offline / unreachable devices on hidpp 0.2.
335 pub wpid: Option<u16>,
336 /// Best-guess classification. Identity only — panel gating uses
337 /// [`Self::capabilities`] instead, so a misread kind can't hide panels
338 /// (issue #127).
339 pub kind: DeviceKind,
340 /// Whether the device was reachable at enumeration time; offline devices
341 /// keep their slot with reduced detail.
342 pub online: bool,
343 /// Last battery reading, `None` when offline or the device doesn't
344 /// report battery.
345 pub battery: Option<BatteryInfo>,
346 /// Output of HID++ feature 0x0003 — populated for online devices that
347 /// expose the feature. Drives asset-registry lookups in the GUI.
348 pub model_info: Option<DeviceModelInfo>,
349 /// Configuration capabilities derived from the device's HID++ feature
350 /// table. `None` for devices we couldn't probe (offline / unreachable);
351 /// the GUI then falls back to [`Capabilities::presumed_from_kind`].
352 pub capabilities: Option<Capabilities>,
353}
354
355/// Address of a standalone raw-HID interface.
356///
357/// The identity is an opaque transport-generated string. It is deliberately
358/// kept separate from the HID++ receiver/slot address so a raw device cannot
359/// accidentally enter the HID++ `Direct` path.
360#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
361pub struct RawDeviceAddress {
362 /// HID vendor ID.
363 pub vendor_id: u16,
364 /// HID product ID.
365 pub product_id: u16,
366 /// HID usage page.
367 pub usage_page: u16,
368 /// HID usage ID.
369 pub usage_id: u16,
370 /// Identity chosen by the transport: a serial when available, otherwise
371 /// an explicitly transient OS-node identity. It is never an enumeration
372 /// index and a transient value is not persisted as a physical key.
373 pub identity: String,
374}
375
376/// A standalone device that is not a HID++ receiver pairing slot.
377///
378/// This is the inventory bridge for Litra and future non-HID++ categories.
379/// Receiver-backed devices continue to use [`PairedDevice`] inside
380/// [`DeviceInventory`].
381#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
382pub struct StandaloneDevice {
383 /// Raw HID address used to re-find the interface.
384 pub address: RawDeviceAddress,
385 /// Human-readable name supplied by the OS/HID descriptor.
386 pub display_name: String,
387 /// Human-readable manufacturer, when available.
388 pub manufacturer: Option<String>,
389 /// Device serial, when the HID backend exposes one.
390 pub serial_number: Option<String>,
391 /// Stable four-byte identity when the protocol/driver provides one.
392 /// Raw HID drivers may use zeroes when no such field exists.
393 pub unit_id: [u8; 4],
394 /// Identity classification. Capability fields gate controls.
395 pub kind: DeviceKind,
396 /// Whether this interface was present in the latest completed scan.
397 pub online: bool,
398 /// HID++ capabilities are absent for a non-HID++ device.
399 pub capabilities: Option<Capabilities>,
400 /// Standalone capability descriptor, if the selected driver recognizes it.
401 pub light_capabilities: Option<LightCapabilities>,
402 /// Stable identifier of the driver family that owns this raw interface.
403 /// This is deliberately separate from the product ID so a future family
404 /// can share a protocol driver across several product variants.
405 pub driver_id: String,
406 /// Optional model-level identity in the OpenLogi asset registry.
407 ///
408 /// This is deliberately appended: `StandaloneDevice` crosses the
409 /// append-only GUI↔agent bincode wire format.
410 #[serde(default)]
411 pub registry_model_id: Option<String>,
412}
413
414/// One receiver and its paired devices — the unit the agent's inventory
415/// snapshot is made of.
416///
417/// Crosses the agent↔GUI IPC (everything it embeds too: [`ReceiverInfo`],
418/// [`PairedDevice`], battery/model-info/capability types). bincode encodes
419/// field and variant *order*, so reordering, retyping, or wrapping any field
420/// in this tree is a wire-format change and requires a `PROTOCOL_VERSION`
421/// bump (guarded by `openlogi-ipc/tests/wire_format.rs`).
422#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
423pub struct DeviceInventory {
424 /// The receiver's identity — synthetic (mirroring the device itself)
425 /// for a direct Bluetooth/wired attachment.
426 pub receiver: ReceiverInfo,
427 /// The devices reached through this receiver; a direct attachment
428 /// carries exactly one entry.
429 pub paired: Vec<PairedDevice>,
430}
431
432#[cfg(test)]
433mod tests {
434 use super::{
435 BatteryInfo, BatteryLevel, BatteryStatus, Capabilities, DeviceInventory, DeviceKind,
436 DeviceModelInfo, DeviceTransports, LightValueRange, LightValueUnit, PairedDevice,
437 ReceiverInfo,
438 };
439
440 fn inventory(slot: u8, wpid: Option<u16>, battery_percentage: u8) -> DeviceInventory {
441 DeviceInventory {
442 receiver: ReceiverInfo {
443 name: "Logi Bolt Receiver".to_string(),
444 vendor_id: 0x046d,
445 product_id: 0xc548,
446 unique_id: Some("receiver-1".to_string()),
447 },
448 paired: vec![PairedDevice {
449 slot,
450 codename: Some("MX Test".to_string()),
451 wpid,
452 kind: DeviceKind::Mouse,
453 online: true,
454 battery: Some(BatteryInfo {
455 percentage: battery_percentage,
456 level: BatteryLevel::Good,
457 status: BatteryStatus::Discharging,
458 }),
459 model_info: Some(DeviceModelInfo {
460 entity_count: 1,
461 serial_number: Some("serial-1".to_string()),
462 unit_id: [1, 2, 3, 4],
463 transports: DeviceTransports {
464 usb: true,
465 equad: true,
466 btle: false,
467 bluetooth: false,
468 },
469 model_ids: [0xb023, 0, 0],
470 extended_model_id: 0x02,
471 }),
472 capabilities: Some(Capabilities {
473 buttons: true,
474 pointer: true,
475 lighting: false,
476 scroll_inversion: false,
477 hires_wheel: false,
478 thumbwheel: false,
479 haptic_feedback: false,
480 haptic_panel: false,
481 }),
482 }],
483 }
484 }
485
486 #[test]
487 fn device_inventory_equality_includes_nested_device_fields() {
488 let base = inventory(1, Some(0xb023), 86);
489 assert_eq!(base, base.clone());
490
491 assert_ne!(
492 base,
493 inventory(2, Some(0xb023), 86),
494 "slot changes must affect inventory equality"
495 );
496 assert_ne!(
497 base,
498 inventory(1, Some(0xb024), 86),
499 "wireless product id changes must affect inventory equality"
500 );
501 assert_ne!(
502 base,
503 inventory(1, Some(0xb023), 87),
504 "nested battery changes must affect inventory equality"
505 );
506 }
507
508 #[test]
509 fn registry_type_is_case_folded() {
510 // The registry ships both `"mouse"` and `"MOUSE"`; both must resolve so
511 // the asset cross-check can't silently miss a depot.
512 assert_eq!(DeviceKind::from_registry_type("mouse"), DeviceKind::Mouse);
513 assert_eq!(DeviceKind::from_registry_type("MOUSE"), DeviceKind::Mouse);
514 assert_eq!(
515 DeviceKind::from_registry_type(" Keyboard "),
516 DeviceKind::Keyboard
517 );
518 }
519
520 #[test]
521 fn unknown_registry_type_defers_to_the_caller() {
522 // Unmodelled / empty → Unknown, i.e. "no asset opinion".
523 assert_eq!(
524 DeviceKind::from_registry_type("webcam"),
525 DeviceKind::Unknown
526 );
527 assert_eq!(DeviceKind::from_registry_type(""), DeviceKind::Unknown);
528 }
529
530 #[test]
531 fn capabilities_track_the_driving_feature_ids() {
532 use super::Capabilities;
533 // A typical MX mouse: ReprogControls (0x1b04) + ExtendedAdjustableDpi
534 // (0x2202), no lighting.
535 let mouse =
536 Capabilities::from_feature_ids(&[0x0003, 0x1b04, 0x2121, 0x2150, 0x2202, 0x2110]);
537 assert_eq!(
538 mouse,
539 Capabilities {
540 buttons: true,
541 pointer: true,
542 lighting: false,
543 scroll_inversion: false,
544 hires_wheel: true,
545 thumbwheel: true,
546 haptic_feedback: false,
547 haptic_panel: false,
548 }
549 );
550 assert!(!Capabilities::from_feature_ids(&[0x0003, 0x1b04]).thumbwheel);
551 // A wired G-series keyboard: PerKeyLighting (0x8080), no DPI/buttons.
552 let keyboard = Capabilities::from_feature_ids(&[0x0001, 0x8080]);
553 assert_eq!(
554 keyboard,
555 Capabilities {
556 buttons: false,
557 pointer: false,
558 lighting: true,
559 scroll_inversion: false,
560 hires_wheel: false,
561 thumbwheel: false,
562 haptic_feedback: false,
563 haptic_panel: false,
564 }
565 );
566 // No driving features → nothing offered.
567 assert_eq!(
568 Capabilities::from_feature_ids(&[0x0000, 0x0003]),
569 Capabilities::default()
570 );
571 }
572
573 #[test]
574 fn every_driveable_lighting_family_earns_the_tab() {
575 // `set_keyboard_color` walks 0x8070 → 0x8081 → 0x8080, so a keyboard
576 // exposing any one of them can be coloured and must get the tab.
577 // 0x8081 was missing here, which left such a keyboard with no lighting
578 // UI at all.
579 for id in [0x8070, 0x8080, 0x8081] {
580 assert!(
581 Capabilities::from_feature_ids(&[0x0001, id]).lighting,
582 "0x{id:04x} must offer the lighting tab"
583 );
584 }
585 // Backlight (0x198x) stays out — the panel cannot drive it.
586 assert!(!Capabilities::from_feature_ids(&[0x0001, 0x1982]).lighting);
587 }
588
589 #[test]
590 fn persisted_capabilities_without_appended_wheel_fields_load_as_unsupported()
591 -> Result<(), toml::de::Error> {
592 use super::Capabilities;
593
594 let capabilities: Capabilities = toml::from_str(
595 r"
596 buttons = true
597 pointer = true
598 lighting = false
599 scroll_inversion = true
600 ",
601 )?;
602
603 assert!(!capabilities.hires_wheel);
604 assert!(!capabilities.thumbwheel);
605 assert!(capabilities.scroll_inversion);
606 Ok(())
607 }
608
609 #[test]
610 fn presumed_capabilities_keep_an_unprobed_mouse_configurable() {
611 use super::Capabilities;
612 let mouse = Capabilities::presumed_from_kind(DeviceKind::Mouse);
613 assert!(mouse.buttons && mouse.pointer && !mouse.lighting);
614 assert!(!mouse.thumbwheel);
615 assert!(Capabilities::presumed_from_kind(DeviceKind::Keyboard).lighting);
616 // An unidentified device presumes nothing — it must be measured.
617 assert_eq!(
618 Capabilities::presumed_from_kind(DeviceKind::Unknown),
619 Capabilities::default()
620 );
621 }
622
623 #[test]
624 fn light_ranges_reject_invalid_grids_and_units() {
625 LightValueRange::new(10, 1, 1, LightValueUnit::Lumens)
626 .expect_err("a minimum above the maximum must be rejected");
627 LightValueRange::new(0, 10, 0, LightValueUnit::Lumens)
628 .expect_err("a zero step must be rejected");
629 LightValueRange::new(0, 10, 3, LightValueUnit::Lumens)
630 .expect_err("a step that does not divide the span must be rejected");
631 LightValueRange::new(0, 101, 1, LightValueUnit::Percent)
632 .expect_err("a percent range above 100 must be rejected");
633 }
634
635 #[test]
636 fn light_ranges_quantize_without_leaving_the_advertised_grid() {
637 let range = LightValueRange::new(20, 250, 10, LightValueUnit::Lumens).expect("valid range");
638 assert_eq!(range.native_for_percent(0), Some(20));
639 assert_eq!(range.native_for_percent(50), Some(140));
640 assert_eq!(range.native_for_percent(100), Some(250));
641 assert_eq!(range.quantize(249), 250);
642 assert!(range.contains(range.native_for_percent(65).expect("mapped value")));
643 }
644
645 #[test]
646 fn invalid_light_ranges_fail_toml_deserialization() {
647 let result = toml::from_str::<LightValueRange>(
648 "min = 2700\nmax = 6500\nstep = 0\nunit = 'kelvin'\n",
649 );
650 result.expect_err("a zero step must not survive deserialization");
651 }
652}