wayland-mouse 0.8.0

Mac-like mouse acceleration for Wayland — pointer + scroll-wheel, tuned below the compositor via evdev/uinput.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
//! Configuration: layered TOML (`preset` → global overrides → per-device
//! overrides → DPI rescale) deserialized with serde, resolved into a flat
//! [`Settings`] the hot path uses.
//!
//! The file format is human-friendly (`[wheel] max_multiplier = 6.0`); the
//! runtime struct keeps the original mathematical field names. One serde type
//! tree is the single source of truth a future GUI can round-trip.

use std::fs;
use std::path::Path;
use std::time::Duration;

use serde::{Deserialize, Serialize};

/// Where the system config lives (a directory, so we can grow into it).
pub const CONFIG_DIR: &str = "/etc/wayland-mouse";
pub const CONFIG_PATH: &str = "/etc/wayland-mouse/config.toml";

/// The `ptr_*` curve in every preset is expressed at this DPI; [`rescale`] maps
/// it to the device's actual DPI so the feel is DPI-independent (like macOS).
pub const REFERENCE_DPI: f64 = 1400.0;

/// Commented starter config written by `install` when none exists.
pub const DEFAULT_TEMPLATE: &str = include_str!("../wayland-mouse.toml.example");

// ---------------------------------------------------------------------------
// Runtime settings (resolved, per device — what the hot path reads)
// ---------------------------------------------------------------------------

#[derive(Clone, Debug)]
pub struct Settings {
    // wheel acceleration
    pub wheel_enabled: bool,
    pub threshold_dps: f64,
    pub accel: f64,
    pub exponent: f64,
    pub max_mult: f64,
    /// Multiplier floor at slow speed. < 1.0 de-amplifies slow scrolling for
    /// finer control in magnitude apps (Chrome/Firefox); 1.0 = no floor.
    pub min_mult: f64,
    pub attack: f64,
    pub release: f64,
    pub reset_gap: Duration,
    /// Emit acceleration as extra whole-detent notches (each its own SYN frame)
    /// instead of one inflated hi-res delta, so apps that scroll a fixed amount
    /// per wheel event (Flutter/Electron, e.g. the Ubuntu App Center) honor it.
    pub wheel_discrete_steps: bool,
    /// Only emit those notches once the multiplier reaches this; below it a
    /// single fine hi-res event keeps smooth apps gliding. 1.0 = always notch.
    pub step_start: f64,

    // pointer acceleration (macOS-like logistic S-curve)
    pub pointer_accel: bool,
    pub ptr_base: f64,
    pub ptr_max: f64,
    pub ptr_mid: f64,
    pub ptr_width: f64,
    pub ptr_tau: f64,
    pub dpi: f64,

    pub debug: bool,
}

// ---------------------------------------------------------------------------
// Presets — concrete curve sets, expressed at REFERENCE_DPI
// ---------------------------------------------------------------------------

/// Names accepted for the built-in presets (for validation / docs).
pub const PRESET_NAMES: &[&str] = &["mac-like", "subtle", "off"];

fn mac_like() -> Settings {
    Settings {
        wheel_enabled: true,
        threshold_dps: 5.0,
        accel: 0.06,
        exponent: 1.0,
        max_mult: 6.0,
        // Slow scroll runs a touch below 1:1 for finer control in magnitude apps
        // (Chrome/Firefox); notches only kick in past 1.5× so those apps glide
        // until a fast flick. Tuned by feel; see the wheel module for the math.
        min_mult: 0.9,
        attack: 0.6,
        release: 0.15,
        reset_gap: Duration::from_millis(180),
        wheel_discrete_steps: true,
        step_start: 1.5,

        pointer_accel: true,
        ptr_base: 0.5,
        ptr_max: 2.5,
        ptr_mid: 4000.0,
        ptr_width: 2000.0,
        ptr_tau: 0.006,
        dpi: REFERENCE_DPI,

        debug: false,
    }
}

