Skip to main content

openlogi_core/config/
settings.rs

1//! App-wide and per-device *value* settings: [`AppSettings`], [`Appearance`],
2//! [`Lighting`], [`ScrollResolution`], [`WheelMode`] / [`SmartShift`], and
3//! [`GestureOwner`], plus
4//! their serde `default_*` / `deserialize_*` helpers.
5
6use serde::{Deserialize, Serialize};
7
8use crate::binding::ButtonId;
9use crate::color::Rgb;
10
11/// Light/dark appearance preference. `System` follows the OS appearance (the
12/// historical behaviour); `Light` / `Dark` force a mode regardless of the OS.
13/// Platform-free so the core crate stays GUI-agnostic — the GUI maps this onto
14/// gpui-component's `ThemeMode`.
15#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
16#[serde(rename_all = "snake_case")]
17pub enum Appearance {
18    /// Follow the operating system's light/dark setting.
19    #[default]
20    System,
21    /// Always use the light variant of the selected theme.
22    Light,
23    /// Always use the dark variant of the selected theme.
24    Dark,
25}
26
27/// App-wide preferences not tied to any particular device.
28///
29/// All fields are `#[serde(default)]` so adding a new one is backward
30/// compatible — old config files just keep the default for the new field.
31#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
32#[allow(
33    clippy::struct_excessive_bools,
34    reason = "independent on/off user preferences, not a state machine"
35)]
36pub struct AppSettings {
37    /// When true, a macOS `LaunchAgent` plist at
38    /// `~/Library/LaunchAgents/org.openlogi.openlogi.plist` is installed
39    /// so the app starts on login (P2.2). The plist is reconciled with
40    /// this field on every startup; flipping the flag and relaunching is
41    /// enough to install / remove it.
42    #[serde(default)]
43    pub launch_at_login: bool,
44    /// Opt-in update check (P2.8). **Off by default** to honour the
45    /// README's "no telemetry, no auto-update poller" promise. When true,
46    /// the app makes exactly one `HEAD /repos/AprilNEA/OpenLogi/releases/
47    /// latest` request per launch and logs whether a newer version is
48    /// available — no automatic download.
49    #[serde(default)]
50    pub check_for_updates: bool,
51    /// Opt-in automatic install. When true *and* [`Self::check_for_updates`]
52    /// surfaces a newer version, the GUI downloads and stages it in the
53    /// background; the update is applied on the next restart (never mid-session,
54    /// and never auto-relaunched). **Off by default** — it only acts after a
55    /// check the user already opted into, and stays inert in unsigned dev builds
56    /// where verification fails closed.
57    #[serde(default)]
58    pub auto_install_updates: bool,
59    /// True once the first-run "check for updates?" prompt has been answered
60    /// (either way), so it is never shown again. The prompt is how a
61    /// privacy-conscious default of `check_for_updates = false` still lets a
62    /// user opt in on first launch.
63    #[serde(default)]
64    pub update_prompt_seen: bool,
65    /// Whether OpenLogi shows a macOS menu-bar (status item) icon — and, on
66    /// Windows, the notification-area (tray) icon. `true` (default) → the
67    /// agent is visible in the menu bar / tray; `false` → it runs with no
68    /// visible presence (macOS additionally keeps the ordinary Dock icon
69    /// while a window is open). Ignored on Linux.
70    #[serde(default = "default_true")]
71    pub show_in_menu_bar: bool,
72    /// Whether the GUI automatically downloads device images from
73    /// `assets.openlogi.org` when a device appears. `true` (default) keeps
74    /// the current behavior; `false` makes no asset network requests at all
75    /// (the app falls back to bundled art and the synthetic silhouette). A
76    /// manual "Refresh assets" in Settings still fetches on demand regardless.
77    #[serde(default = "default_true")]
78    pub auto_download_assets: bool,
79    /// UI language as a BCP-47-ish locale code matching the GUI's bundled
80    /// locales (e.g. `"en"`, `"de"`, `"pt-BR"`, `"zh-CN"`, `"zh-TW"`; see the
81    /// GUI's `i18n::SUPPORTED`). `None` means "follow the system locale", which
82    /// the GUI resolves at startup. Stored here so a user's explicit choice
83    /// survives restarts regardless of the OS setting.
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    pub language: Option<String>,
86    /// Thumb-wheel responsiveness, on a [`MIN_THUMBWHEEL_SENSITIVITY`]–
87    /// [`MAX_THUMBWHEEL_SENSITIVITY`] scale. It scales both the speed of the
88    /// wheel's continuous horizontal scroll and how few rotation increments a
89    /// custom wheel action needs to fire. [`DEFAULT_THUMBWHEEL_SENSITIVITY`]
90    /// (the out-of-the-box value) means 1× scroll speed; the wheel is only
91    /// diverted from native scrolling once this leaves the default.
92    #[serde(default = "default_thumbwheel_sensitivity")]
93    pub thumbwheel_sensitivity: i32,
94    /// Light/dark appearance preference. Defaults to following the OS.
95    #[serde(default)]
96    pub appearance: Appearance,
97    /// Name of the theme used in light mode (a [`crate`]-agnostic string
98    /// matching a gpui-component theme, e.g. `"OpenLogi Light"`). `None` uses
99    /// the OpenLogi brand light theme.
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub theme_light: Option<String>,
102    /// Name of the theme used in dark mode. `None` uses the OpenLogi brand dark
103    /// theme.
104    #[serde(default, skip_serializing_if = "Option::is_none")]
105    pub theme_dark: Option<String>,
106    /// Corner-radius override for the UI, in pixels (the Appearance page offers
107    /// `0` / `6` / `12`). `None` keeps each theme's own radius.
108    #[serde(default, skip_serializing_if = "Option::is_none")]
109    pub ui_radius: Option<u8>,
110}
111
112/// Out-of-the-box [`AppSettings::thumbwheel_sensitivity`]. At this value the
113/// wheel's horizontal scroll runs at 1× and the wheel is left to scroll
114/// natively (no HID++ diversion) unless a binding diverges from its default.
115pub const DEFAULT_THUMBWHEEL_SENSITIVITY: i32 = 14;
116/// Lowest selectable [`AppSettings::thumbwheel_sensitivity`].
117pub const MIN_THUMBWHEEL_SENSITIVITY: i32 = 1;
118/// Highest selectable [`AppSettings::thumbwheel_sensitivity`].
119pub const MAX_THUMBWHEEL_SENSITIVITY: i32 = 100;
120
121impl AppSettings {
122    /// `skip_serializing_if` helper: true when nothing diverges from the
123    /// default, so empty settings don't clutter `config.toml`.
124    #[must_use]
125    pub fn is_default(&self) -> bool {
126        self == &Self::default()
127    }
128}
129
130impl Default for AppSettings {
131    fn default() -> Self {
132        Self {
133            launch_at_login: false,
134            check_for_updates: false,
135            auto_install_updates: false,
136            update_prompt_seen: false,
137            show_in_menu_bar: true,
138            auto_download_assets: true,
139            language: None,
140            thumbwheel_sensitivity: DEFAULT_THUMBWHEEL_SENSITIVITY,
141            appearance: Appearance::System,
142            theme_light: None,
143            theme_dark: None,
144            ui_radius: None,
145        }
146    }
147}
148
149/// serde default for [`AppSettings::show_in_menu_bar`]: `true`, so the menu-bar
150/// icon is on out of the box and configs predating the field keep that behavior.
151fn default_true() -> bool {
152    true
153}
154
155/// serde default for [`AppSettings::thumbwheel_sensitivity`]: keeps configs
156/// predating the field at the 1× default.
157const fn default_thumbwheel_sensitivity() -> i32 {
158    DEFAULT_THUMBWHEEL_SENSITIVITY
159}
160
161/// Per-device RGB lighting: a single static color, brightness, and on/off.
162/// Deliberately basic — per-key effects are a later addition.
163///
164/// Crosses the agent↔GUI IPC (`set_lighting`), so field order is wire format —
165/// changes require a `PROTOCOL_VERSION` bump (guarded by
166/// `openlogi-agent-core/tests/wire_format.rs`).
167#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
168pub struct Lighting {
169    /// Master on/off for the device's lighting. The color and brightness
170    /// persist while disabled, so re-enabling restores the previous look.
171    #[serde(default = "default_lighting_enabled")]
172    pub enabled: bool,
173    /// Static color as 6 hex digits `"RRGGBB"` (no leading `#`). A value
174    /// that does not parse falls back to white on load — the same per-field
175    /// tolerance as `brightness`, because failing the whole load would
176    /// discard the user's entire config (see the `load_or_default` callers).
177    #[serde(
178        default = "default_lighting_color",
179        deserialize_with = "deserialize_lighting_color"
180    )]
181    pub color: Rgb,
182    /// Brightness percent, clamped to 0–100 on load.
183    #[serde(
184        default = "default_lighting_brightness",
185        deserialize_with = "deserialize_brightness"
186    )]
187    pub brightness: u8,
188}
189
190impl Default for Lighting {
191    fn default() -> Self {
192        Self {
193            enabled: default_lighting_enabled(),
194            color: default_lighting_color(),
195            brightness: default_lighting_brightness(),
196        }
197    }
198}
199
200fn default_lighting_enabled() -> bool {
201    true
202}
203
204fn default_lighting_color() -> Rgb {
205    Rgb::WHITE
206}
207
208fn default_lighting_brightness() -> u8 {
209    100
210}
211
212/// Clamp a deserialized brightness into the UI's `0..=100` range, so a
213/// hand-edited `config.toml` can't feed out-of-range values into the scaling
214/// math (which assumes `brightness <= 100`).
215fn deserialize_brightness<'de, D>(deserializer: D) -> Result<u8, D::Error>
216where
217    D: serde::Deserializer<'de>,
218{
219    Ok(u8::deserialize(deserializer)?.min(100))
220}
221
222/// Accept the optional `#` prefix supported by older releases, then fall back
223/// to white when the configured color does not parse, mirroring the `brightness`
224/// clamp above instead of failing the whole config load.
225fn deserialize_lighting_color<'de, D>(deserializer: D) -> Result<Rgb, D::Error>
226where
227    D: serde::Deserializer<'de>,
228{
229    let color = String::deserialize(deserializer)?;
230    Ok(color
231        .strip_prefix('#')
232        .unwrap_or(color.as_str())
233        .parse()
234        .unwrap_or(Rgb::WHITE))
235}
236
237/// Vertical wheel reporting resolution for HID++ `0x2121 HiResWheel`.
238#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
239#[serde(rename_all = "snake_case")]
240pub enum ScrollResolution {
241    /// One scroll report per physical ratchet step.
242    Low,
243    /// Finer-grained reports between physical ratchet steps.
244    High,
245}
246
247/// Scroll-wheel mode for [`SmartShift`]: free-spin or ratchet (clicky).
248#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
249#[serde(rename_all = "snake_case")]
250pub enum WheelMode {
251    /// Free-spin — the wheel rotates without détentes.
252    Free,
253    /// Ratchet (clicky) scrolling. With SmartShift enabled the firmware
254    /// auto-releases into free-spin past the configured
255    /// [`auto_disengage`](SmartShift::auto_disengage) speed.
256    Ratchet,
257}
258
259/// SmartShift auto-disengage out-of-box default (`16` ≈ 4 turn/s, per the
260/// x2110 / x2111 spec). The sensitivity slider's default and the heal target
261/// for a corrupt persisted threshold.
262pub const SMARTSHIFT_AUTO_DISENGAGE_DEFAULT: u8 = 16;
263
264/// Smallest auto-disengage threshold OpenLogi will store or apply (`8` ≈
265/// 2 turn/s). Below this the ratchet releases into free-spin at everyday scroll
266/// speeds, leaving the wheel "stuck" spinning (#317); `0` is also the firmware
267/// "do not change" sentinel that must never be stored as a real value. A
268/// persisted threshold below this floor is a corrupt artifact and is healed to
269/// [`SMARTSHIFT_AUTO_DISENGAGE_DEFAULT`] on load.
270pub const SMARTSHIFT_MIN_AUTO_DISENGAGE: u8 = 8;
271
272/// Heal a persisted auto-disengage threshold on load: anything below
273/// [`SMARTSHIFT_MIN_AUTO_DISENGAGE`] (including the `0` sentinel) becomes the
274/// default. `0xFF` (permanent ratchet) and every real threshold at or above the
275/// floor pass through unchanged.
276fn deserialize_auto_disengage<'de, D>(deserializer: D) -> Result<u8, D::Error>
277where
278    D: serde::Deserializer<'de>,
279{
280    let value = u8::deserialize(deserializer)?;
281    Ok(if value < SMARTSHIFT_MIN_AUTO_DISENGAGE {
282        tracing::warn!(
283            value,
284            min = SMARTSHIFT_MIN_AUTO_DISENGAGE,
285            default = SMARTSHIFT_AUTO_DISENGAGE_DEFAULT,
286            "healed persisted SmartShift auto-disengage threshold below supported floor"
287        );
288        SMARTSHIFT_AUTO_DISENGAGE_DEFAULT
289    } else {
290        value
291    })
292}
293
294/// Per-device SmartShift wheel configuration, persisted so the agent can
295/// re-apply it when the device reconnects: the values are written to device
296/// RAM and do not survive a power cycle (#189), despite earlier assumptions
297/// that the device kept them in NVM.
298///
299/// Config-file only — never crosses the IPC (the agent reads it from
300/// `config.toml` on reload), so it is free to evolve without a
301/// `PROTOCOL_VERSION` bump.
302#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
303pub struct SmartShift {
304    /// The persisted wheel mode, re-applied to device RAM on reconnect.
305    pub mode: WheelMode,
306    /// SmartShift auto-disengage threshold (`0x08`–`0xFE`, in 0.25 turn/s
307    /// steps), or `0xFF` for a permanently engaged ratchet. A persisted value
308    /// below [`SMARTSHIFT_MIN_AUTO_DISENGAGE`] is healed to the default on load.
309    #[serde(deserialize_with = "deserialize_auto_disengage")]
310    pub auto_disengage: u8,
311    /// Tunable-torque force percentage (`1`–`100`), `0` when the device
312    /// doesn't support tunable torque.
313    pub tunable_torque: u8,
314}
315
316/// Which control owns a device's single gesture role.
317///
318/// Stored explicitly — rather than inferred from which button happens to carry a
319/// [`Binding::Gesture`](crate::binding::Binding::Gesture) — so switching the
320/// gesture button never has to collapse a button's gesture map to encode the
321/// choice: every gesture-capable button keeps its full direction map, and only
322/// the owner is dispatched. Serialized as a bare string (`"Off"` or a
323/// [`ButtonId`] name) so it stays a TOML scalar.
324#[derive(Clone, Copy, Debug, PartialEq, Eq)]
325pub enum GestureOwner {
326    /// Gestures are explicitly turned off for this device.
327    Off,
328    /// The named button owns the gesture role.
329    Button(ButtonId),
330}
331
332impl Serialize for GestureOwner {
333    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
334        match self {
335            // "Off" can't collide with a ButtonId variant name (all CamelCase
336            // control names), so the string space is unambiguous.
337            GestureOwner::Off => serializer.serialize_str("Off"),
338            GestureOwner::Button(id) => id.serialize(serializer),
339        }
340    }
341}
342
343/// Lenient field deserializer for `RawDeviceConfig::gesture_owner`
344/// (`crate::config::device`). An unrecognized or miscased value (`"back"`, a
345/// typo, a future-version button name) is treated as absent — i.e. "infer the
346/// owner" — rather than failing the whole-document parse and reverting *every*
347/// device's settings to defaults. Mirrors [`deserialize_brightness`], which
348/// clamps a bad value instead of erroring; a hand-editable config should
349/// degrade one field, not the document.
350pub(super) fn deserialize_gesture_owner<'de, D>(
351    deserializer: D,
352) -> Result<Option<GestureOwner>, D::Error>
353where
354    D: serde::Deserializer<'de>,
355{
356    let s = String::deserialize(deserializer)?;
357    if s == "Off" {
358        return Ok(Some(GestureOwner::Off));
359    }
360    // Parse the button name with a throwaway error type so an unknown token maps
361    // to `None` (infer) rather than propagating an error.
362    let button = ButtonId::deserialize(
363        serde::de::value::StrDeserializer::<serde::de::value::Error>::new(&s),
364    )
365    .ok();
366    Ok(button.map(GestureOwner::Button))
367}
368
369#[cfg(test)]
370#[allow(clippy::expect_used, reason = "expect/unwrap are idiomatic in tests")]
371mod tests {
372    use super::*;
373
374    #[test]
375    fn low_auto_disengage_heals_to_default_on_load() {
376        // A pre-#317 config could persist a runaway-low threshold (or the `0`
377        // sentinel); loading it must heal to the default so reapply doesn't
378        // re-program free-spin-on-any-scroll into the device — while a real
379        // threshold and the `0xFF` permanent-ratchet value pass through.
380        let heal = |v: u8| {
381            let body = format!("mode = \"ratchet\"\nauto_disengage = {v}\ntunable_torque = 50\n");
382            toml::from_str::<SmartShift>(&body)
383                .expect("parse")
384                .auto_disengage
385        };
386        assert_eq!(heal(0), SMARTSHIFT_AUTO_DISENGAGE_DEFAULT);
387        assert_eq!(heal(1), SMARTSHIFT_AUTO_DISENGAGE_DEFAULT);
388        assert_eq!(
389            heal(SMARTSHIFT_MIN_AUTO_DISENGAGE - 1),
390            SMARTSHIFT_AUTO_DISENGAGE_DEFAULT
391        );
392        assert_eq!(
393            heal(SMARTSHIFT_MIN_AUTO_DISENGAGE),
394            SMARTSHIFT_MIN_AUTO_DISENGAGE
395        );
396        assert_eq!(heal(16), 16);
397        assert_eq!(heal(0xff), 0xff);
398    }
399}