pinready 0.4.0

Cross-platform configurator and launcher for Visual Pinball standalone
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
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
use sdl3_sys::everything::*;
use std::ffi::CStr;
use std::thread;

/// An input action that can be mapped to a key or button.
#[derive(Clone)]
pub struct InputAction {
    pub setting_id: &'static str,
    pub label: &'static str,
    pub default_scancode: SDL_Scancode,
    pub essential: bool,
    pub mapping: Option<CapturedInput>,
}

/// A captured input event (keyboard or joystick).
#[derive(Clone)]
pub enum CapturedInput {
    Keyboard {
        scancode: SDL_Scancode,
        name: String,
    },
    JoystickButton {
        device_id: String,
        button: u8,
        name: String,
    },
    #[allow(dead_code)]
    JoystickAxis {
        device_id: String,
        axis: u8,
        name: String,
    },
}

impl CapturedInput {
    /// Format as VPX ini mapping string.
    pub fn to_mapping_string(&self) -> String {
        match self {
            Self::Keyboard { scancode, .. } => {
                format!("Key;{}", scancode.0)
            }
            Self::JoystickButton {
                device_id, button, ..
            } => {
                format!("{device_id};{button}")
            }
            Self::JoystickAxis {
                device_id, axis, ..
            } => {
                format!("{device_id};{axis}")
            }
        }
    }

    pub fn display_name(&self) -> &str {
        match self {
            Self::Keyboard { name, .. }
            | Self::JoystickButton { name, .. }
            | Self::JoystickAxis { name, .. } => name,
        }
    }
}

/// Joystick events sent from the SDL3 joystick thread to the UI.
#[derive(Clone)]
pub enum JoystickEvent {
    ButtonDown {
        device_id: String,
        button: u8,
        name: String,
    },
    #[allow(dead_code)]
    AxisMotion {
        device_id: String,
        axis: u8,
        name: String,
    },
    /// Live accelerometer/axis data for visualization (axis_id, normalized value -1.0 to 1.0)
    AccelUpdate { x: f32, y: f32 },
    /// A Pinscape controller was detected with this VPX device ID
    PinscapeDetected { vpx_id: String },
    /// A generic gamepad was detected with this VPX device ID
    GamepadDetected { vpx_id: String, name: String },
}

/// Build the VPX-compatible device ID for an SDL joystick.
/// VPX format: `SDLJoy_<serial>` where serial comes from SDL_GetJoystickSerial.
/// Falls back to GUID string if no serial is available.
unsafe fn vpx_device_id(joy: *mut sdl3_sys::everything::SDL_Joystick) -> String {
    let serial_ptr = SDL_GetJoystickSerial(joy);
    if !serial_ptr.is_null() {
        let serial = CStr::from_ptr(serial_ptr).to_string_lossy();
        if !serial.is_empty() {
            return format!("SDLJoy_{serial}");
        }
    }
    // Fallback: use GUID as hex string
    let guid = SDL_GetJoystickGUID(joy);
    let mut buf = [0u8; 64];
    SDL_GUIDToString(guid, buf.as_mut_ptr() as *mut _, buf.len() as i32);
    let guid_str = CStr::from_ptr(buf.as_ptr() as *const _).to_string_lossy();
    format!("SDLJoy_{guid_str}")
}

/// Get a human-readable name for an SDL scancode.
pub fn scancode_name(scancode: SDL_Scancode) -> String {
    unsafe {
        let name_ptr = SDL_GetScancodeName(scancode);
        if !name_ptr.is_null() {
            let s = CStr::from_ptr(name_ptr).to_string_lossy().into_owned();
            if !s.is_empty() {
                return s;
            }
        }
    }
    format!("Key {}", scancode.0)
}