/// A gentle nudge rather than a transformation: kicks in later, ramps softer,
/// lower caps.
fn subtle() -> Settings {
    Settings {
        wheel_enabled: true,
        threshold_dps: 10.0,
        accel: 0.05,
        exponent: 1.0,
        max_mult: 4.0,
        min_mult: 1.0,
        attack: 0.5,
        release: 0.15,
        reset_gap: Duration::from_millis(180),
        wheel_discrete_steps: true,
        step_start: 1.0,

        pointer_accel: true,
        ptr_base: 0.8,
        ptr_max: 1.6,
        ptr_mid: 5000.0,
        ptr_width: 2500.0,
        ptr_tau: 0.012,
        dpi: REFERENCE_DPI,

        debug: false,
    }
}

/// Pure passthrough: both subsystems off, identity values if ever consulted.
fn off() -> Settings {
    Settings {
        wheel_enabled: false,
        threshold_dps: 0.0,
        accel: 0.0,
        exponent: 1.0,
        max_mult: 1.0,
        min_mult: 1.0,
        attack: 1.0,
        release: 1.0,
        reset_gap: Duration::from_millis(180),
        wheel_discrete_steps: false,
        step_start: 1.0,

        pointer_accel: false,
        ptr_base: 1.0,
        ptr_max: 1.0,
        ptr_mid: 4000.0,
        ptr_width: 2000.0,
        ptr_tau: 0.012,
        dpi: REFERENCE_DPI,

        debug: false,
    }
}

/// Resolve a preset by name; `None` if unknown (caller decides the fallback).
fn preset(name: &str) -> Option<Settings> {
    match name.trim().to_lowercase().as_str() {
        "mac-like" | "mac" | "macos" | "mac_like" => Some(mac_like()),
        "subtle" | "gentle" => Some(subtle()),
        "off" | "flat" | "none" | "passthrough" => Some(off()),
        _ => None,
    }
}

/// The preset's config-space (un-rescaled) settings, falling back to mac-like.
/// The tuner uses this to show effective values before any override is applied.
#[cfg(feature = "tune")]
pub fn preset_or_default(name: &str) -> Settings {
    preset(name).unwrap_or_else(mac_like)
}

// ---------------------------------------------------------------------------
// On-disk format (serde)
// ---------------------------------------------------------------------------

#[derive(Deserialize, Serialize, Clone, Debug, PartialEq)]
#[serde(default)]
pub struct ConfigFile {
    pub preset: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dpi: Option<f64>,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub name_filter: String,
    #[serde(skip_serializing_if = "is_false")]
    pub debug: bool,
    #[serde(skip_serializing_if = "WheelCfg::is_empty")]
    pub wheel: WheelCfg,
    #[serde(skip_serializing_if = "PointerCfg::is_empty")]
    pub pointer: PointerCfg,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub device: Vec<DeviceRule>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub button: Vec<ButtonRule>,
}

impl Default for ConfigFile {
    fn default() -> Self {
        ConfigFile {
            preset: "mac-like".to_string(),
            dpi: None,
            name_filter: String::new(),
            debug: false,
            wheel: WheelCfg::default(),
            pointer: PointerCfg::default(),
            device: Vec::new(),
            button: Vec::new(),
        }
    }
}

/// A button → key-combo mapping. `match` is a button name (`BTN_SIDE` or
/// `side`); `keys` is the combo (`["Super", "Page_Up"]`); `mode` is `tap`
/// (default, press+release on button-down) or `hold` (mirror the button).
#[derive(Deserialize, Serialize, Default, Clone, Debug, PartialEq)]
#[serde(default)]
pub struct ButtonRule {
    #[serde(rename = "match")]
    pub match_: String,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub keys: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mode: Option<String>,
}

#[derive(Deserialize, Serialize, Default, Clone, Debug, PartialEq)]
#[serde(default)]
pub struct WheelCfg {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_speed: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub strength: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub curve: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_multiplier: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub smoothing_up: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub smoothing_down: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_multiplier: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reset_after_ms: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub discrete_steps: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub steps_above: Option<f64>,
}

