openlogi-core 0.7.1

Core types, config, and paths for OpenLogi. No I/O specifics.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
//! Per-device config: [`DeviceIdentity`], [`DeviceConfig`], and the
//! [`RawDeviceConfig`] migration shim that folds pre-v2 files into the
//! unified `bindings` map.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

use super::settings::{
    CameraControls, GestureOwner, LightSettings, Lighting, ScrollResolution, SmartShift,
    deserialize_gesture_owner, deserialize_optional_thumbwheel_sensitivity,
};
use crate::binding::{Action, ActionRingConfig, Binding, ButtonId, GestureDirection};
use crate::device::{Capabilities, DeviceKind, DeviceModelInfo, LightCapabilities};

/// Last-known identity of a device, captured while it was online so the UI can
/// render its card and the *correct* config panels before any live HID++ probe
/// completes — or while the device is asleep and can't be probed at all.
///
/// Every field is a **static property of the model**, not of the current
/// connection: an MX Master 3S has adjustable DPI whether or not it is awake.
/// That is what makes this safe to persist — it never goes stale. It is also
/// free of any per-unit identifier (no serial number, no unit id), so caching
/// it adds no privacy surface beyond the `config_key` already used as the map
/// key. Persisting identity is what stops a sleeping/just-booted mouse from
/// vanishing from the device list (and losing its Pointer/Buttons panels)
/// until a cold probe happens to win its race — see issue #159.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DeviceIdentity {
    /// The name shown in the carousel, as resolved from the asset registry the
    /// last time the device was online.
    pub display_name: String,
    /// HID++ model identity from feature 0x0003, when available. Persisted so
    /// the GUI can resolve the same curated asset while the device is asleep.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model_info: Option<DeviceModelInfo>,
    /// Firmware codename, when available. Used as an asset-resolution hint and
    /// as a readable fallback for devices without curated model metadata.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub codename: Option<String>,
    /// The device's resolved [`DeviceKind`] (asset registry preferred, HID++
    /// classification as fallback).
    pub kind: DeviceKind,
    /// Configuration capabilities measured from the device's HID++ feature
    /// table. This is the field that keeps a sleeping mouse's panels visible.
    pub capabilities: Capabilities,
    /// Standalone-light controls measured by its protocol driver, if this is
    /// a non-HID++ light. Old configs omit this field.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub light_capabilities: Option<LightCapabilities>,
    /// Standalone driver family that produced this identity, when applicable.
    /// Old configs and HID++ devices omit it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub driver_id: Option<String>,
    /// Optional model-level identity in the OpenLogi asset registry. This is
    /// not a physical-device key and never contains a serial or OS node id.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub registry_model_id: Option<String>,
}

impl DeviceIdentity {
    /// Remove per-unit identifiers before this model snapshot is persisted.
    #[must_use]
    pub fn without_unit_identifiers(mut self) -> Self {
        if let Some(model) = &mut self.model_info {
            model.serial_number = None;
            model.unit_id = [0; 4];
        }
        self
    }
}

