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