impl WheelCfg {
    fn is_empty(&self) -> bool {
        self.enabled.is_none()
            && self.start_speed.is_none()
            && self.strength.is_none()
            && self.curve.is_none()
            && self.max_multiplier.is_none()
            && self.min_multiplier.is_none()
            && self.smoothing_up.is_none()
            && self.smoothing_down.is_none()
            && self.reset_after_ms.is_none()
            && self.discrete_steps.is_none()
            && self.steps_above.is_none()
    }
}

#[derive(Deserialize, Serialize, Default, Clone, Debug, PartialEq)]
#[serde(default)]
pub struct PointerCfg {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub precision_gain: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_gain: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub midpoint_speed: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub transition_width: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub smoothing_ms: Option<f64>,
}

impl PointerCfg {
    fn is_empty(&self) -> bool {
        self.enabled.is_none()
            && self.precision_gain.is_none()
            && self.max_gain.is_none()
            && self.midpoint_speed.is_none()
            && self.transition_width.is_none()
            && self.smoothing_ms.is_none()
    }
}

#[derive(Deserialize, Serialize, Default, Clone, Debug, PartialEq)]
#[serde(default)]
pub struct DeviceRule {
    /// Case-insensitive substring matched against the device name.
    #[serde(rename = "match")]
    pub match_: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub preset: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dpi: Option<f64>,
    #[serde(skip_serializing_if = "WheelCfg::is_empty")]
    pub wheel: WheelCfg,
    #[serde(skip_serializing_if = "PointerCfg::is_empty")]
    pub pointer: PointerCfg,
}

fn is_false(b: &bool) -> bool {
    !*b
}

// ---------------------------------------------------------------------------
// Resolution
// ---------------------------------------------------------------------------

impl ConfigFile {
    /// First device rule whose `match` substring is in `device_name`.
    fn rule_for<'a>(&'a self, device_name: &str) -> Option<&'a DeviceRule> {
        let lname = device_name.to_lowercase();
        self.device
            .iter()
            .find(|d| !d.match_.is_empty() && lname.contains(&d.match_.to_lowercase()))
    }

    /// Resolve the effective [`Settings`] for a device by name.
    ///
    /// Layering: base preset (device rule's preset if set, else the global
    /// preset) → global overrides → device overrides → DPI rescale.
    pub fn resolve(&self, device_name: &str) -> Settings {
        let rule = self.rule_for(device_name);
        let preset_name = rule
            .and_then(|r| r.preset.as_deref())
            .unwrap_or(&self.preset);
        let mut s = preset(preset_name).unwrap_or_else(|| {
            eprintln!("wayland-mouse: unknown preset {preset_name:?}, using 'mac-like'");
            mac_like()
        });

        apply_wheel(&mut s, &self.wheel);
        apply_pointer(&mut s, &self.pointer);
        if let Some(r) = rule {
            apply_wheel(&mut s, &r.wheel);
            apply_pointer(&mut s, &r.pointer);
        }

        s.dpi = rule
            .and_then(|r| r.dpi)
            .or(self.dpi)
            .unwrap_or(REFERENCE_DPI);
        s.debug = self.debug;
        rescale(&mut s);
        s
    }

    /// Effective settings with no device rule applied (the global baseline).
    pub fn resolve_global(&self) -> Settings {
        self.resolve("")
    }

    /// Config-space (un-rescaled) global settings: preset + global overrides,
    /// before DPI rescale. This is what the tuner edits and plots — the values
    /// as they appear in the file, independent of DPI.
    #[cfg(feature = "tune")]
    pub fn resolve_unscaled(&self) -> Settings {
        let mut s = preset_or_default(&self.preset);
        apply_wheel(&mut s, &self.wheel);
        apply_pointer(&mut s, &self.pointer);
        s.dpi = self.dpi.unwrap_or(REFERENCE_DPI);
        s
    }
}