/// Settings scoped to a single physical device.
///
/// Deserialization goes through `RawDeviceConfig` (`#[serde(from)]`) so
/// pre-v2 files — which split bindings across `button_bindings` +
/// `gesture_bindings` — fold into the unified [`Self::bindings`] map. Only
/// `bindings` is ever serialized, so a migrated file is rewritten to the v2
/// shape on its next save.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(from = "RawDeviceConfig")]
pub struct DeviceConfig {
    /// Whether OpenLogi manages this device at all. `false` leaves the device
    /// fully native: no capture session (no HID++ diversion of any control)
    /// and no volatile-settings re-apply on reconnect. Defaults to `true` and
    /// is only serialized when disabled.
    #[serde(default = "default_true", skip_serializing_if = "is_true")]
    pub enabled: bool,
    /// Legacy owner-lock carrier, deserialize-only: the v3-and-older
    /// `gesture_owner` field, held here just long enough for the version-gated
    /// load migration (`Config::migrate_owner_locked_gestures`) to consume it.
    /// Never serialized — since v4 the binding shape is the whole truth
    /// (gesture mode is per-button; see
    /// [`Config::set_gesture_mode`](crate::config::Config::set_gesture_mode)).
    #[serde(skip_serializing)]
    pub(super) gesture_owner: Option<GestureOwner>,
    /// Last-known identity (name / kind / capabilities), captured while the
    /// device was online. Lets the UI render this device — with the right
    /// config panels — on a cold start before any probe, or while it sleeps.
    /// `None` for configs written before this field existed or by hand.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub identity: Option<DeviceIdentity>,
    /// Every rebindable button's binding: a single [`Action`], or — for a
    /// button in gesture mode — a [`Binding::Gesture`] per-direction map.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub bindings: BTreeMap<ButtonId, Binding>,
    /// Direction maps of buttons whose gesture mode is currently OFF, keyed by
    /// button — pure UX memory so re-enabling restores the user's customized
    /// arms exactly
    /// (see [`Config::set_gesture_mode`](crate::config::Config::set_gesture_mode)).
    /// Never dispatched: the runtime reads only `bindings`, where a demoted
    /// button is a [`Binding::Single`] of its former `Click`.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub disabled_gestures: BTreeMap<ButtonId, BTreeMap<GestureDirection, Action>>,
    /// Per-application binding overlays (P1.4). Keyed by bundle identifier
    /// (e.g. `"com.microsoft.VSCode"` on macOS). When the foreground app's
    /// id matches a key here, those bindings take precedence; anything not
    /// listed falls through to `bindings`. Deliberately `Action`-valued (not
    /// `Binding`): a per-app override replaces the whole button with one
    /// action, never a per-direction gesture overlay.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub per_app_bindings: BTreeMap<String, BTreeMap<ButtonId, Action>>,
    /// Host-rendered Actions Ring settings and complete per-application layouts.
    #[serde(default, skip_serializing_if = "ActionRingConfig::is_default")]
    pub action_ring: ActionRingConfig,
    /// Ordered list of DPI presets cycled through by
    /// [`Action::CycleDpiPresets`] and indexed by
    /// [`Action::SetDpiPreset`]. Empty means "no presets configured" —
    /// the cycle action becomes a no-op until the user adds at least one.
    #[serde(
        default,
        deserialize_with = "deserialize_dpi_presets",
        skip_serializing_if = "Vec::is_empty"
    )]
    pub dpi_presets: Vec<u32>,
    /// The sensor DPI the user committed for this device. Persisted because
    /// the value lives in device RAM and resets on a power cycle (#189); the
    /// agent re-applies it when the device reconnects. `None` until the user
    /// first changes DPI.
    #[serde(
        default,
        deserialize_with = "deserialize_optional_dpi",
        skip_serializing_if = "Option::is_none"
    )]
    pub dpi: Option<u32>,
    /// Per-device RGB lighting (static color + brightness + on/off). `None`
    /// until the user changes it, so it stays out of `config.toml` otherwise.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lighting: Option<Lighting>,
    /// Per-device standalone-light settings. Separate from [`Self::lighting`],
    /// which is the existing HID++ keyboard RGB configuration.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub light: Option<LightSettings>,
    /// Per-device SmartShift wheel configuration, re-applied on reconnect for
    /// the same reason as [`Self::dpi`]. `None` until the user changes it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub smartshift: Option<SmartShift>,
    /// Per-webcam UVC image controls (brightness/contrast/…). `None` until the
    /// user adjusts one, so it stays out of `config.toml` otherwise.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub camera_controls: Option<CameraControls>,
    /// User-saved camera profiles (name → control snapshot). Built-in profiles
    /// (Default / Streaming / Video call) live in the GUI, not here.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub camera_profiles: BTreeMap<String, CameraControls>,
    /// The camera profile last applied from the GUI, highlighted on reopen.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub camera_profile: Option<String>,
    /// Per-device thumb-wheel sensitivity override. `None` falls back to the
    /// app-wide
    /// [`AppSettings::thumbwheel_sensitivity`](crate::config::AppSettings::thumbwheel_sensitivity).
    #[serde(
        default,
        deserialize_with = "deserialize_optional_thumbwheel_sensitivity",
        skip_serializing_if = "Option::is_none"
    )]
    pub thumbwheel_sensitivity: Option<i32>,
    /// Invert this device's scroll-wheel direction relative to the OS setting
    /// (issue #126): on, a wheel tick scrolls the opposite way, so a user who
    /// keeps macOS "natural scrolling" for the trackpad can have a traditional
    /// "reverse" wheel on the mouse. Vertical only; the agent applies it through
    /// the device's HID++ native wheel-inversion mode when supported. `false`
    /// (default) is the native direction, and is omitted from `config.toml`.
    #[serde(default, skip_serializing_if = "is_false")]
    pub invert_scroll: bool,
    /// Persisted HID++ `0x2121` wheel resolution. `None` leaves the device's
    /// current resolution unmanaged and omits the field from `config.toml`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub scroll_resolution: Option<ScrollResolution>,
    /// Physical config keys of pointing devices that follow this keyboard's
    /// host switch channel. The relationship is keyboard-initiated: pressing
    /// one of this device's host keys switches every listed target first, then
    /// lets the keyboard leave the current host.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub host_switch_targets: Vec<String>,
    /// Keyboard Fn-lock state (HID++ fn inversion, `0x40a2`/`0x40a3`): `true`
    /// means the F-row sends F1–F12 without holding Fn. The state lives in
    /// device RAM per host, so the agent re-applies it on reconnect like
    /// [`Self::dpi`]. `None` means "never set — leave the keyboard alone".
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fn_lock: Option<bool>,
}

