Skip to main content

openlogi_core/config/
settings.rs

1//! App-wide and per-device *value* settings: [`AppSettings`], [`Appearance`],
2//! [`UiScale`], [`AppIcon`], [`Lighting`], [`ScrollResolution`], [`WheelMode`] /
3//! [`SmartShift`], and the legacy [`GestureOwner`], plus their serde helpers.
4
5use std::collections::BTreeMap;
6
7use az::SaturatingAs;
8use nutype::nutype;
9use serde::{Deserialize, Serialize};
10
11use crate::binding::ButtonId;
12use crate::color::Rgb;
13use crate::hid::{SmartShiftAutoDisengage, SmartShiftThreshold, TunableTorque};
14
15/// Light/dark appearance preference. `System` follows the OS appearance (the
16/// historical behaviour); `Light` / `Dark` force a mode regardless of the OS.
17/// Platform-free so the core crate stays GUI-agnostic — the GUI maps this onto
18/// gpui-component's `ThemeMode`.
19#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
20#[serde(rename_all = "snake_case")]
21pub enum Appearance {
22    /// Follow the operating system's light/dark setting.
23    #[default]
24    System,
25    /// Always use the light variant of the selected theme.
26    Light,
27    /// Always use the dark variant of the selected theme.
28    Dark,
29}
30
31/// User-selected scale for text and rem-based interface spacing.
32///
33/// The core stores a semantic choice rather than GPUI pixels; the desktop maps
34/// each variant's percentage onto the window's rem size. Keeping the supported
35/// range finite lets every layout be verified at every scale.
36#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(rename_all = "snake_case")]
38pub enum UiScale {
39    /// 90% of the standard interface size.
40    Small,
41    /// The standard interface size.
42    #[default]
43    Normal,
44    /// 110% of the standard interface size.
45    Large,
46    /// 125% of the standard interface size.
47    ExtraLarge,
48}
49
50impl UiScale {
51    /// Every supported scale, in the order Settings offers them.
52    pub const ALL: [Self; 4] = [Self::Small, Self::Normal, Self::Large, Self::ExtraLarge];
53
54    /// The displayed percentage for this scale.
55    #[must_use]
56    pub const fn percent(self) -> u16 {
57        match self {
58            Self::Small => 90,
59            Self::Normal => 100,
60            Self::Large => 110,
61            Self::ExtraLarge => 125,
62        }
63    }
64}
65
66/// Layout used for the Home device gallery.
67///
68/// This is a presentation preference: the GUI owns how each mode renders, while
69/// core keeps the persisted vocabulary platform-free alongside [`Appearance`].
70#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
71#[serde(rename_all = "snake_case")]
72pub enum DeviceViewMode {
73    /// Responsive cards that wrap to keep the finite device set visible.
74    #[default]
75    Grid,
76    /// Compact full-width rows for scanning identity and status.
77    List,
78    /// A horizontally scrolling row navigated with previous/next controls.
79    Carousel,
80}
81
82/// Which icon the app wears.
83///
84/// Variant names are one string doing three jobs, and all three are part of a
85/// contract: the value persisted in `config.toml`, the file each alternate
86/// ships as inside the macOS bundle, and the name the build compiles its source
87/// document under. Renaming one renames all three.
88///
89/// Platform-free, like [`Appearance`]: honouring it is the frontend's business,
90/// and today only macOS can — Windows embeds its icon in the executable at
91/// compile time and Linux installs a fixed one from the package.
92#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, strum::Display)]
93#[serde(rename_all = "snake_case")]
94#[strum(serialize_all = "snake_case")]
95pub enum AppIcon {
96    /// The icon the app is signed with, and the one it wears until a user picks
97    /// another.
98    #[default]
99    Openlogi,
100    /// The geometric mark on a faceted, light-refracting fill.
101    Prism,
102}
103
104impl AppIcon {
105    /// Every icon, in the order Settings offers them.
106    pub const ALL: [Self; 2] = [Self::Openlogi, Self::Prism];
107
108    /// Whether this is the icon the installed bundle already wears — the one
109    /// case a frontend applies by clearing its override rather than by handing
110    /// the system a file.
111    #[must_use]
112    pub fn is_default(self) -> bool {
113        matches!(self, Self::Openlogi)
114    }
115}
116
117/// Preferred source for on-demand device assets.
118///
119/// `Automatic` races every built-in mirror; the other variants pin a sync to
120/// one source. The GUI maps this persisted preference to the shared asset
121/// client's source type, keeping endpoint URLs and npm routing out of config.
122#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
123#[serde(rename_all = "snake_case")]
124pub enum AssetSourcePreference {
125    /// Use the first healthy built-in mirror.
126    #[default]
127    Automatic,
128    /// Use OpenLogi's official asset endpoint.
129    #[serde(rename = "openlogi")]
130    OpenLogi,
131    /// Use the versioned endpoint on Cloudflare's network.
132    Cloudflare,
133    /// Use the versioned npm packages through Fastly's network.
134    Fastly,
135}
136
137/// App-wide preferences not tied to any particular device.
138///
139/// All fields are `#[serde(default)]` so adding a new one is backward
140/// compatible — old config files just keep the default for the new field.
141#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
142#[serde(deny_unknown_fields)]
143#[expect(
144    clippy::struct_excessive_bools,
145    reason = "independent on/off user preferences, not a state machine"
146)]
147pub struct AppSettings {
148    /// When true, a macOS `LaunchAgent` plist at
149    /// `~/Library/LaunchAgents/org.openlogi.openlogi.plist` is installed
150    /// so the app starts on login (P2.2). The plist is reconciled with
151    /// this field on every startup; flipping the flag and relaunching is
152    /// enough to install / remove it.
153    #[serde(default)]
154    pub launch_at_login: bool,
155    /// Opt-in update check (P2.8). **Off by default** to honour the
156    /// README's "no telemetry, no auto-update poller" promise. When true,
157    /// the app makes exactly one `HEAD /repos/AprilNEA/OpenLogi/releases/
158    /// latest` request per launch and logs whether a newer version is
159    /// available — no automatic download.
160    #[serde(default)]
161    pub check_for_updates: bool,
162    /// Opt-in automatic install. When true *and* [`Self::check_for_updates`]
163    /// surfaces a newer version, the GUI downloads and stages it in the
164    /// background; the update is applied on the next restart (never mid-session,
165    /// and never auto-relaunched). **Off by default** — it only acts after a
166    /// check the user already opted into, and stays inert in unsigned dev builds
167    /// where verification fails closed.
168    #[serde(default)]
169    pub auto_install_updates: bool,
170    /// True once the first-run "check for updates?" prompt has been answered
171    /// (either way), so it is never shown again. The prompt is how a
172    /// privacy-conscious default of `check_for_updates = false` still lets a
173    /// user opt in on first launch.
174    #[serde(default)]
175    pub update_prompt_seen: bool,
176    /// Whether OpenLogi shows a macOS menu-bar (status item) icon — and, on
177    /// Windows, the notification-area (tray) icon. `true` (default) → the
178    /// agent is visible in the menu bar / tray; `false` → it runs with no
179    /// visible presence (macOS additionally keeps the ordinary Dock icon
180    /// while a window is open). Ignored on Linux.
181    #[serde(default = "default_true")]
182    pub show_in_menu_bar: bool,
183    /// Whether the agent installs the OS-level mouse hook (CGEventTap /
184    /// exclusive `evdev` grab / `WH_MOUSE_LL`) that intercepts mouse events
185    /// for button remapping. `true` (default) keeps remapping active;
186    /// `false` is an escape hatch that leaves every input device untouched
187    /// (on Linux: no exclusive grabs at all; on macOS the agent also skips
188    /// the startup Accessibility prompt). HID++-side features — DPI,
189    /// SmartShift, the gesture button, the thumb wheel — are unaffected.
190    /// Takes effect on agent restart.
191    #[serde(default = "default_true")]
192    pub capture_mouse_events: bool,
193    /// Whether ordinary mouse-wheel input is replaced with a finite smooth
194    /// scroll animation. **Off by default**: while enabled the OS hook
195    /// suppresses eligible physical wheel events only after its non-blocking
196    /// scroll worker accepts them. Trackpad and other continuous pixel input
197    /// remains native. Windows' low-level hook cannot attribute wheel messages
198    /// to a device, so the preference applies to every traditional mouse-wheel
199    /// message there.
200    #[serde(default)]
201    pub smooth_scroll: bool,
202    /// Distance multiplier for traditional vertical mouse-wheel input.
203    /// [`VerticalScrollSensitivity::DEFAULT`] means 1×; trackpad and other
204    /// continuous pixel input is never scaled.
205    #[serde(default)]
206    pub vertical_scroll_sensitivity: VerticalScrollSensitivity,
207    /// Which app icon the user picked. Applied at launch, and whenever it
208    /// changes, by whichever process owns a surface showing one — on macOS the
209    /// GUI hands the choice to the Dock and writes it onto the bundle (so the
210    /// icon survives a quit), and the agent restyles the menu-bar item, which
211    /// is its own glyph and no one else's to set. Elsewhere it is inert.
212    /// Defaults to the icon the app is signed with.
213    #[serde(default)]
214    pub app_icon: AppIcon,
215    /// Whether the GUI automatically downloads device images from
216    /// `assets.openlogi.org` when a device appears. `true` (default) keeps
217    /// the current behavior; `false` makes no asset network requests at all
218    /// (the app falls back to bundled art and the synthetic silhouette). A
219    /// manual "Refresh assets" in Settings still fetches on demand regardless.
220    /// Whether the GUI automatically downloads device images from the selected
221    /// source when a device appears. `true` (default) keeps the current behavior;
222    /// `false` makes no asset network requests at all (the app falls back to
223    /// bundled art and the synthetic silhouette). A manual "Refresh assets" in
224    /// Settings still fetches on demand regardless.
225    #[serde(default = "default_true")]
226    pub auto_download_assets: bool,
227    /// Preferred mirror for automatic and manual device-asset downloads.
228    /// Defaults to racing all built-in mirrors; `OPENLOGI_ASSETS` remains a
229    /// process-level override for development and diagnostics.
230    #[serde(default)]
231    pub asset_source: AssetSourcePreference,
232    /// UI language as a BCP-47-ish locale code matching the GUI's bundled
233    /// locales (e.g. `"en"`, `"de"`, `"pt-BR"`, `"zh-CN"`, `"zh-TW"`; see the
234    /// GUI's `i18n::SUPPORTED`). `None` means "follow the system locale", which
235    /// the GUI resolves at startup. Stored here so a user's explicit choice
236    /// survives restarts regardless of the OS setting.
237    #[serde(default, skip_serializing_if = "Option::is_none")]
238    pub language: Option<String>,
239    /// Thumb-wheel responsiveness. It scales both the speed of the wheel's
240    /// continuous horizontal or remapped vertical scroll and how few rotation
241    /// increments a custom wheel action needs to fire.
242    /// [`ThumbwheelSensitivity::DEFAULT`] means 1× scroll speed; the wheel is
243    /// only diverted from native scrolling once this leaves the default.
244    #[serde(default)]
245    pub thumbwheel_sensitivity: ThumbwheelSensitivity,
246    /// Light/dark appearance preference. Defaults to following the OS.
247    #[serde(default)]
248    pub appearance: Appearance,
249    /// Text and rem-based interface scale. Defaults to 100%.
250    #[serde(default)]
251    pub ui_scale: UiScale,
252    /// Layout used for the Home device gallery. Defaults to the responsive grid.
253    #[serde(default)]
254    pub device_view_mode: DeviceViewMode,
255    /// Name of the theme used in light mode (a [`crate`]-agnostic string
256    /// matching a gpui-component theme, e.g. `"OpenLogi Light"`). `None` uses
257    /// the OpenLogi brand light theme.
258    #[serde(default, skip_serializing_if = "Option::is_none")]
259    pub theme_light: Option<String>,
260    /// Name of the theme used in dark mode. `None` uses the OpenLogi brand dark
261    /// theme.
262    #[serde(default, skip_serializing_if = "Option::is_none")]
263    pub theme_dark: Option<String>,
264    /// Corner-radius override for the UI, in pixels (the Appearance page offers
265    /// `0` / `6` / `12`). `None` keeps each theme's own radius.
266    #[serde(default, skip_serializing_if = "Option::is_none")]
267    pub ui_radius: Option<u8>,
268}
269
270const SENSITIVITY_MIN: u8 = 1;
271const SENSITIVITY_MAX: u8 = 100;
272const SENSITIVITY_DEFAULT: u8 = 14;
273
274/// Traditional vertical mouse-wheel responsiveness on OpenLogi's `1..=100`
275/// scale.
276///
277/// This is deliberately distinct from [`ThumbwheelSensitivity`]: vertical
278/// sensitivity changes only scroll distance and never changes a custom action
279/// threshold.
280#[nutype(
281    const_fn,
282    validate(greater_or_equal = SENSITIVITY_MIN, less_or_equal = SENSITIVITY_MAX),
283    derive(
284        Debug,
285        Clone,
286        Copy,
287        PartialEq,
288        Eq,
289        PartialOrd,
290        Ord,
291        TryFrom,
292        Into,
293        Display,
294        Serialize,
295        Deserialize
296    )
297)]
298pub struct VerticalScrollSensitivity(u8);
299
300impl VerticalScrollSensitivity {
301    /// Lowest selectable sensitivity.
302    pub const MIN: Self = match Self::try_new(SENSITIVITY_MIN) {
303        Ok(value) => value,
304        Err(_) => panic!("valid minimum vertical scroll sensitivity"),
305    };
306    /// Highest selectable sensitivity.
307    pub const MAX: Self = match Self::try_new(SENSITIVITY_MAX) {
308        Ok(value) => value,
309        Err(_) => panic!("valid maximum vertical scroll sensitivity"),
310    };
311    /// Out-of-the-box sensitivity. At this value scrolling runs at 1×.
312    pub const DEFAULT: Self = match Self::try_new(SENSITIVITY_DEFAULT) {
313        Ok(value) => value,
314        Err(_) => panic!("valid default vertical scroll sensitivity"),
315    };
316
317    /// Round and clamp a floating-point slider value into the valid range.
318    #[must_use]
319    pub fn from_rounded(value: f32) -> Self {
320        let raw = rounded_sensitivity(value);
321        let Ok(value) = Self::try_new(raw) else {
322            unreachable!("clamped vertical scroll sensitivity is always valid");
323        };
324        value
325    }
326
327    /// Vertical scroll-distance multiplier relative to [`Self::DEFAULT`].
328    #[must_use]
329    pub fn scroll_multiplier(self) -> f64 {
330        f64::from(self.into_inner()) / f64::from(Self::DEFAULT.into_inner())
331    }
332}
333
334impl Default for VerticalScrollSensitivity {
335    fn default() -> Self {
336        Self::DEFAULT
337    }
338}
339
340impl From<VerticalScrollSensitivity> for f32 {
341    fn from(sensitivity: VerticalScrollSensitivity) -> Self {
342        Self::from(sensitivity.into_inner())
343    }
344}
345
346/// Thumb-wheel responsiveness on OpenLogi's `1..=100` scale.
347#[nutype(
348    const_fn,
349    validate(greater_or_equal = SENSITIVITY_MIN, less_or_equal = SENSITIVITY_MAX),
350    derive(
351        Debug,
352        Clone,
353        Copy,
354        PartialEq,
355        Eq,
356        PartialOrd,
357        Ord,
358        TryFrom,
359        Into,
360        Display,
361        Serialize,
362        Deserialize
363    )
364)]
365pub struct ThumbwheelSensitivity(u8);
366
367impl ThumbwheelSensitivity {
368    /// Lowest selectable sensitivity.
369    pub const MIN: Self = match Self::try_new(SENSITIVITY_MIN) {
370        Ok(value) => value,
371        Err(_) => panic!("valid minimum thumb-wheel sensitivity"),
372    };
373    /// Highest selectable sensitivity.
374    pub const MAX: Self = match Self::try_new(SENSITIVITY_MAX) {
375        Ok(value) => value,
376        Err(_) => panic!("valid maximum thumb-wheel sensitivity"),
377    };
378    /// Out-of-the-box sensitivity. At this value scrolling runs at 1× and
379    /// remains native unless a thumb-wheel binding is customized.
380    pub const DEFAULT: Self = match Self::try_new(SENSITIVITY_DEFAULT) {
381        Ok(value) => value,
382        Err(_) => panic!("valid default thumb-wheel sensitivity"),
383    };
384
385    /// Round and clamp a floating-point slider value into the valid range.
386    #[must_use]
387    pub fn from_rounded(value: f32) -> Self {
388        let raw = rounded_sensitivity(value);
389        let Ok(value) = Self::try_new(raw) else {
390            unreachable!("clamped thumb-wheel sensitivity is always valid");
391        };
392        value
393    }
394
395    /// Continuous-scroll speed multiplier relative to [`Self::DEFAULT`].
396    #[must_use]
397    pub fn scroll_multiplier(self) -> f64 {
398        f64::from(self.into_inner()) / f64::from(Self::DEFAULT.into_inner())
399    }
400
401    /// Rotation increments required to fire a discrete thumb-wheel action.
402    #[must_use]
403    pub fn action_threshold(self) -> i32 {
404        (2 * i32::from(Self::DEFAULT) - i32::from(self)).max(1)
405    }
406}
407
408impl Default for ThumbwheelSensitivity {
409    fn default() -> Self {
410        Self::DEFAULT
411    }
412}
413
414impl From<ThumbwheelSensitivity> for f32 {
415    fn from(sensitivity: ThumbwheelSensitivity) -> Self {
416        Self::from(sensitivity.into_inner())
417    }
418}
419
420impl From<ThumbwheelSensitivity> for i32 {
421    fn from(sensitivity: ThumbwheelSensitivity) -> Self {
422        Self::from(sensitivity.into_inner())
423    }
424}
425
426fn rounded_sensitivity(value: f32) -> u8 {
427    let value = if value.is_nan() {
428        f32::from(SENSITIVITY_MIN)
429    } else {
430        value
431    };
432    value
433        .clamp(f32::from(SENSITIVITY_MIN), f32::from(SENSITIVITY_MAX))
434        .round()
435        .saturating_as::<u8>()
436}
437
438impl AppSettings {
439    /// `skip_serializing_if` helper: true when nothing diverges from the
440    /// default, so empty settings don't clutter `config.toml`.
441    #[must_use]
442    pub fn is_default(&self) -> bool {
443        self == &Self::default()
444    }
445}
446
447impl Default for AppSettings {
448    fn default() -> Self {
449        Self {
450            launch_at_login: false,
451            check_for_updates: false,
452            auto_install_updates: false,
453            update_prompt_seen: false,
454            show_in_menu_bar: true,
455            capture_mouse_events: true,
456            smooth_scroll: false,
457            vertical_scroll_sensitivity: VerticalScrollSensitivity::DEFAULT,
458            auto_download_assets: true,
459            asset_source: AssetSourcePreference::Automatic,
460            language: None,
461            thumbwheel_sensitivity: ThumbwheelSensitivity::DEFAULT,
462            appearance: Appearance::System,
463            ui_scale: UiScale::Normal,
464            device_view_mode: DeviceViewMode::Grid,
465            app_icon: AppIcon::Openlogi,
466            theme_light: None,
467            theme_dark: None,
468            ui_radius: None,
469        }
470    }
471}
472
473/// serde default for the on-by-default [`AppSettings`] toggles
474/// ([`AppSettings::show_in_menu_bar`], [`AppSettings::capture_mouse_events`],
475/// [`AppSettings::auto_download_assets`]), so configs predating a field keep the
476/// out-of-the-box behavior.
477fn default_true() -> bool {
478    true
479}
480
481/// Per-device RGB lighting: a single static color, brightness, and on/off.
482/// Deliberately basic — per-key effects are a later addition.
483///
484/// Crosses the agent↔GUI IPC (`set_lighting`), so field order is wire format —
485/// changes require a `PROTOCOL_VERSION` bump (guarded by
486/// `openlogi-ipc/tests/wire_format.rs`).
487#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
488#[serde(deny_unknown_fields)]
489pub struct Lighting {
490    /// Master on/off for the device's lighting. The color and brightness
491    /// persist while disabled, so re-enabling restores the previous look.
492    #[serde(default = "default_lighting_enabled")]
493    pub enabled: bool,
494    /// Static color as 6 hex digits `"RRGGBB"` (no leading `#`). A value
495    /// that does not parse is rejected with its TOML location.
496    #[serde(
497        default = "default_lighting_color",
498        deserialize_with = "deserialize_lighting_color"
499    )]
500    pub color: Rgb,
501    /// Brightness percent (`0`–`100`).
502    #[serde(
503        default = "default_lighting_brightness",
504        deserialize_with = "deserialize_brightness"
505    )]
506    pub brightness: u8,
507}
508
509/// Persisted settings for a standalone light such as Logitech Litra.
510///
511/// Brightness is stored as a normalized percentage so the same config shape
512/// works for lumen-based, percentage-based, and stepped light protocols. The
513/// selected driver maps it to its native range when applying the setting.
514#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
515#[serde(deny_unknown_fields)]
516pub struct LightSettings {
517    /// Whether the light should be on.
518    #[serde(default = "default_true")]
519    pub enabled: bool,
520    /// Link power to aggregate host-camera activity. This is a policy setting:
521    /// brightness, colour temperature, and the persisted manual power choice
522    /// remain independent from the transient effective power state.
523    #[serde(default, skip_serializing_if = "is_false")]
524    pub auto_camera: bool,
525    /// Brightness across the device's advertised range.
526    #[serde(
527        default = "default_light_brightness",
528        deserialize_with = "deserialize_brightness"
529    )]
530    pub brightness_percent: u8,
531    /// Desired colour temperature, when the device supports it.
532    #[serde(default, skip_serializing_if = "Option::is_none")]
533    pub temperature_kelvin: Option<u16>,
534    /// Optional colour for a driver that exposes RGB controls.
535    #[serde(default, skip_serializing_if = "Option::is_none")]
536    pub color: Option<Rgb>,
537}
538
539const fn default_light_brightness() -> u8 {
540    100
541}
542
543impl Default for LightSettings {
544    fn default() -> Self {
545        Self {
546            enabled: true,
547            auto_camera: false,
548            brightness_percent: default_light_brightness(),
549            temperature_kelvin: None,
550            color: None,
551        }
552    }
553}
554
555impl LightSettings {
556    /// Create settings with a normalized brightness percentage.
557    #[must_use]
558    pub fn new(enabled: bool, brightness_percent: u8, temperature_kelvin: Option<u16>) -> Self {
559        Self {
560            enabled,
561            auto_camera: false,
562            brightness_percent: brightness_percent.min(100),
563            temperature_kelvin,
564            color: None,
565        }
566    }
567}
568
569#[expect(
570    clippy::trivially_copy_pass_by_ref,
571    reason = "serde's skip_serializing_if requires a fn(&T) -> bool signature"
572)]
573const fn is_false(value: &bool) -> bool {
574    !*value
575}
576
577impl Default for Lighting {
578    fn default() -> Self {
579        Self {
580            enabled: default_lighting_enabled(),
581            color: default_lighting_color(),
582            brightness: default_lighting_brightness(),
583        }
584    }
585}
586
587fn default_lighting_enabled() -> bool {
588    true
589}
590
591fn default_lighting_color() -> Rgb {
592    Rgb::WHITE
593}
594
595fn default_lighting_brightness() -> u8 {
596    100
597}
598
599/// Reject brightness outside the UI and hardware contract.
600fn deserialize_brightness<'de, D>(deserializer: D) -> Result<u8, D::Error>
601where
602    D: serde::Deserializer<'de>,
603{
604    let value = u8::deserialize(deserializer)?;
605    if value <= 100 {
606        Ok(value)
607    } else {
608        Err(serde::de::Error::custom(format_args!(
609            "brightness must be between 0 and 100, got {value}"
610        )))
611    }
612}
613
614/// Accept the optional `#` prefix supported by older releases, then parse the
615/// validated RGB value.
616fn deserialize_lighting_color<'de, D>(deserializer: D) -> Result<Rgb, D::Error>
617where
618    D: serde::Deserializer<'de>,
619{
620    let color = String::deserialize(deserializer)?;
621    color
622        .strip_prefix('#')
623        .unwrap_or(color.as_str())
624        .parse()
625        .map_err(serde::de::Error::custom)
626}
627
628/// Per-webcam UVC controls, keyed by control name (`brightness`, `focus`,
629/// `focus_auto`, …). Each value is the raw device unit (its scale comes from
630/// the camera's own min/max); auto toggles store 0/1. Persisted so values
631/// survive an unplug or reboot — the GUI re-applies them over USB when the
632/// camera is next viewed, since the hardware only retains them until it loses
633/// power. Serializes to the same TOML table the earlier fixed-field struct
634/// wrote, so existing saved controls load unchanged.
635#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
636#[serde(transparent)]
637pub struct CameraControls(pub BTreeMap<String, i32>);
638
639/// Vertical wheel reporting resolution for HID++ `0x2121 HiResWheel`.
640#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
641#[serde(rename_all = "snake_case")]
642pub enum ScrollResolution {
643    /// One scroll report per physical ratchet step.
644    Low,
645    /// Finer-grained reports between physical ratchet steps.
646    High,
647}
648
649/// Scroll-wheel mode for [`SmartShift`]: free-spin or ratchet (clicky).
650#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
651#[serde(rename_all = "snake_case")]
652pub enum WheelMode {
653    /// Free-spin — the wheel rotates without détentes.
654    Free,
655    /// Ratchet (clicky) scrolling. With SmartShift enabled the firmware
656    /// auto-releases into free-spin past the configured
657    /// [`auto_disengage`](SmartShift::auto_disengage) speed.
658    Ratchet,
659}
660
661/// SmartShift auto-disengage out-of-box default (`16` ≈ 4 turn/s, per the
662/// x2110 / x2111 spec). The sensitivity slider's default.
663pub const SMARTSHIFT_AUTO_DISENGAGE_DEFAULT: SmartShiftThreshold =
664    match SmartShiftThreshold::try_new(16) {
665        Ok(value) => value,
666        Err(_) => panic!("valid default SmartShift threshold"),
667    };
668
669/// Smallest auto-disengage threshold OpenLogi will store or apply (`8` ≈
670/// 2 turn/s). Below this the ratchet releases into free-spin at everyday scroll
671/// speeds, leaving the wheel "stuck" spinning (#317); `0` is also the firmware
672/// "do not change" sentinel that must never be stored as a real value. A
673/// persisted threshold below this floor is rejected on load.
674pub const SMARTSHIFT_MIN_AUTO_DISENGAGE: SmartShiftThreshold = match SmartShiftThreshold::try_new(8)
675{
676    Ok(value) => value,
677    Err(_) => panic!("valid minimum SmartShift threshold"),
678};
679
680/// Reject a persisted auto-disengage threshold below the supported floor.
681fn deserialize_auto_disengage<'de, D>(deserializer: D) -> Result<SmartShiftAutoDisengage, D::Error>
682where
683    D: serde::Deserializer<'de>,
684{
685    let value = SmartShiftAutoDisengage::deserialize(deserializer)?;
686    match value {
687        SmartShiftAutoDisengage::Threshold(threshold)
688            if threshold < SMARTSHIFT_MIN_AUTO_DISENGAGE =>
689        {
690            Err(serde::de::Error::custom(format_args!(
691                "SmartShift auto_disengage must be between {SMARTSHIFT_MIN_AUTO_DISENGAGE} and 255, got {threshold}"
692            )))
693        }
694        _ => Ok(value),
695    }
696}
697
698/// Per-device SmartShift wheel configuration, persisted so the agent can
699/// re-apply it when the device reconnects: the values are written to device
700/// RAM and do not survive a power cycle (#189), despite earlier assumptions
701/// that the device kept them in NVM.
702///
703/// Config-file only — never crosses the IPC (the agent reads it from
704/// `config.toml` on reload), so it is free to evolve without a
705/// `PROTOCOL_VERSION` bump.
706#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
707#[serde(deny_unknown_fields)]
708pub struct SmartShift {
709    /// The persisted wheel mode, re-applied to device RAM on reconnect.
710    pub mode: WheelMode,
711    /// SmartShift auto-disengage threshold (`0x08`–`0xFE`, in 0.25 turn/s
712    /// steps), or `0xFF` for a permanently engaged ratchet. A persisted value
713    /// below [`SMARTSHIFT_MIN_AUTO_DISENGAGE`] is rejected on load.
714    #[serde(deserialize_with = "deserialize_auto_disengage")]
715    pub auto_disengage: SmartShiftAutoDisengage,
716    /// Firmware tunable-torque level (`1`–`255`), `0` when the device does not
717    /// expose tunable torque. HID++ defines the full non-zero byte range.
718    #[serde(with = "crate::hid::smartshift::optional_tunable_torque")]
719    pub tunable_torque: Option<TunableTorque>,
720}
721
722/// The v3-and-older owner-lock choice: which control owned a device's single
723/// gesture role. Deserialize-only since v4 — the load migration
724/// (`Config::migrate_owner_locked_gestures`) consumes it and rewrites the
725/// binding shapes, which are the whole truth from then on. Read as a bare TOML
726/// scalar (`"Off"` or a [`ButtonId`] name).
727#[derive(Clone, Copy, Debug, PartialEq, Eq)]
728pub(super) enum GestureOwner {
729    /// Gestures were explicitly turned off for this device.
730    Off,
731    /// The named button owned the gesture role.
732    Button(ButtonId),
733}
734
735/// Lenient legacy deserializer for v3-and-older `gesture_owner`. Those releases
736/// already treated an unknown value as absent and inferred the owner; preserving
737/// that behavior keeps migration compatible. Current schemas reject the field
738/// before device deserialization.
739pub(super) fn deserialize_gesture_owner<'de, D>(
740    deserializer: D,
741) -> Result<Option<GestureOwner>, D::Error>
742where
743    D: serde::Deserializer<'de>,
744{
745    let s = String::deserialize(deserializer)?;
746    if s == "Off" {
747        return Ok(Some(GestureOwner::Off));
748    }
749    // Parse the button name with a throwaway error type so an unknown token maps
750    // to `None` (infer) rather than propagating an error.
751    let button = ButtonId::deserialize(
752        serde::de::value::StrDeserializer::<serde::de::value::Error>::new(&s),
753    )
754    .ok();
755    Ok(button.map(GestureOwner::Button))
756}
757
758#[cfg(test)]
759mod tests {
760    use super::*;
761
762    #[test]
763    fn smartshift_rejects_values_outside_the_persisted_contract() {
764        let parse = |auto_disengage: u8, tunable_torque: u8| {
765            let body = format!(
766                "mode = \"ratchet\"\nauto_disengage = {auto_disengage}\ntunable_torque = {tunable_torque}\n"
767            );
768            toml::from_str::<SmartShift>(&body)
769        };
770        let minimum = u8::from(SMARTSHIFT_MIN_AUTO_DISENGAGE);
771        parse(minimum - 1, 50)
772            .expect_err("auto_disengage below the persisted minimum must be rejected");
773        parse(minimum, 50).expect("the minimum itself is in contract");
774        parse(0xff, 0xff).expect("the top of both ranges is in contract");
775        assert_eq!(
776            parse(minimum, 0)
777                .expect("zero torque represents unsupported hardware")
778                .tunable_torque,
779            None
780        );
781    }
782
783    #[test]
784    fn floating_thumbwheel_sensitivity_rounds_and_saturates_into_the_domain() {
785        assert_eq!(u8::from(ThumbwheelSensitivity::from_rounded(49.6)), 50);
786        assert_eq!(
787            ThumbwheelSensitivity::from_rounded(f32::NAN),
788            ThumbwheelSensitivity::MIN
789        );
790        assert_eq!(
791            ThumbwheelSensitivity::from_rounded(f32::NEG_INFINITY),
792            ThumbwheelSensitivity::MIN
793        );
794        assert_eq!(
795            ThumbwheelSensitivity::from_rounded(f32::INFINITY),
796            ThumbwheelSensitivity::MAX
797        );
798    }
799
800    #[test]
801    fn floating_vertical_scroll_sensitivity_rounds_and_saturates_into_the_domain() {
802        assert_eq!(u8::from(VerticalScrollSensitivity::from_rounded(49.6)), 50);
803        assert_eq!(
804            VerticalScrollSensitivity::from_rounded(f32::NAN),
805            VerticalScrollSensitivity::MIN
806        );
807        assert_eq!(
808            VerticalScrollSensitivity::from_rounded(f32::NEG_INFINITY),
809            VerticalScrollSensitivity::MIN
810        );
811        assert_eq!(
812            VerticalScrollSensitivity::from_rounded(f32::INFINITY),
813            VerticalScrollSensitivity::MAX
814        );
815    }
816}