fn apply_wheel(s: &mut Settings, w: &WheelCfg) {
    if let Some(v) = w.enabled {
        s.wheel_enabled = v;
    }
    if let Some(v) = w.start_speed {
        s.threshold_dps = v;
    }
    if let Some(v) = w.strength {
        s.accel = v;
    }
    if let Some(v) = w.curve {
        s.exponent = v;
    }
    if let Some(v) = w.max_multiplier {
        s.max_mult = v;
    }
    if let Some(v) = w.min_multiplier {
        s.min_mult = v;
    }
    if let Some(v) = w.smoothing_up {
        s.attack = v;
    }
    if let Some(v) = w.smoothing_down {
        s.release = v;
    }
    if let Some(v) = w.reset_after_ms {
        s.reset_gap = Duration::from_secs_f64((v / 1000.0).max(0.0));
    }
    if let Some(v) = w.discrete_steps {
        s.wheel_discrete_steps = v;
    }
    if let Some(v) = w.steps_above {
        s.step_start = v;
    }
}

fn apply_pointer(s: &mut Settings, p: &PointerCfg) {
    if let Some(v) = p.enabled {
        s.pointer_accel = v;
    }
    if let Some(v) = p.precision_gain {
        s.ptr_base = v;
    }
    if let Some(v) = p.max_gain {
        s.ptr_max = v;
    }
    if let Some(v) = p.midpoint_speed {
        s.ptr_mid = v;
    }
    if let Some(v) = p.transition_width {
        s.ptr_width = v;
    }
    if let Some(v) = p.smoothing_ms {
        s.ptr_tau = (v / 1000.0).max(0.0);
    }
}

/// Map the REFERENCE_DPI curve onto the device's real DPI: speed breakpoints
/// scale up, gains scale down, so the on-screen feel stays identical.
fn rescale(s: &mut Settings) {
    if s.dpi > 0.0 {
        let k = s.dpi / REFERENCE_DPI;
        s.ptr_mid *= k;
        s.ptr_width *= k;
        s.ptr_base /= k;
        s.ptr_max /= k;
    }
}

// ---------------------------------------------------------------------------
// Loading
// ---------------------------------------------------------------------------

/// Load and parse the config. A missing file yields defaults (mac-like); only a
/// read or parse error is `Err`.
pub fn load(path: &Path) -> Result<ConfigFile, String> {
    let text = match fs::read_to_string(path) {
        Ok(t) => t,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(ConfigFile::default()),
        Err(e) => return Err(format!("reading {}: {e}", path.display())),
    };
    toml::from_str(&text).map_err(|e| format!("parsing {}:\n{e}", path.display()))
}

// ---------------------------------------------------------------------------
// `config --print` and `config --check`
// ---------------------------------------------------------------------------

/// Print the effective (post-rescale) settings and any device rules.
pub fn print_effective(path: &Path) -> i32 {
    let cf = match load(path) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("error: {e}");
            return 1;
        }
    };
    if path.exists() {
        println!("# effective config from {}", path.display());
    } else {
        println!(
            "# no config at {} — built-in defaults (preset = mac-like)",
            path.display()
        );
    }
    print_settings("global", &cf.resolve_global());
    for r in &cf.device {
        if r.match_.is_empty() {
            continue;
        }
        println!();
        print_settings(
            &format!("device matching {:?}", r.match_),
            &cf.resolve(&r.match_),
        );
    }
    if !cf.button.is_empty() {
        println!("\n[buttons]");
        for b in &cf.button {
            let mode = b.mode.as_deref().unwrap_or("tap");
            println!("  {} -> {}  ({mode})", b.match_, b.keys.join(" + "));
        }
    }
    0
}