impl Default for DeviceConfig {
    fn default() -> Self {
        Self {
            // A fresh entry (e.g. created by a first DPI write) must stay
            // managed — `enabled: false` is an explicit user choice only.
            enabled: true,
            gesture_owner: None,
            identity: None,
            bindings: BTreeMap::new(),
            disabled_gestures: BTreeMap::new(),
            per_app_bindings: BTreeMap::new(),
            action_ring: ActionRingConfig::default(),
            dpi_presets: Vec::new(),
            dpi: None,
            lighting: None,
            light: None,
            smartshift: None,
            camera_controls: None,
            camera_profiles: BTreeMap::new(),
            camera_profile: None,
            thumbwheel_sensitivity: None,
            invert_scroll: false,
            scroll_resolution: None,
            host_switch_targets: Vec::new(),
            fn_lock: None,
        }
    }
}

/// `serde(default)` helper for `bool` fields that default to `true`.
fn default_true() -> bool {
    true
}

/// `skip_serializing_if` helper for `bool` fields whose default is `true`.
#[allow(
    clippy::trivially_copy_pass_by_ref,
    reason = "serde's skip_serializing_if requires a fn(&T) -> bool signature"
)]
fn is_true(b: &bool) -> bool {
    *b
}

/// `skip_serializing_if` helper for plain `bool` fields whose default is
/// `false`: keeps an unset toggle out of `config.toml` entirely.
#[allow(
    clippy::trivially_copy_pass_by_ref,
    reason = "serde's skip_serializing_if requires a fn(&T) -> bool signature"
)]
fn is_false(b: &bool) -> bool {
    !*b
}

fn deserialize_dpi_presets<'de, D>(deserializer: D) -> Result<Vec<u32>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let values = Vec::<u32>::deserialize(deserializer)?;
    if let Some(value) = values.iter().find(|value| u16::try_from(**value).is_err()) {
        return Err(serde::de::Error::custom(format_args!(
            "DPI must fit the HID++ 16-bit range, got {value}"
        )));
    }
    Ok(values)
}

fn deserialize_optional_dpi<'de, D>(deserializer: D) -> Result<Option<u32>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let value = Option::<u32>::deserialize(deserializer)?;
    if let Some(value) = value
        && u16::try_from(value).is_err()
    {
        return Err(serde::de::Error::custom(format_args!(
            "DPI must fit the HID++ 16-bit range, got {value}"
        )));
    }
    Ok(value)
}

