openlogi_core/config/device.rs
1//! Per-device config: [`DeviceIdentity`], [`DeviceConfig`], and the
2//! [`RawDeviceConfig`] migration shim that folds pre-v2 files into the
3//! unified `bindings` map.
4
5use std::collections::BTreeMap;
6
7use serde::{Deserialize, Serialize};
8
9use super::settings::{
10 CameraControls, GestureOwner, LightSettings, Lighting, ScrollResolution, SmartShift,
11 ThumbwheelSensitivity, deserialize_gesture_owner,
12};
13use crate::binding::{Action, ActionRingConfig, Binding, ButtonId, GestureDirection};
14use crate::device::{Capabilities, DeviceKind, DeviceModelInfo, LightCapabilities};
15use crate::hid::Dpi;
16
17/// Last-known identity of a device, captured while it was online so the UI can
18/// render its card and the *correct* config panels before any live HID++ probe
19/// completes — or while the device is asleep and can't be probed at all.
20///
21/// Every field is a **static property of the model**, not of the current
22/// connection: an MX Master 3S has adjustable DPI whether or not it is awake.
23/// That is what makes this safe to persist — it never goes stale. It is also
24/// free of any per-unit identifier (no serial number, no unit id), so caching
25/// it adds no privacy surface beyond the `config_key` already used as the map
26/// key. Persisting identity is what stops a sleeping/just-booted mouse from
27/// vanishing from the device list (and losing its Pointer/Buttons panels)
28/// until a cold probe happens to win its race — see issue #159.
29#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
30#[serde(deny_unknown_fields)]
31pub struct DeviceIdentity {
32 /// The name shown in the carousel, as resolved from the asset registry the
33 /// last time the device was online.
34 pub display_name: String,
35 /// HID++ model identity from feature 0x0003, when available. Persisted so
36 /// the GUI can resolve the same curated asset while the device is asleep.
37 #[serde(default, skip_serializing_if = "Option::is_none")]
38 pub model_info: Option<DeviceModelInfo>,
39 /// Firmware codename, when available. Used as an asset-resolution hint and
40 /// as a readable fallback for devices without curated model metadata.
41 #[serde(default, skip_serializing_if = "Option::is_none")]
42 pub codename: Option<String>,
43 /// The device's resolved [`DeviceKind`] (asset registry preferred, HID++
44 /// classification as fallback).
45 pub kind: DeviceKind,
46 /// Configuration capabilities measured from the device's HID++ feature
47 /// table. This is the field that keeps a sleeping mouse's panels visible.
48 pub capabilities: Capabilities,
49 /// Standalone-light controls measured by its protocol driver, if this is
50 /// a non-HID++ light. Old configs omit this field.
51 #[serde(default, skip_serializing_if = "Option::is_none")]
52 pub light_capabilities: Option<LightCapabilities>,
53 /// Standalone driver family that produced this identity, when applicable.
54 /// Old configs and HID++ devices omit it.
55 #[serde(default, skip_serializing_if = "Option::is_none")]
56 pub driver_id: Option<String>,
57 /// Optional model-level identity in the OpenLogi asset registry. This is
58 /// not a physical-device key and never contains a serial or OS node id.
59 #[serde(default, skip_serializing_if = "Option::is_none")]
60 pub registry_model_id: Option<String>,
61}
62
63impl DeviceIdentity {
64 /// Remove per-unit identifiers before this model snapshot is persisted.
65 #[must_use]
66 pub fn without_unit_identifiers(mut self) -> Self {
67 if let Some(model) = &mut self.model_info {
68 model.serial_number = None;
69 model.unit_id = [0; 4];
70 }
71 self
72 }
73}
74
75/// Settings scoped to a single physical device.
76///
77/// Deserialization goes through `RawDeviceConfig` (`#[serde(from)]`) so
78/// pre-v2 files — which split bindings across `button_bindings` +
79/// `gesture_bindings` — fold into the unified [`Self::bindings`] map. Only
80/// `bindings` is ever serialized, so a migrated file is rewritten to the v2
81/// shape on its next save.
82#[derive(Debug, Clone, Serialize, Deserialize)]
83#[serde(from = "RawDeviceConfig")]
84pub struct DeviceConfig {
85 /// Whether OpenLogi manages this device at all. `false` leaves the device
86 /// fully native: no capture session (no HID++ diversion of any control)
87 /// and no volatile-settings re-apply on reconnect. Defaults to `true` and
88 /// is only serialized when disabled.
89 #[serde(default = "default_true", skip_serializing_if = "is_true")]
90 pub enabled: bool,
91 /// Legacy owner-lock carrier, deserialize-only: the v3-and-older
92 /// `gesture_owner` field, held here just long enough for the version-gated
93 /// load migration (`Config::migrate_owner_locked_gestures`) to consume it.
94 /// Never serialized — since v4 the binding shape is the whole truth
95 /// (gesture mode is per-button; see
96 /// [`Config::set_gesture_mode`](crate::config::Config::set_gesture_mode)).
97 #[serde(skip_serializing)]
98 pub(super) gesture_owner: Option<GestureOwner>,
99 /// Last-known identity (name / kind / capabilities), captured while the
100 /// device was online. Lets the UI render this device — with the right
101 /// config panels — on a cold start before any probe, or while it sleeps.
102 /// `None` for configs written before this field existed or by hand.
103 #[serde(default, skip_serializing_if = "Option::is_none")]
104 pub identity: Option<DeviceIdentity>,
105 /// Every rebindable button's binding: a single [`Action`], or — for a
106 /// button in gesture mode — a [`Binding::Gesture`] per-direction map.
107 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
108 pub bindings: BTreeMap<ButtonId, Binding>,
109 /// Direction maps of buttons whose gesture mode is currently OFF, keyed by
110 /// button — pure UX memory so re-enabling restores the user's customized
111 /// arms exactly
112 /// (see [`Config::set_gesture_mode`](crate::config::Config::set_gesture_mode)).
113 /// Never dispatched: the runtime reads only `bindings`, where a demoted
114 /// button is a [`Binding::Single`] of its former `Click`.
115 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
116 pub disabled_gestures: BTreeMap<ButtonId, BTreeMap<GestureDirection, Action>>,
117 /// Per-application binding overlays (P1.4). Keyed by bundle identifier
118 /// (e.g. `"com.microsoft.VSCode"` on macOS). When the foreground app's
119 /// id matches a key here, those bindings take precedence; anything not
120 /// listed falls through to `bindings`. Deliberately `Action`-valued (not
121 /// `Binding`): a per-app override replaces the whole button with one
122 /// action, never a per-direction gesture overlay.
123 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
124 pub per_app_bindings: BTreeMap<String, BTreeMap<ButtonId, Action>>,
125 /// Host-rendered Actions Ring settings and complete per-application layouts.
126 #[serde(default, skip_serializing_if = "ActionRingConfig::is_default")]
127 pub action_ring: ActionRingConfig,
128 /// Ordered list of DPI presets cycled through by
129 /// [`Action::CycleDpiPresets`] and indexed by
130 /// [`Action::SetDpiPreset`]. Empty means "no presets configured" —
131 /// the cycle action becomes a no-op until the user adds at least one.
132 #[serde(
133 default,
134 deserialize_with = "deserialize_dpi_presets",
135 skip_serializing_if = "Vec::is_empty"
136 )]
137 pub dpi_presets: Vec<Dpi>,
138 /// The sensor DPI the user committed for this device. Persisted because
139 /// the value lives in device RAM and resets on a power cycle (#189); the
140 /// agent re-applies it when the device reconnects. `None` until the user
141 /// first changes DPI.
142 #[serde(
143 default,
144 deserialize_with = "deserialize_optional_dpi",
145 skip_serializing_if = "Option::is_none"
146 )]
147 pub dpi: Option<Dpi>,
148 /// Per-device RGB lighting (static color + brightness + on/off). `None`
149 /// until the user changes it, so it stays out of `config.toml` otherwise.
150 #[serde(default, skip_serializing_if = "Option::is_none")]
151 pub lighting: Option<Lighting>,
152 /// Per-device standalone-light settings. Separate from [`Self::lighting`],
153 /// which is the existing HID++ keyboard RGB configuration.
154 #[serde(default, skip_serializing_if = "Option::is_none")]
155 pub light: Option<LightSettings>,
156 /// Per-device SmartShift wheel configuration, re-applied on reconnect for
157 /// the same reason as [`Self::dpi`]. `None` until the user changes it.
158 #[serde(default, skip_serializing_if = "Option::is_none")]
159 pub smartshift: Option<SmartShift>,
160 /// Per-webcam UVC image controls (brightness/contrast/…). `None` until the
161 /// user adjusts one, so it stays out of `config.toml` otherwise.
162 #[serde(default, skip_serializing_if = "Option::is_none")]
163 pub camera_controls: Option<CameraControls>,
164 /// User-saved camera profiles (name → control snapshot). Built-in profiles
165 /// (Default / Streaming / Video call) live in the GUI, not here.
166 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
167 pub camera_profiles: BTreeMap<String, CameraControls>,
168 /// The camera profile last applied from the GUI, highlighted on reopen.
169 #[serde(default, skip_serializing_if = "Option::is_none")]
170 pub camera_profile: Option<String>,
171 /// Per-device thumb-wheel sensitivity override. `None` falls back to the
172 /// app-wide
173 /// [`AppSettings::thumbwheel_sensitivity`](crate::config::AppSettings::thumbwheel_sensitivity).
174 #[serde(default, skip_serializing_if = "Option::is_none")]
175 pub thumbwheel_sensitivity: Option<ThumbwheelSensitivity>,
176 /// Invert this device's scroll-wheel direction relative to the OS setting
177 /// (issue #126): on, a wheel tick scrolls the opposite way, so a user who
178 /// keeps macOS "natural scrolling" for the trackpad can have a traditional
179 /// "reverse" wheel on the mouse. Vertical only; the agent applies it through
180 /// the device's HID++ native wheel-inversion mode when supported. `false`
181 /// (default) is the native direction, and is omitted from `config.toml`.
182 #[serde(default, skip_serializing_if = "is_false")]
183 pub invert_scroll: bool,
184 /// Persisted HID++ `0x2121` wheel resolution. `None` leaves the device's
185 /// current resolution unmanaged and omits the field from `config.toml`.
186 #[serde(default, skip_serializing_if = "Option::is_none")]
187 pub scroll_resolution: Option<ScrollResolution>,
188 /// Physical config keys of pointing devices that follow this keyboard's
189 /// host switch channel. The relationship is keyboard-initiated: pressing
190 /// one of this device's host keys switches every listed target first, then
191 /// lets the keyboard leave the current host.
192 #[serde(default, skip_serializing_if = "Vec::is_empty")]
193 pub host_switch_targets: Vec<String>,
194 /// Keyboard Fn-lock state (HID++ fn inversion, `0x40a2`/`0x40a3`): `true`
195 /// means the F-row sends F1–F12 without holding Fn. The state lives in
196 /// device RAM per host, so the agent re-applies it on reconnect like
197 /// [`Self::dpi`]. `None` means "never set — leave the keyboard alone".
198 #[serde(default, skip_serializing_if = "Option::is_none")]
199 pub fn_lock: Option<bool>,
200}
201
202impl Default for DeviceConfig {
203 fn default() -> Self {
204 Self {
205 // A fresh entry (e.g. created by a first DPI write) must stay
206 // managed — `enabled: false` is an explicit user choice only.
207 enabled: true,
208 gesture_owner: None,
209 identity: None,
210 bindings: BTreeMap::new(),
211 disabled_gestures: BTreeMap::new(),
212 per_app_bindings: BTreeMap::new(),
213 action_ring: ActionRingConfig::default(),
214 dpi_presets: Vec::new(),
215 dpi: None,
216 lighting: None,
217 light: None,
218 smartshift: None,
219 camera_controls: None,
220 camera_profiles: BTreeMap::new(),
221 camera_profile: None,
222 thumbwheel_sensitivity: None,
223 invert_scroll: false,
224 scroll_resolution: None,
225 host_switch_targets: Vec::new(),
226 fn_lock: None,
227 }
228 }
229}
230
231/// `serde(default)` helper for `bool` fields that default to `true`.
232fn default_true() -> bool {
233 true
234}
235
236/// `skip_serializing_if` helper for `bool` fields whose default is `true`.
237#[allow(
238 clippy::trivially_copy_pass_by_ref,
239 reason = "serde's skip_serializing_if requires a fn(&T) -> bool signature"
240)]
241fn is_true(b: &bool) -> bool {
242 *b
243}
244
245/// `skip_serializing_if` helper for plain `bool` fields whose default is
246/// `false`: keeps an unset toggle out of `config.toml` entirely.
247#[allow(
248 clippy::trivially_copy_pass_by_ref,
249 reason = "serde's skip_serializing_if requires a fn(&T) -> bool signature"
250)]
251fn is_false(b: &bool) -> bool {
252 !*b
253}
254
255fn deserialize_dpi_presets<'de, D>(deserializer: D) -> Result<Vec<Dpi>, D::Error>
256where
257 D: serde::Deserializer<'de>,
258{
259 Vec::<u32>::deserialize(deserializer)?
260 .into_iter()
261 .map(|value| {
262 Dpi::try_from(value).map_err(|_| {
263 serde::de::Error::custom(format_args!(
264 "DPI must fit the HID++ 16-bit range, got {value}"
265 ))
266 })
267 })
268 .collect()
269}
270
271fn deserialize_optional_dpi<'de, D>(deserializer: D) -> Result<Option<Dpi>, D::Error>
272where
273 D: serde::Deserializer<'de>,
274{
275 let value = Option::<u32>::deserialize(deserializer)?;
276 value
277 .map(|value| {
278 Dpi::try_from(value).map_err(|_| {
279 serde::de::Error::custom(format_args!(
280 "DPI must fit the HID++ 16-bit range, got {value}"
281 ))
282 })
283 })
284 .transpose()
285}
286
287/// Deserialize-only shim that folds the pre-v2 `button_bindings` +
288/// `gesture_bindings` fields into [`DeviceConfig::bindings`]. Never serialized
289/// (only [`DeviceConfig`] is), so reading a legacy file and saving rewrites it
290/// in the v2 shape.
291#[derive(Deserialize)]
292#[serde(deny_unknown_fields)]
293struct RawDeviceConfig {
294 /// Explicit gesture owner (v2.1+). Absent on older configs → `None` → the
295 /// owner is inferred during the version-gated migration. A
296 /// present-but-invalid legacy value is tolerated as `None` for compatibility
297 /// with v3-and-older behavior; current schemas reject the field first.
298 #[serde(default, deserialize_with = "deserialize_gesture_owner")]
299 gesture_owner: Option<GestureOwner>,
300 #[serde(default)]
301 identity: Option<DeviceIdentity>,
302 /// v2 shape — present on already-migrated files; wins on any key collision.
303 #[serde(default)]
304 bindings: BTreeMap<ButtonId, Binding>,
305 /// v4 stash of turned-off gesture maps (see [`DeviceConfig::disabled_gestures`]).
306 #[serde(default)]
307 disabled_gestures: BTreeMap<ButtonId, BTreeMap<GestureDirection, Action>>,
308 /// Legacy v1 per-button single bindings.
309 #[serde(default)]
310 button_bindings: BTreeMap<ButtonId, Action>,
311 /// Legacy v1 flat gesture map (implicitly the gesture button's directions).
312 #[serde(default)]
313 gesture_bindings: BTreeMap<GestureDirection, Action>,
314 #[serde(default)]
315 per_app_bindings: BTreeMap<String, BTreeMap<ButtonId, Action>>,
316 #[serde(default)]
317 action_ring: ActionRingConfig,
318 #[serde(default, deserialize_with = "deserialize_dpi_presets")]
319 dpi_presets: Vec<Dpi>,
320 #[serde(default, deserialize_with = "deserialize_optional_dpi")]
321 dpi: Option<Dpi>,
322 #[serde(default)]
323 lighting: Option<Lighting>,
324 #[serde(default)]
325 light: Option<LightSettings>,
326 #[serde(default)]
327 smartshift: Option<SmartShift>,
328 #[serde(default)]
329 camera_controls: Option<CameraControls>,
330 #[serde(default)]
331 camera_profiles: BTreeMap<String, CameraControls>,
332 #[serde(default)]
333 camera_profile: Option<String>,
334 #[serde(default)]
335 thumbwheel_sensitivity: Option<ThumbwheelSensitivity>,
336 #[serde(default)]
337 invert_scroll: bool,
338 #[serde(default)]
339 scroll_resolution: Option<ScrollResolution>,
340 #[serde(default)]
341 host_switch_targets: Vec<String>,
342 #[serde(default)]
343 fn_lock: Option<bool>,
344 #[serde(default = "default_true")]
345 enabled: bool,
346}
347
348impl From<RawDeviceConfig> for DeviceConfig {
349 fn from(raw: RawDeviceConfig) -> Self {
350 let mut bindings = raw.bindings; // the v2 map wins on every key.
351
352 // Re-home the legacy flat gesture map under `GestureButton`. This MUST
353 // happen before folding `button_bindings`, so a legacy single
354 // `button_bindings[GestureButton]` entry coexisting with a
355 // `gesture_bindings` map cannot claim the slot first and silently drop
356 // the whole direction map (the pre-v2 rule was "gesture entries win").
357 if !raw.gesture_bindings.is_empty() {
358 bindings
359 .entry(ButtonId::GestureButton)
360 .or_insert_with(|| Binding::Gesture(raw.gesture_bindings));
361 }
362 for (button, action) in raw.button_bindings {
363 // A legacy `button_bindings[GestureButton]` is vestigial and must not
364 // become a `Binding::Single`: the gesture button never dispatched
365 // through the per-button map (it is not an OS-hook button, and its
366 // plain press routes through the gesture `Click` slot — see
367 // agent-core `bindings_for`). A `Single` here would be unreachable —
368 // the GUI hides it and the runtime ignores it — while folding it into
369 // `Click` would resurrect a dead binding as a behavior change. Drop
370 // it: the gesture map (re-homed above) already owns this button, and
371 // an absent entry falls back to the canonical default, exactly as
372 // pre-v2.
373 if button == ButtonId::GestureButton {
374 continue;
375 }
376 bindings.entry(button).or_insert(Binding::Single(action));
377 }
378
379 DeviceConfig {
380 enabled: raw.enabled,
381 gesture_owner: raw.gesture_owner,
382 identity: raw.identity.map(DeviceIdentity::without_unit_identifiers),
383 bindings,
384 disabled_gestures: raw.disabled_gestures,
385 per_app_bindings: raw.per_app_bindings,
386 action_ring: raw.action_ring,
387 dpi_presets: raw.dpi_presets,
388 dpi: raw.dpi,
389 lighting: raw.lighting,
390 light: raw.light,
391 smartshift: raw.smartshift,
392 camera_controls: raw.camera_controls,
393 camera_profiles: raw.camera_profiles,
394 camera_profile: raw.camera_profile,
395 thumbwheel_sensitivity: raw.thumbwheel_sensitivity,
396 invert_scroll: raw.invert_scroll,
397 scroll_resolution: raw.scroll_resolution,
398 host_switch_targets: raw.host_switch_targets,
399 fn_lock: raw.fn_lock,
400 }
401 }
402}
403
404#[cfg(test)]
405mod tests {
406 use super::DeviceConfig;
407
408 #[test]
409 fn host_switch_targets_round_trip_as_physical_keys() -> Result<(), Box<dyn std::error::Error>> {
410 let config: DeviceConfig = toml::from_str(
411 r#"host_switch_targets = [
412 "receiver:keyboard:slot:1",
413 "receiver:mouse:slot:2",
414]"#,
415 )?;
416
417 assert_eq!(
418 config.host_switch_targets,
419 ["receiver:keyboard:slot:1", "receiver:mouse:slot:2"]
420 );
421 let serialized = toml::to_string(&config)?;
422 assert!(serialized.contains("host_switch_targets"));
423 Ok(())
424 }
425}