fn print_settings(label: &str, s: &Settings) {
    println!("[{label}]  dpi = {}", s.dpi);
    println!(
        "  wheel:   enabled={} start_speed={} strength={} curve={} max_multiplier={} \
         min_multiplier={} smoothing_up={} smoothing_down={} reset_after_ms={:.0} \
         discrete_steps={} steps_above={}",
        s.wheel_enabled,
        s.threshold_dps,
        s.accel,
        s.exponent,
        s.max_mult,
        s.min_mult,
        s.attack,
        s.release,
        s.reset_gap.as_secs_f64() * 1000.0,
        s.wheel_discrete_steps,
        s.step_start,
    );
    println!(
        "  pointer: enabled={} precision_gain={:.3} max_gain={:.3} midpoint_speed={:.0} \
         transition_width={:.0} smoothing_ms={:.1}  (values shown after DPI rescale)",
        s.pointer_accel,
        s.ptr_base,
        s.ptr_max,
        s.ptr_mid,
        s.ptr_width,
        s.ptr_tau * 1000.0,
    );
}

/// Validate the config: syntax, unknown keys (warn), value ranges (warn),
/// unknown presets (warn). Returns a process exit code (non-zero only on a
/// hard parse error).
pub fn check(path: &Path) -> i32 {
    let text = match fs::read_to_string(path) {
        Ok(t) => t,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            println!(
                "no config at {} — built-in defaults apply (preset = mac-like)",
                path.display()
            );
            return 0;
        }
        Err(e) => {
            eprintln!("error reading {}: {e}", path.display());
            return 1;
        }
    };

    // 1. Syntax + typed parse.
    let value: toml::Value = match toml::from_str(&text) {
        Ok(v) => v,
        Err(e) => {
            eprintln!("✗ parse error in {}:\n{e}", path.display());
            return 1;
        }
    };
    let cf: ConfigFile = match toml::from_str(&text) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("{}:\n{e}", path.display());
            return 1;
        }
    };

    let mut warnings = 0u32;
    let mut warn = |msg: String| {
        eprintln!("{msg}");
        warnings += 1;
    };

    // 2. Unknown keys.
    const TOP: &[&str] = &[
        "preset",
        "dpi",
        "name_filter",
        "debug",
        "wheel",
        "pointer",
        "device",
        "button",
    ];
    const BUTTON: &[&str] = &["match", "keys", "mode"];
    const WHEEL: &[&str] = &[
        "enabled",
        "start_speed",
        "strength",
        "curve",
        "max_multiplier",
        "min_multiplier",
        "smoothing_up",
        "smoothing_down",
        "reset_after_ms",
        "discrete_steps",
        "steps_above",
    ];
    const POINTER: &[&str] = &[
        "enabled",
        "precision_gain",
        "max_gain",
        "midpoint_speed",
        "transition_width",
        "smoothing_ms",
    ];
    const DEVICE: &[&str] = &["match", "preset", "dpi", "wheel", "pointer"];

    if let Some(t) = value.as_table() {
        unknowns(t, TOP, "", &mut warn);
        if let Some(w) = t.get("wheel").and_then(|v| v.as_table()) {
            unknowns(w, WHEEL, "wheel.", &mut warn);
        }
        if let Some(p) = t.get("pointer").and_then(|v| v.as_table()) {
            unknowns(p, POINTER, "pointer.", &mut warn);
        }
        if let Some(arr) = t.get("device").and_then(|v| v.as_array()) {
            for (i, d) in arr.iter().enumerate() {
                if let Some(dt) = d.as_table() {
                    unknowns(dt, DEVICE, &format!("device[{i}]."), &mut warn);
                    if let Some(w) = dt.get("wheel").and_then(|v| v.as_table()) {
                        unknowns(w, WHEEL, &format!("device[{i}].wheel."), &mut warn);
                    }
                    if let Some(p) = dt.get("pointer").and_then(|v| v.as_table()) {
                        unknowns(p, POINTER, &format!("device[{i}].pointer."), &mut warn);
                    }
                }
            }
        }
        if let Some(arr) = t.get("button").and_then(|v| v.as_array()) {
            for (i, b) in arr.iter().enumerate() {
                if let Some(bt) = b.as_table() {
                    unknowns(bt, BUTTON, &format!("button[{i}]."), &mut warn);
                }
            }
        }
    }

    // 3. Preset names.
    if preset(&cf.preset).is_none() {
        warn(format!(
            "preset {:?} is unknown (valid: {})",
            cf.preset,
            PRESET_NAMES.join(", ")
        ));
    }
    for r in &cf.device {
        if let Some(p) = &r.preset {
            if preset(p).is_none() {
                warn(format!("device {:?}: preset {:?} is unknown", r.match_, p));
            }
        }
    }

    // 4. Value ranges (on the resolved global settings).
    validate_ranges(&cf.resolve_global(), &mut warn);

    // 5. Button rules.
    crate::remap::validate_buttons(&cf.button, &mut warn);

    if warnings == 0 {
        println!("{} is valid", path.display());
    } else {
        println!(
            "{} warning(s); config still loads (unknown keys/values are ignored or clamped)",
            warnings
        );
    }
    0
}