/// Convert an egui::Key to an SDL_Scancode.
/// This allows capturing keyboard input via egui (which has the window focus)
/// instead of a separate SDL3 thread.
pub fn egui_key_to_scancode(key: egui::Key) -> Option<SDL_Scancode> {
    use egui::Key;
    let sc = match key {
        Key::A => SDL_SCANCODE_A,
        Key::B => SDL_SCANCODE_B,
        Key::C => SDL_SCANCODE_C,
        Key::D => SDL_SCANCODE_D,
        Key::E => SDL_SCANCODE_E,
        Key::F => SDL_SCANCODE_F,
        Key::G => SDL_SCANCODE_G,
        Key::H => SDL_SCANCODE_H,
        Key::I => SDL_SCANCODE_I,
        Key::J => SDL_SCANCODE_J,
        Key::K => SDL_SCANCODE_K,
        Key::L => SDL_SCANCODE_L,
        Key::M => SDL_SCANCODE_M,
        Key::N => SDL_SCANCODE_N,
        Key::O => SDL_SCANCODE_O,
        Key::P => SDL_SCANCODE_P,
        Key::Q => SDL_SCANCODE_Q,
        Key::R => SDL_SCANCODE_R,
        Key::S => SDL_SCANCODE_S,
        Key::T => SDL_SCANCODE_T,
        Key::U => SDL_SCANCODE_U,
        Key::V => SDL_SCANCODE_V,
        Key::W => SDL_SCANCODE_W,
        Key::X => SDL_SCANCODE_X,
        Key::Y => SDL_SCANCODE_Y,
        Key::Z => SDL_SCANCODE_Z,
        Key::Num0 => SDL_SCANCODE_0,
        Key::Num1 => SDL_SCANCODE_1,
        Key::Num2 => SDL_SCANCODE_2,
        Key::Num3 => SDL_SCANCODE_3,
        Key::Num4 => SDL_SCANCODE_4,
        Key::Num5 => SDL_SCANCODE_5,
        Key::Num6 => SDL_SCANCODE_6,
        Key::Num7 => SDL_SCANCODE_7,
        Key::Num8 => SDL_SCANCODE_8,
        Key::Num9 => SDL_SCANCODE_9,
        Key::Escape => SDL_SCANCODE_ESCAPE,
        Key::Tab => SDL_SCANCODE_TAB,
        Key::Space => SDL_SCANCODE_SPACE,
        Key::Enter => SDL_SCANCODE_RETURN,
        Key::Backspace => SDL_SCANCODE_BACKSPACE,
        Key::Delete => SDL_SCANCODE_DELETE,
        Key::Home => SDL_SCANCODE_HOME,
        Key::End => SDL_SCANCODE_END,
        Key::PageUp => SDL_SCANCODE_PAGEUP,
        Key::PageDown => SDL_SCANCODE_PAGEDOWN,
        Key::ArrowUp => SDL_SCANCODE_UP,
        Key::ArrowDown => SDL_SCANCODE_DOWN,
        Key::ArrowLeft => SDL_SCANCODE_LEFT,
        Key::ArrowRight => SDL_SCANCODE_RIGHT,
        Key::F1 => SDL_SCANCODE_F1,
        Key::F2 => SDL_SCANCODE_F2,
        Key::F3 => SDL_SCANCODE_F3,
        Key::F4 => SDL_SCANCODE_F4,
        Key::F5 => SDL_SCANCODE_F5,
        Key::F6 => SDL_SCANCODE_F6,
        Key::F7 => SDL_SCANCODE_F7,
        Key::F8 => SDL_SCANCODE_F8,
        Key::F9 => SDL_SCANCODE_F9,
        Key::F10 => SDL_SCANCODE_F10,
        Key::F11 => SDL_SCANCODE_F11,
        Key::F12 => SDL_SCANCODE_F12,
        Key::Minus => SDL_SCANCODE_MINUS,
        Key::Comma => SDL_SCANCODE_COMMA,
        Key::Period => SDL_SCANCODE_PERIOD,
        _ => return None,
    };
    Some(sc)
}

/// Check for modifier keys pressed in egui and return matching scancode.
pub fn egui_modifiers_to_scancode(modifiers: &egui::Modifiers) -> Option<SDL_Scancode> {
    if modifiers.shift && !modifiers.ctrl && !modifiers.alt {
        Some(SDL_SCANCODE_LSHIFT)
    } else if modifiers.ctrl && !modifiers.shift && !modifiers.alt {
        Some(SDL_SCANCODE_LCTRL)
    } else if modifiers.alt && !modifiers.shift && !modifiers.ctrl {
        Some(SDL_SCANCODE_LALT)
    } else {
        None
    }
}

