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::{GestureOwner, Lighting, SmartShift, deserialize_gesture_owner};
10use crate::binding::{Action, Binding, ButtonId, GestureDirection};
11use crate::device::{Capabilities, DeviceKind, DeviceModelInfo};
12
13/// Last-known identity of a device, captured while it was online so the UI can
14/// render its card and the *correct* config panels before any live HID++ probe
15/// completes — or while the device is asleep and can't be probed at all.
16///
17/// Every field is a **static property of the model**, not of the current
18/// connection: an MX Master 3S has adjustable DPI whether or not it is awake.
19/// That is what makes this safe to persist — it never goes stale. It is also
20/// free of any per-unit identifier (no serial number, no unit id), so caching
21/// it adds no privacy surface beyond the `config_key` already used as the map
22/// key. Persisting identity is what stops a sleeping/just-booted mouse from
23/// vanishing from the device list (and losing its Pointer/Buttons panels)
24/// until a cold probe happens to win its race — see issue #159.
25#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
26pub struct DeviceIdentity {
27 /// The name shown in the carousel, as resolved from the asset registry the
28 /// last time the device was online.
29 pub display_name: String,
30 /// HID++ model identity from feature 0x0003, when available. Persisted so
31 /// the GUI can resolve the same curated asset while the device is asleep.
32 #[serde(default, skip_serializing_if = "Option::is_none")]
33 pub model_info: Option<DeviceModelInfo>,
34 /// Firmware codename, when available. Used as an asset-resolution hint and
35 /// as a readable fallback for devices without curated model metadata.
36 #[serde(default, skip_serializing_if = "Option::is_none")]
37 pub codename: Option<String>,
38 /// The device's resolved [`DeviceKind`] (asset registry preferred, HID++
39 /// classification as fallback).
40 pub kind: DeviceKind,
41 /// Configuration capabilities measured from the device's HID++ feature
42 /// table. This is the field that keeps a sleeping mouse's panels visible.
43 pub capabilities: Capabilities,
44}
45
46/// Settings scoped to a single physical device.
47///
48/// Deserialization goes through `RawDeviceConfig` (`#[serde(from)]`) so
49/// pre-v2 files — which split bindings across `button_bindings` +
50/// `gesture_bindings` — fold into the unified [`Self::bindings`] map. Only
51/// `bindings` is ever serialized, so a migrated file self-heals to the v2 shape
52/// on its next save.
53#[derive(Debug, Clone, Default, Serialize, Deserialize)]
54#[serde(from = "RawDeviceConfig")]
55pub struct DeviceConfig {
56 /// Which button owns the device's single gesture role, once the user has
57 /// chosen explicitly. Absent means "infer" (the dedicated HID++ gesture
58 /// button owns gestures if present) — see
59 /// [`Config::gesture_owner`](crate::config::Config::gesture_owner). Listed
60 /// first so it serializes as a scalar ahead of the `bindings` sub-table.
61 #[serde(default, skip_serializing_if = "Option::is_none")]
62 pub gesture_owner: Option<GestureOwner>,
63 /// Last-known identity (name / kind / capabilities), captured while the
64 /// device was online. Lets the UI render this device — with the right
65 /// config panels — on a cold start before any probe, or while it sleeps.
66 /// `None` for configs written before this field existed or by hand.
67 #[serde(default, skip_serializing_if = "Option::is_none")]
68 pub identity: Option<DeviceIdentity>,
69 /// Every rebindable button's binding: a single [`Action`], or — for the
70 /// gesture button (and, later, any raw-XY-capable button) — a
71 /// [`Binding::Gesture`] per-direction map.
72 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
73 pub bindings: BTreeMap<ButtonId, Binding>,
74 /// Per-application binding overlays (P1.4). Keyed by bundle identifier
75 /// (e.g. `"com.microsoft.VSCode"` on macOS). When the foreground app's
76 /// id matches a key here, those bindings take precedence; anything not
77 /// listed falls through to `bindings`. Deliberately `Action`-valued (not
78 /// `Binding`): a per-app override replaces the whole button with one
79 /// action, never a per-direction gesture overlay.
80 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
81 pub per_app_bindings: BTreeMap<String, BTreeMap<ButtonId, Action>>,
82 /// Ordered list of DPI presets cycled through by
83 /// [`Action::CycleDpiPresets`] and indexed by
84 /// [`Action::SetDpiPreset`]. Empty means "no presets configured" —
85 /// the cycle action becomes a no-op until the user adds at least one.
86 #[serde(default, skip_serializing_if = "Vec::is_empty")]
87 pub dpi_presets: Vec<u32>,
88 /// The sensor DPI the user committed for this device. Persisted because
89 /// the value lives in device RAM and resets on a power cycle (#189); the
90 /// agent re-applies it when the device reconnects. `None` until the user
91 /// first changes DPI.
92 #[serde(default, skip_serializing_if = "Option::is_none")]
93 pub dpi: Option<u32>,
94 /// Per-device RGB lighting (static color + brightness + on/off). `None`
95 /// until the user changes it, so it stays out of `config.toml` otherwise.
96 #[serde(default, skip_serializing_if = "Option::is_none")]
97 pub lighting: Option<Lighting>,
98 /// Per-device SmartShift wheel configuration, re-applied on reconnect for
99 /// the same reason as [`Self::dpi`]. `None` until the user changes it.
100 #[serde(default, skip_serializing_if = "Option::is_none")]
101 pub smartshift: Option<SmartShift>,
102 /// Invert this device's scroll-wheel direction relative to the OS setting
103 /// (issue #126): on, a wheel tick scrolls the opposite way, so a user who
104 /// keeps macOS "natural scrolling" for the trackpad can have a traditional
105 /// "reverse" wheel on the mouse. Vertical only; the agent applies it through
106 /// the device's HID++ native wheel-inversion mode when supported. `false`
107 /// (default) is the native direction, and is omitted from `config.toml`.
108 #[serde(default, skip_serializing_if = "is_false")]
109 pub invert_scroll: bool,
110}
111
112/// `skip_serializing_if` helper for plain `bool` fields whose default is
113/// `false`: keeps an unset toggle out of `config.toml` entirely.
114#[allow(
115 clippy::trivially_copy_pass_by_ref,
116 reason = "serde's skip_serializing_if requires a fn(&T) -> bool signature"
117)]
118fn is_false(b: &bool) -> bool {
119 !*b
120}
121
122/// Deserialize-only shim that folds the pre-v2 `button_bindings` +
123/// `gesture_bindings` fields into [`DeviceConfig::bindings`]. Never serialized
124/// (only [`DeviceConfig`] is), so reading a legacy file and saving rewrites it
125/// in the v2 shape.
126#[derive(Deserialize)]
127struct RawDeviceConfig {
128 /// Explicit gesture owner (v2.1+). Absent on older configs → `None` → the
129 /// owner is inferred in
130 /// [`Config::gesture_owner`](crate::config::Config::gesture_owner). A
131 /// present-but-invalid value is tolerated as `None` (infer), not a parse
132 /// error — see [`deserialize_gesture_owner`].
133 #[serde(default, deserialize_with = "deserialize_gesture_owner")]
134 gesture_owner: Option<GestureOwner>,
135 #[serde(default)]
136 identity: Option<DeviceIdentity>,
137 /// v2 shape — present on already-migrated files; wins on any key collision.
138 #[serde(default)]
139 bindings: BTreeMap<ButtonId, Binding>,
140 /// Legacy v1 per-button single bindings.
141 #[serde(default)]
142 button_bindings: BTreeMap<ButtonId, Action>,
143 /// Legacy v1 flat gesture map (implicitly the gesture button's directions).
144 #[serde(default)]
145 gesture_bindings: BTreeMap<GestureDirection, Action>,
146 #[serde(default)]
147 per_app_bindings: BTreeMap<String, BTreeMap<ButtonId, Action>>,
148 #[serde(default)]
149 dpi_presets: Vec<u32>,
150 #[serde(default)]
151 dpi: Option<u32>,
152 #[serde(default)]
153 lighting: Option<Lighting>,
154 #[serde(default)]
155 smartshift: Option<SmartShift>,
156 #[serde(default)]
157 invert_scroll: bool,
158}
159
160impl From<RawDeviceConfig> for DeviceConfig {
161 fn from(raw: RawDeviceConfig) -> Self {
162 let mut bindings = raw.bindings; // the v2 map wins on every key.
163
164 // Re-home the legacy flat gesture map under `GestureButton`. This MUST
165 // happen before folding `button_bindings`, so a legacy single
166 // `button_bindings[GestureButton]` entry coexisting with a
167 // `gesture_bindings` map cannot claim the slot first and silently drop
168 // the whole direction map (the pre-v2 rule was "gesture entries win").
169 if !raw.gesture_bindings.is_empty() {
170 bindings
171 .entry(ButtonId::GestureButton)
172 .or_insert_with(|| Binding::Gesture(raw.gesture_bindings));
173 }
174 for (button, action) in raw.button_bindings {
175 // A legacy `button_bindings[GestureButton]` is vestigial and must not
176 // become a `Binding::Single`: the gesture button never dispatched
177 // through the per-button map (it is not an OS-hook button, and its
178 // plain press routes through the gesture `Click` slot — see
179 // agent-core `bindings_for`). A `Single` here would be unreachable —
180 // the GUI hides it and the runtime ignores it — while folding it into
181 // `Click` would resurrect a dead binding as a behavior change. Drop
182 // it: the gesture map (re-homed above) already owns this button, and
183 // an absent entry falls back to the canonical default, exactly as
184 // pre-v2.
185 if button == ButtonId::GestureButton {
186 continue;
187 }
188 bindings.entry(button).or_insert(Binding::Single(action));
189 }
190
191 DeviceConfig {
192 gesture_owner: raw.gesture_owner,
193 identity: raw.identity,
194 bindings,
195 per_app_bindings: raw.per_app_bindings,
196 dpi_presets: raw.dpi_presets,
197 dpi: raw.dpi,
198 lighting: raw.lighting,
199 smartshift: raw.smartshift,
200 invert_scroll: raw.invert_scroll,
201 }
202 }
203}