Skip to main content

openlogi_core/
config.rs

1//! User configuration, persisted as TOML at the platform-standard config
2//! path.
3//!
4//! Per-device state (button bindings, …) lives under the
5//! [`Config::devices`] map, keyed by the device's own identity such as
6//! `"unit:6be9d300"` — or, for a device that reports none, by the route it was
7//! reached on, such as `"receiver:abc123:slot:2"`. Schema migrations branch on
8//! [`Config::schema_version`].
9
10use std::collections::BTreeMap;
11
12use serde::{Deserialize, Serialize};
13
14mod button_map;
15mod device;
16#[cfg(feature = "fs")]
17mod file;
18mod function_key;
19mod gestures;
20mod identity;
21mod key_trigger;
22mod migrate;
23mod per_app;
24mod per_device;
25mod settings;
26
27// Stacked, not `all(test, …)`: clippy reads the combined form as a test
28// outside a test module and withdraws the `unwrap`/`expect` exemption.
29#[cfg(test)]
30#[cfg(feature = "fs")]
31mod tests;
32
33pub use device::{DeviceConfig, DeviceIdentity, LinkConfig, LinkOverrides};
34#[cfg(feature = "fs")]
35pub use file::{ConfigError, ConfigFile};
36#[cfg(all(test, feature = "fs"))]
37use file::{backup_existing_config, config_backup_path};
38pub use function_key::FunctionKey;
39pub use identity::canonical_device_key;
40pub use key_trigger::{KeyModifiers, KeyTrigger, KeyboardConfig, ParseTriggerError};
41pub use settings::LightSettings;
42pub use settings::{
43    AppIcon, AppSettings, Appearance, AssetSourcePreference, CameraControls, DeviceViewMode,
44    Lighting, MouseProfileTarget, SMARTSHIFT_AUTO_DISENGAGE_DEFAULT, SMARTSHIFT_MIN_AUTO_DISENGAGE,
45    ScrollResolution, SmartShift, ThumbwheelSensitivity, UiScale, VerticalScrollSensitivity,
46    WheelMode,
47};
48
49use crate::binding::Action;
50#[cfg(all(test, feature = "fs"))]
51use crate::binding::{Binding, ButtonId, GestureDirection};
52/// The schema version the current build produces. Bumped whenever the
53/// persisted shape or enum vocabulary changes; readers inspect this value
54/// before consuming the rest of the file.
55///
56/// v7 aligns the thumb-wheel scroll defaults with its normalised physical
57/// direction. Pre-v7 explicit default pairs are migrated in device and
58/// per-application profiles so they remain native rather than becoming a
59/// reversal (see `Config::migrate_thumbwheel_native_direction`).
60///
61/// v6 adds threshold-based `{ short = ..., long = ... }` button bindings.
62///
63/// v5 also drops the transport prefix from `direct:` keys: `direct:046d:c08d:unit:6be9d300`
64/// names the mouse *and the cable it was plugged into*, so a device moved to a
65/// different route was silently orphaned from its settings.
66/// [`Config::migrate_transport_scoped_keys`] rewrites such a key to its bare
67/// identity fragment (`unit:6be9d300`) — including `selected_device` and every
68/// `host_switch_targets` entry — and keeps the dropped route as a
69/// [`DeviceConfig::links`] entry. `receiver:` keys are left alone: nothing on
70/// disk says which device occupies a pairing slot, so those are folded at
71/// runtime instead, on the next online sighting (see `adopt_route`).
72///
73/// v5 adds the app-wide `ui_scale` preference. Older files default to the
74/// standard 100% scale.
75///
76/// Per-device custom names and the Home gallery view preference are optional
77/// and did not require a version bump: absent fields use the model name and
78/// responsive grid respectively.
79///
80/// v4 removes the one-gesture-button-per-device owner lock: gesture mode is a
81/// per-button fact read from the binding shape, so `gesture_owner` no longer
82/// serializes. Loading a v3-or-older file resolves the old owner and rewrites
83/// the shapes to dispatch identically
84/// (see `Config::migrate_owner_locked_gestures`); the version gate is what
85/// keeps that pass off v4 files, where several gesture-shaped buttons are a
86/// deliberate state, not a dormant leftover.
87///
88/// v3 changes the device map from model keys to physical-device keys. No v2
89/// device entries are migrated because model-scoped settings cannot be assigned
90/// safely when two identical devices exist.
91///
92/// v2 merged the per-device `button_bindings` + `gesture_bindings` maps into a
93/// single `bindings: BTreeMap<ButtonId, Binding>`. A v1 file still loads (the
94/// `RawDeviceConfig` shim folds the legacy fields) and self-heals to v2 on the
95/// next save; [`Config::load_from_path`] accepts supported versions `1` through
96/// [`SCHEMA_VERSION`] so an invalid or forward file fails loudly instead of
97/// silently losing bindings.
98pub const SCHEMA_VERSION: u32 = 7;
99
100/// Top-level config document.
101#[derive(Debug, Clone, Serialize, Deserialize)]
102#[serde(deny_unknown_fields)]
103pub struct Config {
104    /// Schema version the file was written with. Compared against
105    /// [`SCHEMA_VERSION`] on load: supported older layouts migrate, while zero
106    /// and newer layouts are rejected rather than silently losing settings.
107    pub schema_version: u32,
108    /// Non-device-scoped preferences (autostart, tray, language, …).
109    #[serde(default, skip_serializing_if = "AppSettings::is_default")]
110    pub app_settings: AppSettings,
111    /// Physical config key of the active device, persisted so a
112    /// restart restores the last view rather than always landing on the
113    /// first paired device. `None` means "fall back to the first device".
114    #[serde(default, skip_serializing_if = "Option::is_none")]
115    pub selected_device: Option<String>,
116    /// When set (see [`Self::ephemeral`]), [`Self::save_atomic`] is a no-op:
117    /// this config never writes the on-disk file. Never true for a loaded or
118    /// default-constructed config.
119    #[serde(skip)]
120    // Read only by the `fs` half, which is where saving happens. The field
121    // stays in every build: `Config::ephemeral()` is public API, and a field
122    // that exists conditionally is a struct whose shape depends on a feature.
123    #[cfg_attr(
124        not(feature = "fs"),
125        expect(clippy::allow_attributes, reason = "see above"),
126        allow(dead_code, reason = "only the `fs` half suppresses a save")
127    )]
128    ephemeral: bool,
129    /// Per-device state, normally keyed by the stable physical-device
130    /// identifier (e.g. `"receiver:abc123:slot:2"`). A serial-less camera's
131    /// custom name instead uses its OS capture id so same-model cameras remain
132    /// distinguishable.
133    #[serde(default)]
134    pub devices: BTreeMap<String, DeviceConfig>,
135    /// Keyboard remappings, independent of device. The function-key remapper
136    /// (M1) reads this; `#[serde(default)]` keeps older configs without a
137    /// `[keyboard]` section loading unchanged.
138    #[serde(default)]
139    pub keyboard: KeyboardConfig,
140}
141
142impl Default for Config {
143    fn default() -> Self {
144        Self {
145            schema_version: SCHEMA_VERSION,
146            app_settings: AppSettings::default(),
147            selected_device: None,
148            devices: BTreeMap::new(),
149            ephemeral: false,
150            keyboard: KeyboardConfig::default(),
151        }
152    }
153}
154
155impl Config {
156    /// A config that never touches the on-disk file: [`Self::save_atomic`] is
157    /// a no-op. For tests that drive the state layer's persistence paths —
158    /// with a default config those would overwrite the developer's real
159    /// `config.toml` with test fixtures.
160    #[must_use]
161    pub fn ephemeral() -> Self {
162        Self {
163            ephemeral: true,
164            ..Self::default()
165        }
166    }
167
168    /// Records (or, with `action = None`, clears) the F-key `trigger` binding
169    /// in the global `[keyboard]` map. Keyboard bindings are device-agnostic —
170    /// one map applies across all keyboards — so this mirrors [`Self::set_binding`]
171    /// minus the device key.
172    pub fn set_keyboard_binding(&mut self, trigger: KeyTrigger, action: Option<Action>) {
173        match action {
174            Some(a) => {
175                self.keyboard.bindings.insert(trigger, a);
176            }
177            None => {
178                self.keyboard.bindings.remove(&trigger);
179            }
180        }
181    }
182
183    /// The global keyboard F-key bindings (read accessor).
184    #[must_use]
185    pub fn keyboard_bindings(&self) -> &BTreeMap<KeyTrigger, Action> {
186        &self.keyboard.bindings
187    }
188
189    /// HID++ config key of the active device, if any.
190    #[must_use]
191    pub fn selected_device(&self) -> Option<&str> {
192        self.selected_device.as_deref()
193    }
194
195    /// Update the active device. Pass `None` to clear the
196    /// selection (e.g. when the previously-selected device disappears).
197    pub fn set_selected_device(&mut self, key: Option<String>) {
198        self.selected_device = key;
199    }
200}