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 deserialize_gesture_owner,
12};
13use crate::binding::{Action, Binding, ButtonId, GestureDirection};
14use crate::device::{Capabilities, DeviceKind, DeviceModelInfo, LightCapabilities};
15
16/// Last-known identity of a device, captured while it was online so the UI can
17/// render its card and the *correct* config panels before any live HID++ probe
18/// completes — or while the device is asleep and can't be probed at all.
19///
20/// Every field is a **static property of the model**, not of the current
21/// connection: an MX Master 3S has adjustable DPI whether or not it is awake.
22/// That is what makes this safe to persist — it never goes stale. It is also
23/// free of any per-unit identifier (no serial number, no unit id), so caching
24/// it adds no privacy surface beyond the `config_key` already used as the map
25/// key. Persisting identity is what stops a sleeping/just-booted mouse from
26/// vanishing from the device list (and losing its Pointer/Buttons panels)
27/// until a cold probe happens to win its race — see issue #159.
28#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
29pub struct DeviceIdentity {
30 /// The name shown in the carousel, as resolved from the asset registry the
31 /// last time the device was online.
32 pub display_name: String,
33 /// HID++ model identity from feature 0x0003, when available. Persisted so
34 /// the GUI can resolve the same curated asset while the device is asleep.
35 #[serde(default, skip_serializing_if = "Option::is_none")]
36 pub model_info: Option<DeviceModelInfo>,
37 /// Firmware codename, when available. Used as an asset-resolution hint and
38 /// as a readable fallback for devices without curated model metadata.
39 #[serde(default, skip_serializing_if = "Option::is_none")]
40 pub codename: Option<String>,
41 /// The device's resolved [`DeviceKind`] (asset registry preferred, HID++
42 /// classification as fallback).
43 pub kind: DeviceKind,
44 /// Configuration capabilities measured from the device's HID++ feature
45 /// table. This is the field that keeps a sleeping mouse's panels visible.
46 pub capabilities: Capabilities,
47 /// Standalone-light controls measured by its protocol driver, if this is
48 /// a non-HID++ light. Old configs omit this field.
49 #[serde(default, skip_serializing_if = "Option::is_none")]
50 pub light_capabilities: Option<LightCapabilities>,
51 /// Standalone driver family that produced this identity, when applicable.
52 /// Old configs and HID++ devices omit it.
53 #[serde(default, skip_serializing_if = "Option::is_none")]
54 pub driver_id: Option<String>,
55 /// Optional model-level identity in the OpenLogi asset registry. This is
56 /// not a physical-device key and never contains a serial or OS node id.
57 #[serde(default, skip_serializing_if = "Option::is_none")]
58 pub registry_model_id: Option<String>,
59}
60
61/// Settings scoped to a single physical device.
62///
63/// Deserialization goes through `RawDeviceConfig` (`#[serde(from)]`) so
64/// pre-v2 files — which split bindings across `button_bindings` +
65/// `gesture_bindings` — fold into the unified [`Self::bindings`] map. Only
66/// `bindings` is ever serialized, so a migrated file self-heals to the v2 shape
67/// on its next save.
68#[derive(Debug, Clone, Default, Serialize, Deserialize)]
69#[serde(from = "RawDeviceConfig")]
70pub struct DeviceConfig {
71 /// Which button owns the device's single gesture role, once the user has
72 /// chosen explicitly. Absent means "infer" (the dedicated HID++ gesture
73 /// button owns gestures if present) — see
74 /// [`Config::gesture_owner`](crate::config::Config::gesture_owner). Listed
75 /// first so it serializes as a scalar ahead of the `bindings` sub-table.
76 #[serde(default, skip_serializing_if = "Option::is_none")]
77 pub gesture_owner: Option<GestureOwner>,
78 /// Last-known identity (name / kind / capabilities), captured while the
79 /// device was online. Lets the UI render this device — with the right
80 /// config panels — on a cold start before any probe, or while it sleeps.
81 /// `None` for configs written before this field existed or by hand.
82 #[serde(default, skip_serializing_if = "Option::is_none")]
83 pub identity: Option<DeviceIdentity>,
84 /// Every rebindable button's binding: a single [`Action`], or — for the
85 /// gesture button (and, later, any raw-XY-capable button) — a
86 /// [`Binding::Gesture`] per-direction map.
87 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
88 pub bindings: BTreeMap<ButtonId, Binding>,
89 /// Per-application binding overlays (P1.4). Keyed by bundle identifier
90 /// (e.g. `"com.microsoft.VSCode"` on macOS). When the foreground app's
91 /// id matches a key here, those bindings take precedence; anything not
92 /// listed falls through to `bindings`. Deliberately `Action`-valued (not
93 /// `Binding`): a per-app override replaces the whole button with one
94 /// action, never a per-direction gesture overlay.
95 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
96 pub per_app_bindings: BTreeMap<String, BTreeMap<ButtonId, Action>>,
97 /// Ordered list of DPI presets cycled through by
98 /// [`Action::CycleDpiPresets`] and indexed by
99 /// [`Action::SetDpiPreset`]. Empty means "no presets configured" —
100 /// the cycle action becomes a no-op until the user adds at least one.
101 #[serde(default, skip_serializing_if = "Vec::is_empty")]
102 pub dpi_presets: Vec<u32>,
103 /// The sensor DPI the user committed for this device. Persisted because
104 /// the value lives in device RAM and resets on a power cycle (#189); the
105 /// agent re-applies it when the device reconnects. `None` until the user
106 /// first changes DPI.
107 #[serde(default, skip_serializing_if = "Option::is_none")]
108 pub dpi: Option<u32>,
109 /// Per-device RGB lighting (static color + brightness + on/off). `None`
110 /// until the user changes it, so it stays out of `config.toml` otherwise.
111 #[serde(default, skip_serializing_if = "Option::is_none")]
112 pub lighting: Option<Lighting>,
113 /// Per-device standalone-light settings. Separate from [`Self::lighting`],
114 /// which is the existing HID++ keyboard RGB configuration.
115 #[serde(default, skip_serializing_if = "Option::is_none")]
116 pub light: Option<LightSettings>,
117 /// Per-device SmartShift wheel configuration, re-applied on reconnect for
118 /// the same reason as [`Self::dpi`]. `None` until the user changes it.
119 #[serde(default, skip_serializing_if = "Option::is_none")]
120 pub smartshift: Option<SmartShift>,
121 /// Per-webcam UVC image controls (brightness/contrast/…). `None` until the
122 /// user adjusts one, so it stays out of `config.toml` otherwise.
123 #[serde(default, skip_serializing_if = "Option::is_none")]
124 pub camera_controls: Option<CameraControls>,
125 /// User-saved camera profiles (name → control snapshot). Built-in profiles
126 /// (Default / Streaming / Video call) live in the GUI, not here.
127 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
128 pub camera_profiles: BTreeMap<String, CameraControls>,
129 /// The camera profile last applied from the GUI, highlighted on reopen.
130 #[serde(default, skip_serializing_if = "Option::is_none")]
131 pub camera_profile: Option<String>,
132 /// Invert this device's scroll-wheel direction relative to the OS setting
133 /// (issue #126): on, a wheel tick scrolls the opposite way, so a user who
134 /// keeps macOS "natural scrolling" for the trackpad can have a traditional
135 /// "reverse" wheel on the mouse. Vertical only; the agent applies it through
136 /// the device's HID++ native wheel-inversion mode when supported. `false`
137 /// (default) is the native direction, and is omitted from `config.toml`.
138 #[serde(default, skip_serializing_if = "is_false")]
139 pub invert_scroll: bool,
140 /// Persisted HID++ `0x2121` wheel resolution. `None` leaves the device's
141 /// current resolution unmanaged and omits the field from `config.toml`.
142 #[serde(default, skip_serializing_if = "Option::is_none")]
143 pub scroll_resolution: Option<ScrollResolution>,
144 /// Physical config keys of pointing devices that follow this keyboard's
145 /// host switch channel. The relationship is keyboard-initiated: pressing
146 /// one of this device's host keys switches every listed target first, then
147 /// lets the keyboard leave the current host.
148 #[serde(default, skip_serializing_if = "Vec::is_empty")]
149 pub host_switch_targets: Vec<String>,
150 /// Keyboard Fn-lock state (HID++ fn inversion, `0x40a2`/`0x40a3`): `true`
151 /// means the F-row sends F1–F12 without holding Fn. The state lives in
152 /// device RAM per host, so the agent re-applies it on reconnect like
153 /// [`Self::dpi`]. `None` means "never set — leave the keyboard alone".
154 #[serde(default, skip_serializing_if = "Option::is_none")]
155 pub fn_lock: Option<bool>,
156}
157
158/// `skip_serializing_if` helper for plain `bool` fields whose default is
159/// `false`: keeps an unset toggle out of `config.toml` entirely.
160#[allow(
161 clippy::trivially_copy_pass_by_ref,
162 reason = "serde's skip_serializing_if requires a fn(&T) -> bool signature"
163)]
164fn is_false(b: &bool) -> bool {
165 !*b
166}
167
168/// Deserialize-only shim that folds the pre-v2 `button_bindings` +
169/// `gesture_bindings` fields into [`DeviceConfig::bindings`]. Never serialized
170/// (only [`DeviceConfig`] is), so reading a legacy file and saving rewrites it
171/// in the v2 shape.
172#[derive(Deserialize)]
173struct RawDeviceConfig {
174 /// Explicit gesture owner (v2.1+). Absent on older configs → `None` → the
175 /// owner is inferred in
176 /// [`Config::gesture_owner`](crate::config::Config::gesture_owner). A
177 /// present-but-invalid value is tolerated as `None` (infer), not a parse
178 /// error — see [`deserialize_gesture_owner`].
179 #[serde(default, deserialize_with = "deserialize_gesture_owner")]
180 gesture_owner: Option<GestureOwner>,
181 #[serde(default)]
182 identity: Option<DeviceIdentity>,
183 /// v2 shape — present on already-migrated files; wins on any key collision.
184 #[serde(default)]
185 bindings: BTreeMap<ButtonId, Binding>,
186 /// Legacy v1 per-button single bindings.
187 #[serde(default)]
188 button_bindings: BTreeMap<ButtonId, Action>,
189 /// Legacy v1 flat gesture map (implicitly the gesture button's directions).
190 #[serde(default)]
191 gesture_bindings: BTreeMap<GestureDirection, Action>,
192 #[serde(default)]
193 per_app_bindings: BTreeMap<String, BTreeMap<ButtonId, Action>>,
194 #[serde(default)]
195 dpi_presets: Vec<u32>,
196 #[serde(default)]
197 dpi: Option<u32>,
198 #[serde(default)]
199 lighting: Option<Lighting>,
200 #[serde(default)]
201 light: Option<LightSettings>,
202 #[serde(default)]
203 smartshift: Option<SmartShift>,
204 #[serde(default)]
205 camera_controls: Option<CameraControls>,
206 #[serde(default)]
207 camera_profiles: BTreeMap<String, CameraControls>,
208 #[serde(default)]
209 camera_profile: Option<String>,
210 #[serde(default)]
211 invert_scroll: bool,
212 #[serde(default)]
213 scroll_resolution: Option<ScrollResolution>,
214 #[serde(default)]
215 host_switch_targets: Vec<String>,
216 #[serde(default)]
217 fn_lock: Option<bool>,
218}
219
220impl From<RawDeviceConfig> for DeviceConfig {
221 fn from(raw: RawDeviceConfig) -> Self {
222 let mut bindings = raw.bindings; // the v2 map wins on every key.
223
224 // Re-home the legacy flat gesture map under `GestureButton`. This MUST
225 // happen before folding `button_bindings`, so a legacy single
226 // `button_bindings[GestureButton]` entry coexisting with a
227 // `gesture_bindings` map cannot claim the slot first and silently drop
228 // the whole direction map (the pre-v2 rule was "gesture entries win").
229 if !raw.gesture_bindings.is_empty() {
230 bindings
231 .entry(ButtonId::GestureButton)
232 .or_insert_with(|| Binding::Gesture(raw.gesture_bindings));
233 }
234 for (button, action) in raw.button_bindings {
235 // A legacy `button_bindings[GestureButton]` is vestigial and must not
236 // become a `Binding::Single`: the gesture button never dispatched
237 // through the per-button map (it is not an OS-hook button, and its
238 // plain press routes through the gesture `Click` slot — see
239 // agent-core `bindings_for`). A `Single` here would be unreachable —
240 // the GUI hides it and the runtime ignores it — while folding it into
241 // `Click` would resurrect a dead binding as a behavior change. Drop
242 // it: the gesture map (re-homed above) already owns this button, and
243 // an absent entry falls back to the canonical default, exactly as
244 // pre-v2.
245 if button == ButtonId::GestureButton {
246 continue;
247 }
248 bindings.entry(button).or_insert(Binding::Single(action));
249 }
250
251 DeviceConfig {
252 gesture_owner: raw.gesture_owner,
253 identity: raw.identity,
254 bindings,
255 per_app_bindings: raw.per_app_bindings,
256 dpi_presets: raw.dpi_presets,
257 dpi: raw.dpi,
258 lighting: raw.lighting,
259 light: raw.light,
260 smartshift: raw.smartshift,
261 camera_controls: raw.camera_controls,
262 camera_profiles: raw.camera_profiles,
263 camera_profile: raw.camera_profile,
264 invert_scroll: raw.invert_scroll,
265 scroll_resolution: raw.scroll_resolution,
266 host_switch_targets: raw.host_switch_targets,
267 fn_lock: raw.fn_lock,
268 }
269 }
270}
271
272#[cfg(test)]
273mod tests {
274 use super::DeviceConfig;
275
276 #[test]
277 fn host_switch_targets_round_trip_as_physical_keys() -> Result<(), Box<dyn std::error::Error>> {
278 let config: DeviceConfig = toml::from_str(
279 r#"host_switch_targets = [
280 "receiver:keyboard:slot:1",
281 "receiver:mouse:slot:2",
282]"#,
283 )?;
284
285 assert_eq!(
286 config.host_switch_targets,
287 ["receiver:keyboard:slot:1", "receiver:mouse:slot:2"]
288 );
289 let serialized = toml::to_string(&config)?;
290 assert!(serialized.contains("host_switch_targets"));
291 Ok(())
292 }
293}