/// Deserialize-only shim that folds the pre-v2 `button_bindings` +
/// `gesture_bindings` fields into [`DeviceConfig::bindings`]. Never serialized
/// (only [`DeviceConfig`] is), so reading a legacy file and saving rewrites it
/// in the v2 shape.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawDeviceConfig {
    /// Explicit gesture owner (v2.1+). Absent on older configs → `None` → the
    /// owner is inferred during the version-gated migration. A
    /// present-but-invalid legacy value is tolerated as `None` for compatibility
    /// with v3-and-older behavior; current schemas reject the field first.
    #[serde(default, deserialize_with = "deserialize_gesture_owner")]
    gesture_owner: Option<GestureOwner>,
    #[serde(default)]
    identity: Option<DeviceIdentity>,
    /// v2 shape — present on already-migrated files; wins on any key collision.
    #[serde(default)]
    bindings: BTreeMap<ButtonId, Binding>,
    /// v4 stash of turned-off gesture maps (see [`DeviceConfig::disabled_gestures`]).
    #[serde(default)]
    disabled_gestures: BTreeMap<ButtonId, BTreeMap<GestureDirection, Action>>,
    /// Legacy v1 per-button single bindings.
    #[serde(default)]
    button_bindings: BTreeMap<ButtonId, Action>,
    /// Legacy v1 flat gesture map (implicitly the gesture button's directions).
    #[serde(default)]
    gesture_bindings: BTreeMap<GestureDirection, Action>,
    #[serde(default)]
    per_app_bindings: BTreeMap<String, BTreeMap<ButtonId, Action>>,
    #[serde(default)]
    action_ring: ActionRingConfig,
    #[serde(default, deserialize_with = "deserialize_dpi_presets")]
    dpi_presets: Vec<u32>,
    #[serde(default, deserialize_with = "deserialize_optional_dpi")]
    dpi: Option<u32>,
    #[serde(default)]
    lighting: Option<Lighting>,
    #[serde(default)]
    light: Option<LightSettings>,
    #[serde(default)]
    smartshift: Option<SmartShift>,
    #[serde(default)]
    camera_controls: Option<CameraControls>,
    #[serde(default)]
    camera_profiles: BTreeMap<String, CameraControls>,
    #[serde(default)]
    camera_profile: Option<String>,
    #[serde(
        default,
        deserialize_with = "deserialize_optional_thumbwheel_sensitivity"
    )]
    thumbwheel_sensitivity: Option<i32>,
    #[serde(default)]
    invert_scroll: bool,
    #[serde(default)]
    scroll_resolution: Option<ScrollResolution>,
    #[serde(default)]
    host_switch_targets: Vec<String>,
    #[serde(default)]
    fn_lock: Option<bool>,
    #[serde(default = "default_true")]
    enabled: bool,
}

impl From<RawDeviceConfig> for DeviceConfig {
    fn from(raw: RawDeviceConfig) -> Self {
        let mut bindings = raw.bindings; // the v2 map wins on every key.

        // Re-home the legacy flat gesture map under `GestureButton`. This MUST
        // happen before folding `button_bindings`, so a legacy single
        // `button_bindings[GestureButton]` entry coexisting with a
        // `gesture_bindings` map cannot claim the slot first and silently drop
        // the whole direction map (the pre-v2 rule was "gesture entries win").
        if !raw.gesture_bindings.is_empty() {
            bindings
                .entry(ButtonId::GestureButton)
                .or_insert_with(|| Binding::Gesture(raw.gesture_bindings));
        }
        for (button, action) in raw.button_bindings {
            // A legacy `button_bindings[GestureButton]` is vestigial and must not
            // become a `Binding::Single`: the gesture button never dispatched
            // through the per-button map (it is not an OS-hook button, and its
            // plain press routes through the gesture `Click` slot — see
            // agent-core `bindings_for`). A `Single` here would be unreachable —
            // the GUI hides it and the runtime ignores it — while folding it into
            // `Click` would resurrect a dead binding as a behavior change. Drop
            // it: the gesture map (re-homed above) already owns this button, and
            // an absent entry falls back to the canonical default, exactly as
            // pre-v2.
            if button == ButtonId::GestureButton {
                continue;
            }
            bindings.entry(button).or_insert(Binding::Single(action));
        }

        DeviceConfig {
            enabled: raw.enabled,
            gesture_owner: raw.gesture_owner,
            identity: raw.identity.map(DeviceIdentity::without_unit_identifiers),
            bindings,
            disabled_gestures: raw.disabled_gestures,
            per_app_bindings: raw.per_app_bindings,
            action_ring: raw.action_ring,
            dpi_presets: raw.dpi_presets,
            dpi: raw.dpi,
            lighting: raw.lighting,
            light: raw.light,
            smartshift: raw.smartshift,
            camera_controls: raw.camera_controls,
            camera_profiles: raw.camera_profiles,
            camera_profile: raw.camera_profile,
            thumbwheel_sensitivity: raw.thumbwheel_sensitivity,
            invert_scroll: raw.invert_scroll,
            scroll_resolution: raw.scroll_resolution,
            host_switch_targets: raw.host_switch_targets,
            fn_lock: raw.fn_lock,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::DeviceConfig;

    #[test]
    fn host_switch_targets_round_trip_as_physical_keys() -> Result<(), Box<dyn std::error::Error>> {
        let config: DeviceConfig = toml::from_str(
            r#"host_switch_targets = [
  "receiver:keyboard:slot:1",
  "receiver:mouse:slot:2",
]"#,
        )?;

        assert_eq!(
            config.host_switch_targets,
            ["receiver:keyboard:slot:1", "receiver:mouse:slot:2"]
        );
        let serialized = toml::to_string(&config)?;
        assert!(serialized.contains("host_switch_targets"));
        Ok(())
    }
}