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