fn unknowns(table: &toml::Table, allowed: &[&str], prefix: &str, warn: &mut impl FnMut(String)) {
    for k in table.keys() {
        if !allowed.contains(&k.as_str()) {
            warn(format!("unknown key '{prefix}{k}'"));
        }
    }
}

fn validate_ranges(s: &Settings, warn: &mut impl FnMut(String)) {
    if s.dpi <= 0.0 {
        warn(format!("dpi must be > 0 (got {})", s.dpi));
    }
    if s.threshold_dps < 0.0 {
        warn("wheel.start_speed should be >= 0".into());
    }
    if s.accel < 0.0 {
        warn("wheel.strength should be >= 0".into());
    }
    if s.exponent <= 0.0 {
        warn("wheel.curve should be > 0".into());
    }
    if s.max_mult < 1.0 {
        warn("wheel.max_multiplier should be >= 1.0".into());
    }
    if s.min_mult <= 0.0 {
        warn("wheel.min_multiplier should be > 0".into());
    }
    if s.min_mult > s.max_mult {
        warn("wheel.min_multiplier is above max_multiplier (curve flattens to max)".into());
    }
    if s.step_start < 1.0 {
        warn("wheel.steps_above should be >= 1.0".into());
    }
    for (name, v) in [("smoothing_up", s.attack), ("smoothing_down", s.release)] {
        if v <= 0.0 || v > 1.0 {
            warn(format!("wheel.{name} should be in (0, 1] (got {v})"));
        }
    }
    if s.ptr_base <= 0.0 {
        warn("pointer.precision_gain should be > 0".into());
    }
    if s.ptr_max < s.ptr_base {
        warn("pointer.max_gain is below precision_gain (curve will invert)".into());
    }
    if s.ptr_mid <= 0.0 {
        warn("pointer.midpoint_speed should be > 0".into());
    }
    if s.ptr_width <= 0.0 {
        warn("pointer.transition_width should be > 0".into());
    }
    if s.ptr_tau <= 0.0 {
        warn("pointer.smoothing_ms should be > 0".into());
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn approx(a: f64, b: f64) -> bool {
        (a - b).abs() < 1e-9
    }

    #[test]
    fn default_is_mac_like() {
        let s = ConfigFile::default().resolve_global();
        assert!(s.wheel_enabled && s.pointer_accel);
        assert!(s.wheel_discrete_steps); // on by default so App Center-class apps accelerate
        assert!(approx(s.threshold_dps, 5.0));
        assert!(approx(s.accel, 0.06));
        assert!(approx(s.max_mult, 6.0));
        // Slight slow-speed de-amp + notches only past 1.5× (tuned by feel).
        assert!(approx(s.min_mult, 0.9));
        assert!(approx(s.step_start, 1.5));
        // dpi == reference, so the curve is unscaled
        assert!(approx(s.ptr_base, 0.5));
        assert!(approx(s.ptr_max, 2.5));
        assert!(approx(s.ptr_mid, 4000.0));
        assert!(approx(s.dpi, 1400.0));
    }

    #[test]
    fn wheel_min_and_step_overrides_apply() {
        let cf: ConfigFile = toml::from_str(
            "preset = \"mac-like\"\n[wheel]\nmin_multiplier = 0.8\nsteps_above = 2.0\n",
        )
        .unwrap();
        let s = cf.resolve_global();
        assert!(approx(s.min_mult, 0.8));
        assert!(approx(s.step_start, 2.0));
        // other wheel knobs still come from the preset
        assert!(approx(s.max_mult, 6.0));
    }

    #[test]
    fn preset_off_disables_both() {
        let cf: ConfigFile = toml::from_str("preset = \"off\"").unwrap();
        let s = cf.resolve_global();
        assert!(!s.wheel_enabled);
        assert!(!s.pointer_accel);
    }

    #[test]
    fn global_override_layers_on_preset() {
        let cf: ConfigFile = toml::from_str(
            "preset = \"mac-like\"\n[pointer]\nmax_gain = 4.0\n[wheel]\nenabled = false\n",
        )
        .unwrap();
        let s = cf.resolve_global();
        assert!(approx(s.ptr_max, 4.0)); // overridden
        assert!(approx(s.ptr_base, 0.5)); // preset default kept
        assert!(!s.wheel_enabled); // overridden
    }

    #[test]
    fn dpi_rescale_keeps_feel() {
        // k = 2800/1400 = 2: speed breakpoints double, gains halve.
        let cf: ConfigFile = toml::from_str("preset = \"mac-like\"\ndpi = 2800\n").unwrap();
        let s = cf.resolve_global();
        assert!(approx(s.ptr_mid, 8000.0));
        assert!(approx(s.ptr_width, 4000.0));
        assert!(approx(s.ptr_base, 0.25));
        assert!(approx(s.ptr_max, 1.25));
    }

    #[test]
    fn per_device_rule_matches_and_overrides() {
        let cf: ConfigFile = toml::from_str(
            "preset = \"mac-like\"\n\
             [[device]]\nmatch = \"Logitech\"\npreset = \"off\"\n\
             [[device]]\nmatch = \"Trackball\"\n[device.pointer]\nenabled = false\n",
        )
        .unwrap();
        // non-matching device falls back to the global preset
        assert!(cf.resolve("Razer DeathAdder").pointer_accel);
        // "Logitech" → off preset
        let log = cf.resolve("Logitech USB Receiver Mouse");
        assert!(!log.wheel_enabled && !log.pointer_accel);
        // "Trackball" → mac-like base, pointer disabled by the device override
        let tb = cf.resolve("Kensington Trackball");
        assert!(tb.wheel_enabled && !tb.pointer_accel);
    }

    #[test]
    fn unknown_preset_falls_back_without_panicking() {
        let cf: ConfigFile = toml::from_str("preset = \"bogus\"").unwrap();
        let s = cf.resolve_global();
        assert!(approx(s.threshold_dps, 5.0)); // mac-like fallback
    }

    #[test]
    fn shipped_example_is_valid() {
        let cf: ConfigFile = toml::from_str(DEFAULT_TEMPLATE).unwrap();
        let _ = cf.resolve_global();
        assert_eq!(cf.preset, "mac-like");
    }

    #[test]
    fn button_rules_parse_from_toml() {
        let cf: ConfigFile = toml::from_str(
            "preset = \"mac-like\"\n\
             [[button]]\nmatch = \"BTN_SIDE\"\nkeys = [\"Super\", \"Page_Up\"]\n",
        )
        .unwrap();
        assert_eq!(cf.button.len(), 1);
        assert_eq!(cf.button[0].match_, "BTN_SIDE"); // #[serde(rename = "match")]
        assert_eq!(cf.button[0].keys, vec!["Super", "Page_Up"]);
    }
}