/// Build the list of all mappable actions with their defaults.
pub fn default_actions() -> Vec<InputAction> {
    vec![
        // Essential — flippers, staged, magna, game commands
        InputAction {
            setting_id: "LeftFlipper",
            label: "input_left_flipper",
            default_scancode: SDL_SCANCODE_LSHIFT,
            essential: true,
            mapping: None,
        },
        InputAction {
            setting_id: "RightFlipper",
            label: "input_right_flipper",
            default_scancode: SDL_SCANCODE_RSHIFT,
            essential: true,
            mapping: None,
        },
        InputAction {
            setting_id: "LeftStagedFlipper",
            label: "input_left_staged_flipper",
            default_scancode: SDL_SCANCODE_LSHIFT,
            essential: true,
            mapping: None,
        },
        InputAction {
            setting_id: "RightStagedFlipper",
            label: "input_right_staged_flipper",
            default_scancode: SDL_SCANCODE_RSHIFT,
            essential: true,
            mapping: None,
        },
        InputAction {
            setting_id: "LeftMagna",
            label: "input_left_magna",
            default_scancode: SDL_SCANCODE_LCTRL,
            essential: true,
            mapping: None,
        },
        InputAction {
            setting_id: "RightMagna",
            label: "input_right_magna",
            default_scancode: SDL_SCANCODE_RCTRL,
            essential: true,
            mapping: None,
        },
        InputAction {
            setting_id: "Lockbar",
            label: "input_lockbar",
            default_scancode: SDL_SCANCODE_LALT,
            essential: true,
            mapping: None,
        },
        InputAction {
            setting_id: "ExtraBall",
            label: "input_extra_ball",
            default_scancode: SDL_SCANCODE_B,
            essential: true,
            mapping: None,
        },
        InputAction {
            setting_id: "LaunchBall",
            label: "input_launch_ball",
            default_scancode: SDL_SCANCODE_RETURN,
            essential: true,
            mapping: None,
        },
        InputAction {
            setting_id: "Start",
            label: "input_start",
            default_scancode: SDL_SCANCODE_1,
            essential: true,
            mapping: None,
        },
        InputAction {
            setting_id: "Credit1",
            label: "input_add_credit",
            default_scancode: SDL_SCANCODE_5,
            essential: true,
            mapping: None,
        },
        InputAction {
            setting_id: "ExitGame",
            label: "input_exit_game",
            default_scancode: SDL_SCANCODE_ESCAPE,
            essential: true,
            mapping: None,
        },
        // Advanced — coin door, services, keyboard nudge, etc.
        InputAction {
            setting_id: "Credit2",
            label: "input_credit_2",
            default_scancode: SDL_SCANCODE_4,
            essential: false,
            mapping: None,
        },
        InputAction {
            setting_id: "Credit3",
            label: "input_credit_3",
            default_scancode: SDL_SCANCODE_3,
            essential: false,
            mapping: None,
        },
        InputAction {
            setting_id: "Credit4",
            label: "input_credit_4",
            default_scancode: SDL_SCANCODE_6,
            essential: false,
            mapping: None,
        },
        InputAction {
            setting_id: "CoinDoor",
            label: "input_coin_door",
            default_scancode: SDL_SCANCODE_END,
            essential: false,
            mapping: None,
        },
        InputAction {
            setting_id: "SlamTilt",
            label: "input_slam_tilt",
            default_scancode: SDL_SCANCODE_HOME,
            essential: false,
            mapping: None,
        },
        InputAction {
            setting_id: "Reset",
            label: "input_reset",
            default_scancode: SDL_SCANCODE_F3,
            essential: false,
            mapping: None,
        },
        InputAction {
            setting_id: "Service1",
            label: "input_service1",
            default_scancode: SDL_SCANCODE_7,
            essential: false,
            mapping: None,
        },
        InputAction {
            setting_id: "Service2",
            label: "input_service2",
            default_scancode: SDL_SCANCODE_8,
            essential: false,
            mapping: None,
        },
        InputAction {
            setting_id: "Service3",
            label: "input_service3",
            default_scancode: SDL_SCANCODE_9,
            essential: false,
            mapping: None,
        },
        InputAction {
            setting_id: "Service4",
            label: "input_service4",
            default_scancode: SDL_SCANCODE_0,
            essential: false,
            mapping: None,
        },
        InputAction {
            setting_id: "Service5",
            label: "input_service5",
            default_scancode: SDL_SCANCODE_6,
            essential: false,
            mapping: None,
        },
        InputAction {
            setting_id: "Service6",
            label: "input_service6",
            default_scancode: SDL_SCANCODE_PAGEUP,
            essential: false,
            mapping: None,
        },
        InputAction {
            setting_id: "Service7",
            label: "input_service7",
            default_scancode: SDL_SCANCODE_MINUS,
            essential: false,
            mapping: None,
        },
        InputAction {
            setting_id: "Service8",
            label: "input_service8",
            default_scancode: SDL_SCANCODE_UNKNOWN,
            essential: false,
            mapping: None,
        },
        InputAction {
            setting_id: "LeftNudge",
            label: "input_left_nudge",
            default_scancode: SDL_SCANCODE_Z,
            essential: false,
            mapping: None,
        },
        InputAction {
            setting_id: "RightNudge",
            label: "input_right_nudge",
            default_scancode: SDL_SCANCODE_SLASH,
            essential: false,
            mapping: None,
        },
        InputAction {
            setting_id: "CenterNudge",
            label: "input_center_nudge",
            default_scancode: SDL_SCANCODE_SPACE,
            essential: false,
            mapping: None,
        },
        InputAction {
            setting_id: "Tilt",
            label: "input_tilt",
            default_scancode: SDL_SCANCODE_T,
            essential: false,
            mapping: None,
        },
        InputAction {
            setting_id: "Pause",
            label: "input_pause",
            default_scancode: SDL_SCANCODE_P,
            essential: false,
            mapping: None,
        },
        InputAction {
            setting_id: "VolumeDown",
            label: "input_volume_down",
            default_scancode: SDL_SCANCODE_MINUS,
            essential: false,
            mapping: None,
        },
        InputAction {
            setting_id: "VolumeUp",
            label: "input_volume_up",
            default_scancode: SDL_SCANCODE_EQUALS,
            essential: false,
            mapping: None,
        },
        InputAction {
            setting_id: "Custom1",
            label: "input_custom1",
            default_scancode: SDL_SCANCODE_UNKNOWN,
            essential: false,
            mapping: None,
        },
        InputAction {
            setting_id: "Custom2",
            label: "input_custom2",
            default_scancode: SDL_SCANCODE_UNKNOWN,
            essential: false,
            mapping: None,
        },
        InputAction {
            setting_id: "Custom3",
            label: "input_custom3",
            default_scancode: SDL_SCANCODE_UNKNOWN,
            essential: false,
            mapping: None,
        },
        InputAction {
            setting_id: "Custom4",
            label: "input_custom4",
            default_scancode: SDL_SCANCODE_UNKNOWN,
            essential: false,
            mapping: None,
        },
    ]
}

