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