/// Check if any two actions share the same key binding.
pub fn find_conflicts(actions: &[InputAction]) -> Vec<(usize, usize)> {
    let mut conflicts = Vec::new();
    for i in 0..actions.len() {
        for j in (i + 1)..actions.len() {
            let a = effective_scancode(&actions[i]);
            let b = effective_scancode(&actions[j]);
            if a != SDL_SCANCODE_UNKNOWN && a == b {
                conflicts.push((i, j));
            }
        }
    }
    conflicts
}

pub(crate) fn effective_scancode(action: &InputAction) -> SDL_Scancode {
    match &action.mapping {
        Some(CapturedInput::Keyboard { scancode, .. }) => *scancode,
        None => action.default_scancode,
        _ => SDL_SCANCODE_UNKNOWN,
    }
}

/// Info about an opened joystick for direct polling.
struct OpenedJoystick {
    handle: *mut sdl3_sys::everything::SDL_Joystick,
    vpx_id: String,
    num_buttons: i32,
    num_axes: i32,
    prev_buttons: Vec<bool>,
    /// Pre-built button names to avoid format!() in the 100Hz polling loop
    button_names: Vec<String>,
    /// Pre-built axis names
    axis_names: Vec<String>,
}

/// Spawn the SDL3 joystick polling thread (keyboard is handled via egui).
/// Uses direct state polling (SDL_GetJoystickButton/Axis) instead of SDL_PollEvent
/// to avoid the SDL3 main-thread assertion on event pumping.
/// Returns a receiver for joystick events.
pub fn spawn_joystick_thread() -> crossbeam_channel::Receiver<JoystickEvent> {
    let (evt_tx, evt_rx) = crossbeam_channel::unbounded::<JoystickEvent>();

    thread::spawn(move || {
        unsafe {
            // Init joystick subsystem in this thread
            if !SDL_InitSubSystem(SDL_INIT_JOYSTICK) {
                log::error!(
                    "Joystick thread: SDL_InitSubSystem failed: {:?}",
                    CStr::from_ptr(SDL_GetError())
                );
                return;
            }

            // Open all connected joysticks
            let mut joy_count: i32 = 0;
            let joy_ids = SDL_GetJoysticks(&mut joy_count);
            let mut joysticks: Vec<OpenedJoystick> = Vec::with_capacity(joy_count as usize);
            if !joy_ids.is_null() {
                for i in 0..joy_count as usize {
                    let jid = *joy_ids.add(i);
                    let joy = SDL_OpenJoystick(jid);
                    if !joy.is_null() {
                        let name_ptr = SDL_GetJoystickName(joy);
                        let name = if !name_ptr.is_null() {
                            CStr::from_ptr(name_ptr).to_string_lossy().into_owned()
                        } else {
                            format!("Joystick {}", jid.0)
                        };
                        let dev_id = vpx_device_id(joy);
                        let num_buttons = SDL_GetNumJoystickButtons(joy);
                        let num_axes = SDL_GetNumJoystickAxes(joy);
                        log::info!(
                            "Opened joystick: {} (vpx_id={}, buttons={}, axes={})",
                            name,
                            dev_id,
                            num_buttons,
                            num_axes
                        );
                        // Detect Pinscape controller
                        if name.contains("Pinscape") || dev_id.contains("PSC") {
                            log::info!("Pinscape controller detected: {}", dev_id);
                            let _ = evt_tx.send(JoystickEvent::PinscapeDetected {
                                vpx_id: dev_id.clone(),
                            });
                        } else if SDL_IsGamepad(jid) {
                            // Generic gamepad (Xbox, PS, etc.)
                            log::info!("Gamepad detected: {} ({})", name, dev_id);
                            let _ = evt_tx.send(JoystickEvent::GamepadDetected {
                                vpx_id: dev_id.clone(),
                                name: name.clone(),
                            });
                        }
                        // Pre-build names to avoid format!() in the hot polling loop
                        let button_names: Vec<String> = (0..num_buttons)
                            .map(|b| format!("{} Button {}", dev_id, b))
                            .collect();
                        let axis_names: Vec<String> = (0..num_axes)
                            .map(|a| format!("{} Axis {}", dev_id, a))
                            .collect();
                        joysticks.push(OpenedJoystick {
                            handle: joy,
                            vpx_id: dev_id,
                            num_buttons,
                            num_axes,
                            prev_buttons: vec![false; num_buttons as usize],
                            button_names,
                            axis_names,
                        });
                    }
                }
                SDL_free(joy_ids as *mut _);
            }
            log::info!(
                "Joystick thread started, {} joystick(s) found",
                joysticks.len()
            );

            loop {
                // Update joystick state (required before reading)
                SDL_UpdateJoysticks();

                for js in &mut joysticks {
                    // Poll buttons — detect newly pressed (only allocate on actual press)
                    for b in 0..js.num_buttons {
                        let pressed = SDL_GetJoystickButton(js.handle, b);
                        let idx = b as usize;
                        let was_pressed = js.prev_buttons[idx];
                        if pressed && !was_pressed {
                            let _ = evt_tx.send(JoystickEvent::ButtonDown {
                                device_id: js.vpx_id.clone(),
                                button: b as u8,
                                name: js.button_names[idx].clone(),
                            });
                        }
                        js.prev_buttons[idx] = pressed;
                    }

                    // Poll axes — capture big movements for input binding
                    for a in 0..js.num_axes {
                        let value = SDL_GetJoystickAxis(js.handle, a);
                        if value.abs() > 16000 {
                            let _ = evt_tx.send(JoystickEvent::AxisMotion {
                                device_id: js.vpx_id.clone(),
                                axis: a as u8,
                                name: js.axis_names[a as usize].clone(),
                            });
                        }
                    }

                    // Send raw normalized accel data for tilt visualization (axes 0+1)
                    if js.num_axes >= 2 {
                        let ax = SDL_GetJoystickAxis(js.handle, 0) as f32 / 32767.0;
                        let ay = SDL_GetJoystickAxis(js.handle, 1) as f32 / 32767.0;
                        let _ = evt_tx.send(JoystickEvent::AccelUpdate { x: ax, y: ay });
                    }
                }

                std::thread::sleep(std::time::Duration::from_millis(10));
            }
        }
    });

    evt_rx
}

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

    // --- CapturedInput::to_mapping_string ---

    #[test]
    fn keyboard_mapping_string() {
        let input = CapturedInput::Keyboard {
            scancode: SDL_SCANCODE_LSHIFT,
            name: "Left Shift".to_string(),
        };
        assert_eq!(
            input.to_mapping_string(),
            format!("Key;{}", SDL_SCANCODE_LSHIFT.0)
        );
    }

    #[test]
    fn joystick_button_mapping_string() {
        let input = CapturedInput::JoystickButton {
            device_id: "SDLJoy_PSC004".to_string(),
            button: 7,
            name: "Button 7".to_string(),
        };
        assert_eq!(input.to_mapping_string(), "SDLJoy_PSC004;7");
    }

    #[test]
    fn joystick_axis_mapping_string() {
        let input = CapturedInput::JoystickAxis {
            device_id: "SDLJoy_ABC".to_string(),
            axis: 2,
            name: "Axis 2".to_string(),
        };
        assert_eq!(input.to_mapping_string(), "SDLJoy_ABC;2");
    }

    // --- CapturedInput::display_name ---

    #[test]
    fn display_name_keyboard() {
        let input = CapturedInput::Keyboard {
            scancode: SDL_SCANCODE_A,
            name: "A".to_string(),
        };
        assert_eq!(input.display_name(), "A");
    }

    #[test]
    fn display_name_joystick() {
        let input = CapturedInput::JoystickButton {
            device_id: "dev".to_string(),
            button: 0,
            name: "Start Button".to_string(),
        };
        assert_eq!(input.display_name(), "Start Button");
    }

    // --- default_actions ---

    #[test]
    fn default_actions_has_essential_and_advanced() {
        let actions = default_actions();
        assert!(!actions.is_empty());
        let essential_count = actions.iter().filter(|a| a.essential).count();
        let advanced_count = actions.iter().filter(|a| !a.essential).count();
        assert!(
            essential_count >= 10,
            "expected >=10 essential actions, got {essential_count}"
        );
        assert!(
            advanced_count >= 10,
            "expected >=10 advanced actions, got {advanced_count}"
        );
    }

    #[test]
    fn default_actions_all_have_setting_id() {
        for action in default_actions() {
            assert!(!action.setting_id.is_empty(), "action has empty setting_id");
        }
    }

    #[test]
    fn default_actions_none_have_mapping() {
        for action in default_actions() {
            assert!(
                action.mapping.is_none(),
                "{} should have no mapping by default",
                action.setting_id
            );
        }
    }

    // --- effective_scancode ---

    #[test]
    fn effective_scancode_default() {
        let action = InputAction {
            setting_id: "Test",
            label: "test",
            default_scancode: SDL_SCANCODE_A,
            essential: true,
            mapping: None,
        };
        assert!(effective_scancode(&action) == SDL_SCANCODE_A);
    }

    #[test]
    fn effective_scancode_with_keyboard_mapping() {
        let action = InputAction {
            setting_id: "Test",
            label: "test",
            default_scancode: SDL_SCANCODE_A,
            essential: true,
            mapping: Some(CapturedInput::Keyboard {
                scancode: SDL_SCANCODE_B,
                name: "B".to_string(),
            }),
        };
        assert!(effective_scancode(&action) == SDL_SCANCODE_B);
    }

    #[test]
    fn effective_scancode_with_joystick_is_unknown() {
        let action = InputAction {
            setting_id: "Test",
            label: "test",
            default_scancode: SDL_SCANCODE_A,
            essential: true,
            mapping: Some(CapturedInput::JoystickButton {
                device_id: "dev".to_string(),
                button: 0,
                name: "B0".to_string(),
            }),
        };
        assert!(effective_scancode(&action) == SDL_SCANCODE_UNKNOWN);
    }

    // --- find_conflicts ---

    #[test]
    fn find_conflicts_no_conflicts() {
        let actions = vec![
            InputAction {
                setting_id: "A",
                label: "a",
                default_scancode: SDL_SCANCODE_A,
                essential: true,
                mapping: None,
            },
            InputAction {
                setting_id: "B",
                label: "b",
                default_scancode: SDL_SCANCODE_B,
                essential: true,
                mapping: None,
            },
        ];
        assert!(find_conflicts(&actions).is_empty());
    }

    #[test]
    fn find_conflicts_detects_default_conflict() {
        let actions = vec![
            InputAction {
                setting_id: "A",
                label: "a",
                default_scancode: SDL_SCANCODE_LSHIFT,
                essential: true,
                mapping: None,
            },
            InputAction {
                setting_id: "B",
                label: "b",
                default_scancode: SDL_SCANCODE_LSHIFT,
                essential: true,
                mapping: None,
            },
        ];
        let conflicts = find_conflicts(&actions);
        assert_eq!(conflicts.len(), 1);
        assert_eq!(conflicts[0], (0, 1));
    }

    #[test]
    fn find_conflicts_unknown_scancode_not_conflicting() {
        let actions = vec![
            InputAction {
                setting_id: "A",
                label: "a",
                default_scancode: SDL_SCANCODE_UNKNOWN,
                essential: false,
                mapping: None,
            },
            InputAction {
                setting_id: "B",
                label: "b",
                default_scancode: SDL_SCANCODE_UNKNOWN,
                essential: false,
                mapping: None,
            },
        ];
        assert!(find_conflicts(&actions).is_empty());
    }

    #[test]
    fn find_conflicts_with_mapped_override() {
        let actions = vec![
            InputAction {
                setting_id: "A",
                label: "a",
                default_scancode: SDL_SCANCODE_A,
                essential: true,
                mapping: Some(CapturedInput::Keyboard {
                    scancode: SDL_SCANCODE_Z,
                    name: "Z".to_string(),
                }),
            },
            InputAction {
                setting_id: "B",
                label: "b",
                default_scancode: SDL_SCANCODE_Z,
                essential: true,
                mapping: None,
            },
        ];
        let conflicts = find_conflicts(&actions);
        assert_eq!(conflicts.len(), 1);
    }

    #[test]
    fn find_conflicts_joystick_mapping_no_conflict_with_keyboard() {
        let actions = vec![
            InputAction {
                setting_id: "A",
                label: "a",
                default_scancode: SDL_SCANCODE_A,
                essential: true,
                mapping: Some(CapturedInput::JoystickButton {
                    device_id: "dev".to_string(),
                    button: 0,
                    name: "B0".to_string(),
                }),
            },
            InputAction {
                setting_id: "B",
                label: "b",
                default_scancode: SDL_SCANCODE_A,
                essential: true,
                mapping: None,
            },
        ];
        // A uses joystick (effective = UNKNOWN), B uses keyboard A → no conflict
        assert!(find_conflicts(&actions).is_empty());
    }

    // --- egui_key_to_scancode ---

    #[test]
    fn egui_key_letters() {
        assert!(egui_key_to_scancode(egui::Key::A) == Some(SDL_SCANCODE_A));
        assert!(egui_key_to_scancode(egui::Key::Z) == Some(SDL_SCANCODE_Z));
    }

    #[test]
    fn egui_key_numbers() {
        assert!(egui_key_to_scancode(egui::Key::Num0) == Some(SDL_SCANCODE_0));
        assert!(egui_key_to_scancode(egui::Key::Num9) == Some(SDL_SCANCODE_9));
    }

    #[test]
    fn egui_key_special() {
        assert!(egui_key_to_scancode(egui::Key::Escape) == Some(SDL_SCANCODE_ESCAPE));
        assert!(egui_key_to_scancode(egui::Key::Enter) == Some(SDL_SCANCODE_RETURN));
        assert!(egui_key_to_scancode(egui::Key::Space) == Some(SDL_SCANCODE_SPACE));
    }

    #[test]
    fn egui_key_function_keys() {
        assert!(egui_key_to_scancode(egui::Key::F1) == Some(SDL_SCANCODE_F1));
        assert!(egui_key_to_scancode(egui::Key::F12) == Some(SDL_SCANCODE_F12));
    }

    #[test]
    fn egui_key_unmapped_returns_none() {
        assert!(egui_key_to_scancode(egui::Key::Insert).is_none());
    }

    // --- egui_modifiers_to_scancode ---

    #[test]
    fn modifiers_shift_only() {
        let m = egui::Modifiers {
            shift: true,
            ctrl: false,
            alt: false,
            ..Default::default()
        };
        assert!(egui_modifiers_to_scancode(&m) == Some(SDL_SCANCODE_LSHIFT));
    }

    #[test]
    fn modifiers_ctrl_only() {
        let m = egui::Modifiers {
            ctrl: true,
            shift: false,
            alt: false,
            ..Default::default()
        };
        assert!(egui_modifiers_to_scancode(&m) == Some(SDL_SCANCODE_LCTRL));
    }

    #[test]
    fn modifiers_alt_only() {
        let m = egui::Modifiers {
            alt: true,
            shift: false,
            ctrl: false,
            ..Default::default()
        };
        assert!(egui_modifiers_to_scancode(&m) == Some(SDL_SCANCODE_LALT));
    }

    #[test]
    fn modifiers_multiple_returns_none() {
        let m = egui::Modifiers {
            shift: true,
            ctrl: true,
            alt: false,
            ..Default::default()
        };
        assert!(egui_modifiers_to_scancode(&m).is_none());
    }

    #[test]
    fn modifiers_none_returns_none() {
        let m = egui::Modifiers::default();
        assert!(egui_modifiers_to_scancode(&m).is_none());
    }

    // --- Known VPX default key conflicts ---

    #[test]
    fn default_actions_known_conflicts() {
        // Per CLAUDE.md, LeftFlipper/LeftStagedFlipper share LSHIFT,
        // RightFlipper/RightStagedFlipper share RSHIFT,
        // VolumeDown/Service7 share MINUS, Credit4/Service5 share 6
        let actions = default_actions();
        let conflicts = find_conflicts(&actions);
        assert!(
            !conflicts.is_empty(),
            "expected known default conflicts (LSHIFT, RSHIFT, MINUS, 6)"
        );
        // Verify specific known conflicts exist
        let find_pair = |id_a: &str, id_b: &str| -> bool {
            conflicts.iter().any(|&(i, j)| {
                (actions[i].setting_id == id_a && actions[j].setting_id == id_b)
                    || (actions[i].setting_id == id_b && actions[j].setting_id == id_a)
            })
        };
        assert!(
            find_pair("LeftFlipper", "LeftStagedFlipper"),
            "LSHIFT conflict missing"
        );
        assert!(
            find_pair("RightFlipper", "RightStagedFlipper"),
            "RSHIFT conflict missing"
        );
        assert!(
            find_pair("VolumeDown", "Service7"),
            "MINUS conflict missing"
        );
        assert!(find_pair("Credit4", "Service5"), "6 key conflict missing");
    }
}