pinready 0.27.3

Cross-platform configurator and launcher supporting the adoption of Visual Pinball 10.8.1 — for testers and early adopters, not a replacement for a stable production setup
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
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
use eframe::egui;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};

use crate::audio::{self, AudioCommand, AudioConfig, Sound3DMode};
use crate::config::VpxConfig;
use crate::db::Database;
use crate::i18n::{self, LANGUAGE_OPTIONS};
use crate::inputs::{self, CapturedInput, InputAction, JoystickEvent, pinscape_button_defaults};
use crate::outputs_hid::DiscoveryState;
use crate::screens::{DisplayInfo, DisplayRole};
use crate::tilt::TiltConfig;
use crate::updater::{self, ReleaseInfo, UpdateProgress};
use rust_i18n::t;

/// Application mode
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AppMode {
    Wizard,
    Launcher,
}

/// Cross-session signal for `main.rs` to know what to do after the current
/// eframe session exits. Set by UI click handlers (Finish, Config, etc.) just
/// before they send `ViewportCommand::Close`; `main.rs` reads it after
/// `run_native` returns and relaunches a fresh eframe with the right
/// viewport for the new mode.
///
/// We use a static rather than carrying state through `App` because
/// `eframe::run_native` consumes the App and we want a minimal handshake
/// that survives the Drop.
static NEXT_ACTION: Mutex<Option<AppMode>> = Mutex::new(None);

/// Request a mode switch after the current eframe session closes. Call
/// this, then send `ViewportCommand::Close` to trigger the transition.
pub fn request_mode_switch(mode: AppMode) {
    *NEXT_ACTION.lock().unwrap() = Some(mode);
}

/// Set by the wizard's Finish: the launcher that opens next plays the
/// knocker once. The wizard window closes at once instead of staying up
/// until the sound ends (and a second click could restart it).
static KNOCKER_ON_START: AtomicBool = AtomicBool::new(false);

pub fn request_knocker_on_start() {
    KNOCKER_ON_START.store(true, Ordering::Relaxed);
}

/// Consume the pending mode switch request, if any. `main.rs` calls this
/// after each `run_native` returns; `Some(mode)` means relaunch in `mode`,
/// `None` means the user is quitting the app.
pub fn take_next_mode() -> Option<AppMode> {
    NEXT_ACTION.lock().unwrap().take()
}

/// VPX process status messages sent from the launch thread
enum VpxStatus {
    /// Loading progress message with optional percentage (0.0–1.0)
    Loading(String, Option<f32>),
    /// VPX has finished loading ("Startup done")
    Started,
    /// VPX exited normally
    ExitOk,
    /// VPX exited with error — contains captured stdout + stderr log
    ExitError(String),
    /// Failed to launch VPX
    LaunchError(String),
}

/// Bounds of the UI zoom the user can pick.
const MIN_ZOOM: f32 = 0.5;
const MAX_ZOOM: f32 = 4.0;

/// The zoom a mode opens with when the user never picked one: the wizard
/// at 2.4 (read standing beside a cabinet), the launcher at 1.2, both as
/// they look at a display scale of 1, so divided by the system's own scale.
fn default_zoom(mode: AppMode, native_pixels_per_point: f32) -> f32 {
    let base = match mode {
        AppMode::Wizard => 2.4,
        AppMode::Launcher => 1.2,
    };
    (base / native_pixels_per_point.max(1.0)).max(1.0)
}

/// The rotation the user picked with the `↻` button, as stored in the DB.
/// Kept as degrees so the value reads for itself in a sqlite dump.
fn rotation_to_db(rotation: egui_rotate::Rotation) -> &'static str {
    match rotation {
        egui_rotate::Rotation::None => "0",
        egui_rotate::Rotation::CW90 => "90",
        egui_rotate::Rotation::CW180 => "180",
        egui_rotate::Rotation::CW270 => "270",
    }
}

/// Inverse of [`rotation_to_db`]. `None` when nothing was ever stored, which
/// is what lets cabinet mode fall back to its own default.
pub(crate) fn rotation_from_db(value: &str) -> Option<egui_rotate::Rotation> {
    match value.trim() {
        "0" => Some(egui_rotate::Rotation::None),
        "90" => Some(egui_rotate::Rotation::CW90),
        "180" => Some(egui_rotate::Rotation::CW180),
        "270" => Some(egui_rotate::Rotation::CW270),
        _ => None,
    }
}

/// Viewport ID for the backglass window
const BG_VIEWPORT: &str = "backglass_viewport";
/// Viewport ID for the DMD cover window. The string stays
/// `playfield_viewport` — it is the viewport's identity, and renaming it
/// would orphan the window egui already tracks under that hash.
const DMD_VIEWPORT: &str = "playfield_viewport";
/// Viewport ID for the topper cover window
const TOPPER_VIEWPORT: &str = "topper_viewport";
/// VPX logo bytes (embedded at compile time)
const VPX_LOGO: &[u8] = include_bytes!("../../assets/vpinball_logo.png");

/// Third-party crates PinReady depends on directly (one entry per
/// [dependencies] line in Cargo.toml, no groupings, no sub-crates).
/// Rendered as bullet list in the About window; keep alphabetically
/// sorted (case-insensitive) so additions land in an obvious place at
/// review time.
const ABOUT_CRATE_THANKS: &[&str] = &[
    "anyhow",
    "base64",
    "crossbeam-channel",
    "directb2s",
    "dirs",
    "eframe",
    "egui",
    "egui-rotate",
    "egui_extras",
    "env_logger",
    "flate2",
    "hidapi",
    "image",
    "ini-preserve",
    "log",
    "noto-fonts-dl",
    "percent-encoding",
    "piaf",
    "regex",
    "rfd",
    "rusqlite",
    "rust-i18n",
    "sdl-keybridge",
    "sdl3-sys",
    "self-replace",
    "serde",
    "serde_json",
    "sha2",
    "symphonia",
    "tar",
    "time",
    "ureq",
    "vpin",
    "walkdir",
    "winapi",
    "zip",
];

/// VP-ecosystem contributors specifically thanked — kept in sync with
/// the wizard's last-page credits (`system_page.rs`). Alphabetical,
/// case-insensitive.
const ABOUT_PEOPLE_THANKS: &[&str] = &[
    "Caviar4456",
    "Francisdb",
    "Jsm174",
    "Major Frenchy",
    "Somatik",
    "Spielfool",
    "Superhac",
    "Toxie",
    "Vbousquet",
];

/// A completed background-extraction result: (scan generation, table
/// index, relative .vpx path used as DB key, encoded image bytes,
/// source mtime for cache invalidation). The generation is bumped at
/// every `scan_tables()` so receiver can drop stale messages from a
/// previous scan whose indices no longer match the current grid.
pub type BgExtraction = (u64, usize, String, Vec<u8>, i64);
// The `Vec<u8>` is the grid thumbnail (JPEG), not the full picture.

/// A completed VBS-patch classification+apply result: (rel_path,
/// embedded_sha256, sidecar_sha256, status, last_checked_mtime).
/// `status` is one of `vbs_patches::status::*`.
pub type VbsPatchRecord = (String, String, Option<String>, String, i64);

/// A discovered table
#[derive(Debug, Clone)]
pub struct TableEntry {
    pub path: std::path::PathBuf,
    pub name: String,
    /// Favourite flag, rating and play statistics (see `db::UserTable`).
    pub user: crate::db::UserTable,
    /// The VPS match is reliable enough to share with VPinPlay.
    pub vps_shareable: bool,
    /// `true` once the table has a backglass thumbnail (from the SQLite
    /// cache on scan, or just made by a worker); `false` while extraction
    /// is pending or when nothing could be found, in which case the grid
    /// renders a localized placeholder with instructions. The pictures
    /// themselves live in `bg_cache` (see `bgcache.rs`).
    pub has_bg: bool,
    /// `true` when the live VPSDB `Game.updated_at` has moved past the
    /// value we stored at link time → a fresher version of this table
    /// (or its metadata/media) is published in the catalog. Surfaced in
    /// the launcher as a "↑" badge + a header counter.
    pub update_available: bool,
    /// VPS-assigned game ID stored in `vps_link.vps_id`. Used by the
    /// outdated-badge click-handler to deep-link into the catalog page
    /// at `virtualpinballspreadsheet.github.io/games?game=<vps_id>`.
    pub vps_id: Option<String>,
}

/// Wizard pages
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WizardPage {
    Screens,
    Rendering,
    ThreeD,
    Inputs,
    Outputs,
    Tilt,
    Audio,
    TablesDir,
    System,
}

impl WizardPage {
    fn title(&self) -> String {
        match self {
            Self::Screens => t!("page_screens"),
            Self::Rendering => t!("page_rendering"),
            Self::ThreeD => t!("page_3d"),
            Self::Inputs => t!("page_inputs"),
            Self::Outputs => t!("page_outputs"),
            Self::Tilt => t!("page_tilt"),
            Self::Audio => t!("page_audio"),
            Self::TablesDir => t!("page_tables"),
            Self::System => t!("page_system"),
        }
        .to_string()
    }

    fn index(&self) -> usize {
        match self {
            Self::Screens => 0,
            Self::Rendering => 1,
            Self::ThreeD => 2,
            Self::Inputs => 3,
            Self::Outputs => 4,
            Self::Tilt => 5,
            Self::Audio => 6,
            Self::TablesDir => 7,
            Self::System => 8,
        }
    }

    fn from_index(i: usize) -> Option<Self> {
        match i {
            0 => Some(Self::Screens),
            1 => Some(Self::Rendering),
            2 => Some(Self::ThreeD),
            3 => Some(Self::Inputs),
            4 => Some(Self::Outputs),
            5 => Some(Self::Tilt),
            6 => Some(Self::Audio),
            7 => Some(Self::TablesDir),
            8 => Some(Self::System),
            _ => None,
        }
    }

    fn count() -> usize {
        9
    }
}

/// How the Visual Pinball executable is provided
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VpxInstallMode {
    /// Download from GitHub fork release
    Auto,
    /// User provides the path manually
    Manual,
}

/// Kind of input an auto-map pass listens for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AutoMapDevice {
    Keyboard,
    Joystick,
}

/// State for input capture
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CaptureState {
    Idle,
    /// Waiting for input for action at this index
    Capturing(usize),
}

/// What the cursor diagnostics compare between lines: capture, dormancy,
/// focus, and the position rounded to a 10-point cell.
type CursorDiagState = (bool, bool, bool, Option<(i32, i32)>);

pub struct App {
    mode: AppMode,
    page: WizardPage,
    config: VpxConfig,
    db: Database,

    // Visual Pinball executable path and install directory
    vpx_exe_path: String,
    vpx_install_dir: String,

    // Page 1 — Screens
    displays: Vec<DisplayInfo>,
    screen_count: usize,
    view_mode: i32, // 0=Desktop, 1=Cabinet, 2=FSS
    disable_touch: bool,
    external_dmd: bool, // ZeDMD, PinDMD, etc. — DMD handled by external device, not a screen

    // Cabinet physical dimensions (cm) for Window projection mode
    screen_inclination: f32, // Playfield screen angle, 0 = horizontal
    lockbar_width: f32,      // Lockbar width in cm
    lockbar_height: f32,     // Lockbar height from ground in cm
    player_x: f32,           // Player X offset from center in cm
    player_y: f32,           // Player Y distance from lockbar in cm (negative = behind)
    player_z: f32,           // Player Z height (eyes) from playfield in cm
    player_height: f32,      // Player total height in cm (used to compute Z)

    // Page 2 — Rendering
    aa_factor: f32,            // Supersampling 0.5–2.0 (default 1.0)
    msaa: i32,                 // 0=Off, 1=4x, 2=6x, 3=8x
    fxaa: i32,                 // 0=Off, 1–7 various modes
    sharpen: i32,              // 0=Off, 1=CAS, 2=Bilateral CAS
    pf_reflection: i32,        // 0–5 reflection quality
    max_tex_dim: i32,          // 512–16384
    sync_mode: i32,            // 0=No sync, 1=VSync, 2=Adaptive, 3=Frame Pacing (VPX default)
    max_framerate: f32,        // -1=display ("Max" in the UI), 0=unlimited, else value
    compress_textures: bool,   // Player/CompressTextures (VPX default on)
    effects: effects::Effects, // Visual effects: AO, bloom, motion blur, reflections...
    threed: threed::ThreeD,    // 3D page: VR and stereoscopic rendering (both off by default)
    show_fps: bool,            // Player/ShowFPS: FPS overlay in game (recommended on)
    ball_antistretch: bool,    // Player/BallAntiStretch: keep the ball round (recommended on)

    // Live accelerometer data from joystick thread
    accel_x: f32,
    accel_y: f32,
    // Where the sensor hit its own ceiling recently, for the tilt page.
    clip_marks: Vec<crate::app::tilt_page::ClipMark>,

    // Page 3 — Inputs
    actions: Vec<InputAction>,
    capture_state: CaptureState,
    #[allow(dead_code)]
    // kept for backwards compat with persisted DB; UI dropped in favour of the unified inputs list
    show_advanced_inputs: bool,
    /// Auto-map mode: when true, the inputs page advances to the next
    /// unmapped action automatically after each successful capture (or
    /// Escape, which leaves that action's binding unchanged). Stops
    /// when reaching the end of the list or when the user clicks Cancel.
    auto_map_active: bool,
    /// Which kind of input the running auto-map pass listens for: a key
    /// pass never touches the joystick column and vice versa, so a pass
    /// on the joystick keeps Escape on its quit action.
    auto_map_device: AutoMapDevice,
    joystick_rx: Option<crossbeam_channel::Receiver<JoystickEvent>>,
    /// Set to false to ask the joystick thread to drain + exit. The
    /// thread joins quickly (≤ 10 ms — its sleep granularity), closes
    /// every `SDL_OpenJoystick` handle, and `SDL_QuitSubSystem(JOYSTICK)`
    /// before returning.
    joystick_running: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
    /// JoinHandle for the joystick thread — kept so `launch_table` can
    /// `.join()` after flipping `joystick_running` to false, ensuring
    /// SDL3 joystick state is fully released before VPX is spawned.
    joystick_thread: Option<std::thread::JoinHandle<()>>,
    pinscape_id: Option<String>, // VPX device ID if pinball controller detected
    pinscape_profile: usize,     // 0 = KL25Z, 1 = Pico, 2 = DudesCab
    gamepad_id: Option<String>,  // VPX device ID if generic gamepad detected
    use_gamepad: bool,           // User toggle: use gamepad axes for flippers/nudge/plunger

    // Page 4 — Outputs (discovery tool)
    pub(super) output_discovery: DiscoveryState,

    // Page 3 — Tilt
    tilt: TiltConfig,

    // Page 4 — Audio
    audio: AudioConfig,
    audio_cmd_tx: Option<crossbeam_channel::Sender<AudioCommand>>,
    /// JoinHandle for the audio thread — same shutdown discipline as
    /// the joystick thread: drop the sender to signal shutdown, then
    /// `.join()` before launching VPX so the SDL3 audio device is
    /// fully released.
    audio_thread: Option<std::thread::JoinHandle<()>>,

    // Launcher preview audio. When `selected_table` changes we debounce
    // ~700ms before firing PreviewStart so quick scrolling doesn't spam
    // the audio thread. `preview_last_idx` is the table whose audio is
    // currently playing or queued; `preview_due_at` is the deadline for
    // the next PreviewStart.
    preview_last_idx: Option<usize>,
    preview_due_at: Option<std::time::Instant>,
    preview_playing: bool,

    // Page 5 — Tables dir
    tables_dir: String,

    // Launcher
    tables: Vec<TableEntry>,
    table_filter: String,
    table_filter_lower: String, // cached lowercase version of table_filter
    selected_table: usize,
    /// How the launcher orders the tables (persisted in the config).
    sort_mode: launcher::SortMode,
    /// VPinPlay: settings, community ratings by VPS id, background results.
    vpinplay: crate::vpinplay::Settings,
    community: std::collections::HashMap<String, crate::vpinplay::CommunityRating>,
    vpinplay_rx: Option<crossbeam_channel::Receiver<crate::vpinplay::Event>>,
    vpinplay_status: String,
    /// The running Visual Pinball session: start time and table path
    /// relative to the tables directory, to add its length to the stats.
    vpx_session: Option<(std::time::Instant, String)>,
    scroll_to_selected: bool, // set by joystick navigation to trigger scroll
    last_scroll_target: Option<f32>, // last forced vertical scroll offset — skip reset when the target hasn't moved
    launcher_cols: usize,            // number of columns in the grid (computed in render)
    // Backglass pictures: thumbnails for every table in the GPU, the page
    // on screen full size in the GPU, its neighbours in RAM.
    bg_cache: bgcache::BgCache,
    // User theme preference, cycled from the topbar/wizard toggle. Purely
    // in-memory (starts at System every launch) — no persistence yet.
    theme_pref: egui::ThemePreference,
    /// The UI zoom last stored for this mode; `None` until the first frame
    /// knows the screen's DPI scale (see `sync_zoom`).
    zoom_saved: Option<f32>,
    // About window visibility, driven by the ℹ toolbar icon.
    about_open: bool,
    // Two-step VPX launch state on Wayland: `Some((path, requested_at))`
    // when the user has clicked a table and PinReady sent
    // `ViewportCommand::RequestActivationToken` to the compositor but is
    // still waiting for the reply. The launcher polls this every frame
    // in `App::ui`: on `Frame::take_activation_token` (or after a
    // 500 ms deadline) it drains the pending state and spawns VPX with
    // the token in `XDG_ACTIVATION_TOKEN` — the sealed serial is what
    // makes mutter/kwin actually grant focus to the freshly-created
    // window.
    pending_vpx_launch: Option<(std::path::PathBuf, std::time::Instant)>,
    /// `begin_table_launch` wants a token asked for on the next frame.
    activation_token_wanted: bool,
    // Viewport rotation for the root window. CW90 in cabinet mode, None
    // otherwise. Shadow copy of the value passed to the `RotationPlugin`
    // registered on the egui Context — kept here purely so layout code can
    // branch on rotation without going through the plugin every frame.
    rotation: egui_rotate::Rotation,
    // Kiosk mode: lock the cursor inside the PF window and center it on the grid.
    // Window placement itself is handled at creation via ViewportBuilder::with_monitor.
    // The software-cursor lock/scale themselves live on the plugin — accessed via
    // `App::with_software_cursor`.
    kiosk_cursor: bool, // signals that the plugin was built with a locked SoftwareCursor
    kiosk_cursor_warped: bool, // one-shot: warp cursor after window settles
    // Last virtual cursor position seen — used to restore the cursor where
    // it was after a spurious PointerGone (Mutter Wayland drops the
    // pointer-constraints lock during focus thrashing with secondary
    // viewports), so the user doesn't perceive it as a teleport-to-centre.
    kiosk_last_virtual_pos: Option<egui::Pos2>,
    // Cursor diagnostics (PINREADY_CURSOR_DIAG): last logged state and when,
    // so the log carries transitions instead of one line per frame.
    kiosk_diag_state: Option<CursorDiagState>,
    kiosk_diag_at: Option<std::time::Instant>,
    // Focus-reclaim attempts for the kiosk playfield, throttled and capped:
    // a compositor that refuses three times will refuse the thirtieth too.
    kiosk_focus_tries: u32,
    kiosk_focus_at: Option<std::time::Instant>,
    /// The reset button is armed by a first click and fires on a second:
    /// it throws away every answer given so far.
    reset_armed: bool,
    /// Largest |accel| seen on the tilt page, so the user can size the
    /// accelerometer range against what their cabinet actually produces.
    nudge_peak: f32,
    /// VPX's tilt plumb, simulated here so the page can be shaken rather
    /// than guessed at: the tilt is a pendulum's angle over time, not a
    /// threshold on acceleration.
    plumb: crate::plumb::Plumb,
    /// VPX's nudge chain ahead of the plumb: peak detection or direct
    /// coupling depending on the sensor type, then the cabinet's own springy
    /// response. Feeding the plumb raw acceleration instead would show a
    /// physics nobody plays.
    nudge_sim: crate::nudge_sim::NudgeSim,
    plumb_last_step: Option<std::time::Instant>,
    /// Latches a tilt for a moment so a 1 ms crossing is still readable.
    plumb_tilt_until: Option<std::time::Instant>,
    /// Coarse state of the nudge, for the banner: 0 inside the deadzone,
    /// 1 nudging, 2 tilted. It only ever falls back after a second, so a
    /// glance catches what a shake did rather than what it is doing now.
    nudge_state: u8,
    nudge_state_since: Option<std::time::Instant>,
    /// Where the tilt dial draws its rings, and the key that says whether it
    /// still matches the settings. Placing them runs the cabinet physics a few
    /// dozen times, so it happens when a slider moves, not every frame.
    tilt_rings: crate::tilt::TiltRings,
    tilt_rings_key: u64,
    /// What the Pinscape board says about itself — its accelerometer range
    /// and orientation, whether a plunger exists. Read over HID at startup,
    /// `None` while pending or when no board answers.
    pinscape_cfg: Option<crate::pinscape_config::PinscapeConfig>,
    pinscape_cfg_rx:
        Option<crossbeam_channel::Receiver<Option<crate::pinscape_config::PinscapeConfig>>>,
    // Launcher joystick nav auto-repeat: track which nav button is held
    nav_held: Option<(
        u8,
        launcher_input::LauncherAction,
        std::time::Instant,
        std::time::Instant,
    )>,
    // Background backglass extraction results. Sent by the thread spawned
    // in `scan_tables`: (table index, .vpx path relative to tables_dir,
    // JPEG bytes). The UI thread pulls these in `process_bg_extraction`,
    // stores the bytes in the SQLite cache, and updates the TableEntry +
    // egui image cache.
    bg_rx: Option<crossbeam_channel::Receiver<BgExtraction>>,
    /// Result of the index thread started by `scan_tables`.
    index_rx: Option<crossbeam_channel::Receiver<launcher::IndexResult>>,

    // Scan generation counter. Bumped at every `scan_tables()`; carried
    // verbatim by every BgExtraction message so the UI can drop stale
    // results from a prior scan whose indices no longer line up with the
    // current `tables` Vec. Without this guard, dropping a new .vpx into
    // tables_dir + clicking Rescan while the previous scan's bg thread
    // was still running would shuffle thumbnails onto the wrong rows.
    scan_generation: u64,

    // VBS patch classification results — (rel_path, embedded_sha,
    // sidecar_sha, status, last_checked_mtime). Drained into
    // `vbs_patches` table. Silent on the UI side — we don't show per-
    // table badges; the log is the source of truth for what happened.
    vbs_rx: Option<crossbeam_channel::Receiver<VbsPatchRecord>>,
    // DMD area check of the .directb2s files — (rel_path, status, mtime)
    b2s_dmd_rx: Option<crossbeam_channel::Receiver<(String, String, i64)>>,

    // VPX process running — disables launcher while true
    vpx_running: Arc<AtomicBool>,
    // VPX launch status received from the VPX process thread
    vpx_status_rx: Option<crossbeam_channel::Receiver<VpxStatus>>,
    vpx_loading_msg: String,
    vpx_loading_pct: Option<f32>, // loading progress 0.0–1.0, if parseable
    vpx_hide_covers: bool,        // VPX windows are up, hide covers
    vpx_error_log: Option<String>, // set on unexpected exit, shown as popup
    /// When the crash report was last copied. Drives a short confirmation
    /// flash on the button: a clipboard write leaves no trace on screen, so
    /// without it there is no way to tell a successful copy from a dead
    /// button — which is exactly the doubt a field report just described.
    vpx_error_copied_at: Option<std::time::Instant>,
    /// Result of the last "Save" from the error popup: the path written, or
    /// the failure. Shown under the buttons so saving is not a silent act.
    vpx_error_saved: Option<Result<String, String>>,

    // Autostart on boot
    autostart: bool,
    /// A launcher on the desktop, and the app pinned to the dock. Read once
    /// at startup: both are filesystem/GSettings state, not ours to own. The
    /// checkboxes only record the choice; Finish applies it (`system_apply`).
    desktop_shortcut: bool,
    dock_pinned: bool,
    dock_pinning_available: bool,

    // Desktop integration: app-menu shortcuts (PinReady + VPinballX) and
    // .vpx file association. Mirrors `autostart` — flipped from the wizard's
    // tables_dir page, applied in finalize_wizard.
    desktop_integration: bool,

    // Self-hosted mirror for the VBS catalog and VPin media DB. Empty
    // string = direct GitHub fetch (default). Edited from the System
    // wizard page; persisted to `Database::set_mirror_base_url` on
    // every change so subsequent runs pick it up immediately without
    // waiting for finalize_wizard.
    mirror_base_url: String,

    // Asset bundling ("merge") — optional import step that lives on the
    // Tables wizard page. The three source paths point at legacy
    // VPINMAME/PUPVIDEOS/Music dirs; the merge engine in `crate::merge`
    // walks each .vpx in tables_dir and places companion files into the
    // 10.8.1 folder-per-table layout.
    ht_install_rx: Option<crossbeam_channel::Receiver<crate::headtracking_install::HtEvent>>,
    ht_status_key: Option<&'static str>,
    ht_error: Option<String>,
    ht_done_tag: Option<String>,
    ht_installed_version: Option<Option<String>>,
    /// Whether the head tracking plugin should be enabled in VPX. `None`
    /// until first read from the ini: installing the plugin without turning
    /// it on leaves a cabinet with a camera and nothing happening, which is
    /// exactly what the ini shipped with (`Enable = ` empty).
    ht_enabled: Option<bool>,
    /// Version offered by the release channel: `None` = not asked yet,
    /// `Some(None)` = asked and unreachable.
    ht_latest_version: Option<Option<String>>,
    ht_latest_rx: Option<crossbeam_channel::Receiver<Option<String>>>,
    /// The single directory the import indexes. Empty until the user
    /// picks one (legacy layout only — a modern collection indexes the
    /// tables dir itself).
    merge_src_root: String,
    /// User's answer to "is your collection already folder-per-table?".
    merge_layout_modern: bool,
    /// Live progress of the two steps: index, then bundle.
    merge_scan_files: usize,
    merge_scan_dirs: usize,
    merge_scan_finished: bool,
    merge_table_index: usize,
    merge_table_total: usize,
    /// What the worker is busy with right now — the folder being walked,
    /// then the table being bundled. A bar that only counts looks frozen
    /// on a spinning disk.
    merge_busy_with: String,
    merge_strategy: crate::merge::MergeStrategy,
    merge_progress_rx: Option<crossbeam_channel::Receiver<crate::merge::MergeEvent>>,
    merge_cancel: Option<Arc<AtomicBool>>,
    merge_log: Vec<crate::merge::MergeEvent>,
    merge_dry_run_report: Option<crate::merge::MergeReport>,
    merge_running: bool,

    // Opt-in: auto-patch VBS scripts at scan from
    // jsm174/vpx-standalone-scripts. Off by default — the catalog
    // sometimes introduces regressions on specific tables, so users
    // enable this deliberately from the Tables wizard page.
    jsm174_patching: bool,

    // Add the DMD area to the .directb2s files that lack it, so the DMD
    // shows in the backglass frame. On by default; the original is kept.
    // Persisted in `config.b2s_dmd_enabled`.
    b2s_dmd: bool,

    // Opt-in: VPSDB + VPinMediaDB enrichment at scan. Off by default
    // because the first sync downloads ~7 MB of JSON + per-table
    // media. Persisted in `config.catalog_enrichment_enabled`. Same
    // wizard page as the VBS patcher toggle.
    catalog_enrichment: bool,

    // Cancellation token for the catalog enrichment worker. Each
    // scan_tables() flips the previous token to `true` (signalling
    // the in-flight worker to bail out gracefully at its next
    // table-loop iteration) and replaces it with a fresh token for
    // the new worker. This keeps "click Rebuild 4× in a row" from
    // launching 4 concurrent workers that re-DL the same files
    // (which produced 4× duplicate "MediaDb installed" log lines on
    // initial sync). The newest scan always wins; older runs exit
    // cleanly without finishing their queue.
    catalog_cancel_token: Option<Arc<AtomicBool>>,

    // Deadline for sending `ViewportCommand::Close` after finalize_wizard.
    // Set by Finish: the wizard window closes on the next frame.
    close_at: Option<std::time::Instant>,
    /// The wizard's one-shot check that its window fits the monitor it
    /// opened on (see `fit_wizard_window`).
    wizard_size_checked: bool,

    // Grace deadline after VPX exits, before the launcher accepts input
    // again. The exit button (ExitGame / Escape) that closed VPX is often
    // still down/queued when PinReady reclaims control; without this window
    // the launcher reads it as `Cancel` and quits itself. Set in
    // `process_vpx_status` on any VPX-exit branch; input paths drain and
    // ignore events until it elapses.
    input_resume_at: Option<std::time::Instant>,

    // Deadline for resetting window level back to Normal after a focus-
    // raise from a second launch. `AlwaysOnTop` forces the compositor to
    // re-stack us on top (plain `Focus` is often refused by focus-stealing
    // prevention); we drop it a few frames later to avoid pinning.
    focus_reset_at: Option<std::time::Instant>,

    // Language
    selected_language: usize,

    // VPX updater
    vpx_install_mode: VpxInstallMode,
    vpx_fork_repo: String,
    vpx_installed_tag: String,
    vpx_latest_release: Option<ReleaseInfo>,
    update_check_rx: Option<crossbeam_channel::Receiver<anyhow::Result<ReleaseInfo>>>,
    update_progress_rx: Option<crossbeam_channel::Receiver<UpdateProgress>>,
    update_downloading: bool,
    update_progress: (u64, u64), // (current, total)
    update_error: Option<String>,

    // PinReady self-update (separate from VPX update)
    pinready_latest_release: Option<ReleaseInfo>,
    pinready_update_check_rx: Option<crossbeam_channel::Receiver<anyhow::Result<ReleaseInfo>>>,
    pinready_update_progress_rx: Option<crossbeam_channel::Receiver<UpdateProgress>>,
    pinready_updating: bool,
    pinready_update_progress: (u64, u64),
    pinready_update_error: Option<String>,

    /// `Some` while `VPX -h` runs in the background to (re)write the ini —
    /// see `maybe_normalize_ini`. `ini_normalized` makes it a once-per-session
    /// operation.
    ini_norm_rx: Option<crossbeam_channel::Receiver<bool>>,
    ini_normalized: bool,

    /// SDL video driver VPX is launched under, decided once at launcher
    /// startup ([`crate::display_reconcile::choose_driver_and_reconcile`]).
    /// `None` in wizard mode or on non-Linux.
    vpx_driver: Option<String>,
}

impl App {
    pub fn new(
        mut config: VpxConfig,
        db: Database,
        start_in_wizard: bool,
        displays: Vec<DisplayInfo>,
    ) -> Self {
        // Launcher startup: pick VPX's SDL driver (native Wayland when the
        // compositor has wp_fifo_v1, else XWayland for the framerate escape
        // hatch) and reconcile the `*Display=` names to it — only the screen
        // IDs change, resolution/refresh/dimensions are left as-is. Done once
        // per PinReady launch; table launches reuse the result.
        let vpx_driver = if start_in_wizard {
            None
        } else {
            let d = crate::display_reconcile::choose_driver_and_reconcile(&mut config, &db);
            if let Err(e) = config.save() {
                log::warn!("could not flush reconciled display config: {e}");
            }
            d.map(str::to_string)
        };

        let screen_count = displays.len().min(4);
        let view_mode = if screen_count >= 2 { 1 } else { 0 };
        let disable_touch = config
            .get_i32("Player", "NumberOfTimesToShowTouchMessage")
            .unwrap_or(10)
            == 0;

        let (
            screen_inclination,
            lockbar_width,
            lockbar_height,
            player_x,
            player_y,
            player_z,
            player_height,
        ) = Self::load_cabinet_dimensions(&config);
        let (
            aa_factor,
            msaa,
            fxaa,
            sharpen,
            pf_reflection,
            max_tex_dim,
            sync_mode,
            max_framerate,
            show_fps,
            ball_antistretch,
            compress_textures,
        ) = Self::load_rendering_config(&config);
        let effects = effects::Effects::load(&config);
        let threed = threed::ThreeD::load(&config);

        // Detect + install the user's language BEFORE anything that
        // calls `t!()` or `scancode_name()`, so localised labels (key
        // names, action names) end up in the right language from the
        // first render rather than staying frozen in English.
        let selected_language = Self::detect_language(&db);

        let actions = Self::load_input_mappings(&config);

        let mut tilt = TiltConfig::default();
        tilt.load_from_config(&config);

        let mut audio = AudioConfig::default();
        audio.load_from_config(&config);
        audio.available_devices = AudioConfig::enumerate_devices();

        let (vpx_exe_path, vpx_install_dir, vpx_fork_repo, vpx_installed_tag, vpx_install_mode) =
            Self::load_updater_config(&db);
        let tables_dir = db.get_tables_dir().unwrap_or_default();
        let external_dmd = db.get_config("external_dmd").as_deref() == Some("true");
        let pinscape_profile = db
            .get_config("pinscape_profile")
            .and_then(|s| s.parse().ok())
            .unwrap_or(0);
        let (joystick_rx, joystick_running, joystick_thread) = inputs::spawn_joystick_thread();
        let (audio_cmd_tx, audio_thread) = audio::spawn_audio_thread();
        if !start_in_wizard && KNOCKER_ON_START.swap(false, Ordering::Relaxed) {
            let _ = audio_cmd_tx.send(AudioCommand::PlayOnSpeaker {
                path: "knocker.ogg".to_string(),
                target: audio::SpeakerTarget::FrontBoth,
            });
        }
        let update_check_rx = if vpx_install_mode == VpxInstallMode::Manual {
            None
        } else {
            Self::spawn_update_check(&vpx_fork_repo)
        };
        let jsm174_patching = db.jsm174_patching_enabled();
        let b2s_dmd = db.b2s_dmd_enabled();
        let catalog_enrichment = db.catalog_enrichment_enabled();
        let merge_src_root = db.get_merge_source("root");
        let merge_layout_modern = db
            .get_config("merge_layout_modern")
            .is_none_or(|v| v != "0");
        let merge_strategy = crate::merge::MergeStrategy::from_db_str(&db.get_merge_strategy());
        let mirror_base_url = db.mirror_base_url().unwrap_or_default();

        let (tilt_rings, tilt_rings_key) = (tilt.rings(), tilt.rings_key());
        let db_sort_key = db.get_config("launcher_sort");
        let vpinplay_settings = crate::vpinplay::Settings::load(&db);
        let vpinplay_community = db.get_community_ratings();
        let mut s = Self {
            mode: if start_in_wizard {
                AppMode::Wizard
            } else {
                AppMode::Launcher
            },
            page: WizardPage::Screens,
            config,
            db,
            vpx_exe_path,
            vpx_install_dir,
            displays,
            screen_count,
            view_mode,
            disable_touch,
            external_dmd,
            screen_inclination,
            lockbar_width,
            lockbar_height,
            player_x,
            player_y,
            player_z,
            player_height,
            actions,
            accel_x: 0.0,
            clip_marks: Vec::new(),
            accel_y: 0.0,
            aa_factor,
            msaa,
            fxaa,
            sharpen,
            pf_reflection,
            max_tex_dim,
            sync_mode,
            max_framerate,
            show_fps,
            ball_antistretch,
            compress_textures,
            effects,
            threed,
            capture_state: CaptureState::Idle,
            show_advanced_inputs: false,
            auto_map_active: false,
            auto_map_device: AutoMapDevice::Keyboard,
            joystick_rx: Some(joystick_rx),
            joystick_running: Some(joystick_running),
            joystick_thread: Some(joystick_thread),
            pinscape_id: None,
            pinscape_profile,
            gamepad_id: None,
            use_gamepad: false,
            output_discovery: DiscoveryState::default(),
            tilt,
            audio,
            audio_cmd_tx: Some(audio_cmd_tx),
            audio_thread: Some(audio_thread),
            preview_last_idx: None,
            preview_due_at: None,
            preview_playing: false,
            tables_dir,
            tables: Vec::new(),
            table_filter: String::new(),
            table_filter_lower: String::new(),
            selected_table: 0,
            sort_mode: launcher::SortMode::from_key(db_sort_key.as_deref().unwrap_or_default()),
            vpx_session: None,
            vpinplay: vpinplay_settings,
            community: vpinplay_community,
            vpinplay_rx: None,
            vpinplay_status: String::new(),
            scroll_to_selected: false,
            last_scroll_target: None,
            launcher_cols: 1,
            bg_cache: bgcache::BgCache::new(),
            theme_pref: egui::ThemePreference::System, // from the DB in `theme_pref`
            zoom_saved: None,
            about_open: false,
            pending_vpx_launch: None,
            activation_token_wanted: false,
            rotation: egui_rotate::Rotation::None,
            kiosk_cursor: false,
            kiosk_cursor_warped: false,
            kiosk_last_virtual_pos: None,
            kiosk_diag_state: None,
            kiosk_diag_at: None,
            kiosk_focus_tries: 0,
            kiosk_focus_at: None,
            reset_armed: false,
            nudge_peak: 0.0,
            plumb: crate::plumb::Plumb::default(),
            nudge_sim: crate::nudge_sim::NudgeSim::default(),
            plumb_last_step: None,
            plumb_tilt_until: None,
            nudge_state: 0,
            nudge_state_since: None,
            tilt_rings,
            tilt_rings_key,
            pinscape_cfg: None,
            pinscape_cfg_rx: Some(crate::pinscape_config::spawn_read()),
            nav_held: None,
            bg_rx: None,
            index_rx: None,
            scan_generation: 0,
            vbs_rx: None,
            b2s_dmd_rx: None,
            vpx_running: Arc::new(AtomicBool::new(false)),
            vpx_status_rx: None,
            vpx_loading_msg: String::new(),
            vpx_loading_pct: None,
            vpx_hide_covers: false,
            vpx_error_log: None,
            vpx_error_copied_at: None,
            vpx_error_saved: None,
            autostart: is_autostart_enabled(),
            desktop_shortcut: desktop_integration::is_desktop_shortcut_installed(),
            dock_pinned: desktop_integration::is_pinned_to_dock(),
            dock_pinning_available: desktop_integration::dock_pinning_available(),
            desktop_integration: is_desktop_integration_installed(),
            mirror_base_url,
            ht_install_rx: None,
            ht_status_key: None,
            ht_error: None,
            ht_done_tag: None,
            ht_installed_version: None,
            ht_enabled: None,
            ht_latest_version: None,
            ht_latest_rx: None,
            merge_src_root,
            merge_layout_modern,
            merge_scan_files: 0,
            merge_scan_dirs: 0,
            merge_scan_finished: false,
            merge_table_index: 0,
            merge_table_total: 0,
            merge_busy_with: String::new(),
            merge_strategy,
            merge_progress_rx: None,
            merge_cancel: None,
            merge_log: Vec::new(),
            merge_dry_run_report: None,
            merge_running: false,
            jsm174_patching,
            b2s_dmd,
            catalog_enrichment,
            catalog_cancel_token: None,
            close_at: None,
            wizard_size_checked: false,
            input_resume_at: None,
            focus_reset_at: None,
            selected_language,
            vpx_install_mode,
            vpx_fork_repo,
            vpx_installed_tag,
            vpx_latest_release: None,
            update_check_rx,
            update_progress_rx: None,
            update_downloading: false,
            update_progress: (0, 0),
            update_error: None,
            pinready_latest_release: None,
            pinready_update_check_rx: Self::spawn_pinready_update_check(),
            pinready_update_progress_rx: None,
            pinready_updating: false,
            pinready_update_progress: (0, 0),
            pinready_update_error: None,
            ini_norm_rx: None,
            ini_normalized: false,
            vpx_driver,
        };
        s.normalize_max_framerate();
        if !start_in_wizard {
            s.scan_tables();
        }
        s
    }

    /// PinReady used to write the playfield's refresh rate into `MaxFramerate`,
    /// so a stored number that equals it is that old automatic value, not a
    /// choice. It would also pin the limit at 60 after a move to a 120 Hz mode
    /// in the OS. Read it as "Max" (-1), which follows the screen.
    fn normalize_max_framerate(&mut self) {
        let refresh = self
            .displays
            .iter()
            .find(|d| d.role == DisplayRole::Playfield)
            .map(|d| d.refresh_rate);
        if self.max_framerate > 0.0
            && refresh.is_some_and(|hz| (hz - self.max_framerate).abs() < 1.0)
        {
            self.max_framerate = -1.0;
        }
    }

    fn load_cabinet_dimensions(config: &VpxConfig) -> (f32, f32, f32, f32, f32, f32, f32) {
        let screen_inclination = config.get_f32("Player", "ScreenInclination").unwrap_or(0.0);
        let lockbar_width = config.get_f32("Player", "LockbarWidth").unwrap_or(70.0);
        let lockbar_height = config.get_f32("Player", "LockbarHeight").unwrap_or(85.0);
        let player_x = config.get_f32("Player", "ScreenPlayerX").unwrap_or(0.0);
        let player_y = config.get_f32("Player", "ScreenPlayerY").unwrap_or(-10.0);
        let player_z = config.get_f32("Player", "ScreenPlayerZ").unwrap_or(70.0);
        let player_height = player_z + lockbar_height + 12.0;
        (
            screen_inclination,
            lockbar_width,
            lockbar_height,
            player_x,
            player_y,
            player_z,
            player_height,
        )
    }

    /// Set the viewport rotation for the root window. Called by `main` once,
    /// at App construction time, before `eframe::run_native`. The rotation
    /// drives the input/output hooks below — None is a no-op.
    pub fn set_rotation(&mut self, rotation: egui_rotate::Rotation) {
        self.rotation = rotation;
    }

    /// Enable kiosk cursor behavior: software-scaled cursor, locked inside the
    /// window, and warped to center once the window is mapped. The cursor
    /// itself is configured (scale, lock) at `RotationPlugin` registration in
    /// `main.rs` — this flag just tells the launcher runtime that the plugin
    /// was built with a `SoftwareCursor` and the kiosk warp/lock loop applies.
    /// Window placement is handled separately via `ViewportBuilder::with_monitor`.
    /// The theme kept in the DB (System until the user picks one), applied
    /// to the context with both palettes' styles.
    pub fn apply_theme(&mut self, ctx: &egui::Context) {
        self.theme_pref = theme::theme_from_db(self.db.get_config("ui_theme").as_deref());
        theme::setup(ctx, self.theme_pref);
    }

    pub fn enable_kiosk_cursor(&mut self) {
        self.kiosk_cursor = true;
        self.kiosk_cursor_warped = false;
        log::info!("kiosk_cursor enabled — plugin owns scale/lock, warp on first frame");
    }

    /// Convenience: run `f` against the plugin's `SoftwareCursor` if the
    /// `RotationPlugin` was registered with one (kiosk mode). No-op otherwise.
    fn with_software_cursor<R>(
        ctx: &egui::Context,
        f: impl FnOnce(&mut egui_rotate::SoftwareCursor) -> R,
    ) -> Option<R> {
        ctx.with_plugin::<egui_rotate::RotationPlugin, _>(|p| p.software_cursor_mut().map(f))
            .flatten()
    }

    /// Frame-less icon buttons for the wizard/launcher headers:
    /// - Magnifier − / +: the UI zoom (stored per mode by `sync_zoom`).
    /// - Theme cycle: System (🌗) → Light (☀) → Dark (🌙) → System.
    /// - Rotation cycle: None → CW90 → CW180 → CW270 → None. Drives the
    ///   `RotationPlugin` so the root viewport rotates live — makes the
    ///   wizard readable when the operator is standing off-axis from a
    ///   pincab playfield.
    ///
    /// `icon_size` is the RichText size.
    pub(super) fn toolbar_toggles(
        &mut self,
        ctx: &egui::Context,
        ui: &mut egui::Ui,
        icon_size: f32,
    ) {
        // Magnifier: the same steps as Ctrl - / Ctrl + (egui's gui_zoom).
        let zoom_pct = (ctx.zoom_factor() * 100.0).round();
        if ui
            .add(egui::Button::new(egui::RichText::new("🔍−").size(icon_size)).frame(false))
            .on_hover_text(t!("toolbar_zoom_out", pct = zoom_pct).to_string())
            .clicked()
        {
            egui::gui_zoom::zoom_out(ctx);
        }
        if ui
            .add(egui::Button::new(egui::RichText::new("🔍+").size(icon_size)).frame(false))
            .on_hover_text(t!("toolbar_zoom_in", pct = zoom_pct).to_string())
            .clicked()
        {
            egui::gui_zoom::zoom_in(ctx);
        }

        let (theme_glyph, theme_hint, next_theme) = match self.theme_pref {
            egui::ThemePreference::System => {
                ("🌗", t!("toolbar_theme_auto"), egui::ThemePreference::Light)
            }
            egui::ThemePreference::Light => {
                ("☀", t!("toolbar_theme_light"), egui::ThemePreference::Dark)
            }
            egui::ThemePreference::Dark => (
                "🌙",
                t!("toolbar_theme_dark"),
                egui::ThemePreference::System,
            ),
        };
        let theme_resp = ui
            .add(egui::Button::new(egui::RichText::new(theme_glyph).size(icon_size)).frame(false))
            .on_hover_text(theme_hint.to_string());
        if theme_resp.clicked() {
            self.theme_pref = next_theme;
            ctx.set_theme(self.theme_pref);
            let _ = self
                .db
                .set_config("ui_theme", theme::theme_to_db(self.theme_pref));
        }

        let next_rotation = self.rotation.next_cw();
        let rot_deg = match next_rotation {
            egui_rotate::Rotation::None => "0°",
            egui_rotate::Rotation::CW90 => "90°",
            egui_rotate::Rotation::CW180 => "180°",
            egui_rotate::Rotation::CW270 => "270°",
        };
        let rot_resp = ui
            .add(egui::Button::new(egui::RichText::new("↻").size(icon_size)).frame(false))
            .on_hover_text(t!("toolbar_rotate_next", deg = rot_deg).to_string());
        if rot_resp.clicked() {
            self.rotation = next_rotation;
            ctx.with_plugin::<egui_rotate::RotationPlugin, _>(|p| {
                p.set_rotation(next_rotation);
            });
            // Remember it. Someone setting a cabinet up turns the wizard
            // upright once, on a playfield lying flat; coming back to the
            // configuration later and finding it sideways again means doing
            // it every single time.
            let _ = self
                .db
                .set_config("ui_rotation", rotation_to_db(next_rotation));
            ctx.request_repaint();
        }

        // ℹ — About box. Also the only place the launcher exposes the
        // version number now that the header label was dropped.
        let info_resp = ui
            .add(egui::Button::new(egui::RichText::new("ℹ").size(icon_size)).frame(false))
            .on_hover_text(t!("toolbar_about").to_string());
        if info_resp.clicked() {
            self.about_open = true;
        }
    }

    /// Modal-ish About window: version, homepage, license, credits. Opens
    /// from the ℹ icon in the topbar; also serves as the version display
    /// since the header no longer prints it.
    pub(super) fn render_about_window(&mut self, ctx: &egui::Context) {
        if !self.about_open {
            return;
        }
        let mut open = self.about_open;
        egui::Window::new(t!("about_title").to_string())
            .open(&mut open)
            .collapsible(false)
            .resizable(false)
            .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
            .default_width(460.0)
            .default_height(520.0)
            .show(ctx, |ui| {
                ui.vertical_centered(|ui| {
                    ui.heading(format!("PinReady v{}", env!("CARGO_PKG_VERSION")));
                    ui.add_space(4.0);
                    ui.label(t!("about_tagline"));
                    ui.add_space(12.0);
                    ui.hyperlink_to(t!("about_homepage").to_string(), env!("CARGO_PKG_HOMEPAGE"));
                    ui.hyperlink_to(
                        "💬 Discord — community & support",
                        "https://discord.gg/T37DYHmt2j",
                    );
                    // GPL is copyleft — showing © would clash with the
                    // spirit the user picked the license for. Just plain
                    // authorship + license spdx.
                    ui.label(format!("Sylvain Gargasson — {}", env!("CARGO_PKG_LICENSE")));
                });
                ui.add_space(10.0);
                ui.separator();
                ui.add_space(8.0);

                egui::ScrollArea::vertical()
                    .max_height(280.0)
                    .auto_shrink([false, false])
                    .show(ui, |ui| {
                        ui.strong(t!("about_thanks_crates_title"));
                        ui.add_space(4.0);
                        // Comma-joined prose — reads like a real
                        // acknowledgement, wraps naturally to the
                        // window width, and doesn't turn the About
                        // into a giant bullet-list.
                        ui.label(ABOUT_CRATE_THANKS.join(", "));
                        ui.add_space(12.0);
                        ui.strong(t!("about_thanks_people_title"));
                        ui.add_space(4.0);
                        // 3-column invisible grid, manually centred: the
                        // grid takes the width of its content, and we
                        // pre-pad the row so the whole block sits on the
                        // horizontal axis of the About window.
                        let col_w = 140.0;
                        let cols = 3;
                        let block_w = (col_w * cols as f32)
                            + (ui.spacing().item_spacing.x * (cols as f32 - 1.0));
                        let pad = ((ui.available_width() - block_w) * 0.5).max(0.0);
                        ui.horizontal(|ui| {
                            ui.add_space(pad);
                            egui::Grid::new("about_people_grid")
                                .num_columns(cols)
                                .min_col_width(col_w)
                                .show(ui, |ui| {
                                    // 9 names fit exactly in 3 rows,
                                    // so no dangling row to fill.
                                    for (i, name) in ABOUT_PEOPLE_THANKS.iter().enumerate() {
                                        ui.label(format!("• {name}"));
                                        if i % cols == cols - 1 {
                                            ui.end_row();
                                        }
                                    }
                                });
                        });
                        ui.add_space(8.0);
                        ui.label(egui::RichText::new(t!("about_thanks_testers")).italics());
                    });
            });
        self.about_open = open;
    }

    #[allow(clippy::type_complexity)]
    fn load_rendering_config(
        config: &VpxConfig,
    ) -> (f32, i32, i32, i32, i32, i32, i32, f32, bool, bool, bool) {
        (
            config.get_f32("Player", "AAFactor").unwrap_or(1.0),
            config.get_i32("Player", "MSAASamples").unwrap_or(0),
            config.get_i32("Player", "FXAA").unwrap_or(0),
            config.get_i32("Player", "Sharpen").unwrap_or(0),
            config.get_i32("Player", "PFReflection").unwrap_or(5),
            config.get_i32("Player", "MaxTexDimension").unwrap_or(16384),
            config.get_i32("Player", "SyncMode").unwrap_or(3),
            config.get_f32("Player", "MaxFramerate").unwrap_or(-1.0),
            // ShowFPS: 0 = off, 1 = FPS overlay, 2 = full perf stats. PinReady
            // recommends the FPS overlay on — pre-checked when unset.
            config.get_i32("Player", "ShowFPS").unwrap_or(1) != 0,
            // BallAntiStretch: keep the ball round. VPX defaults it off, but
            // PinReady recommends it on — pre-checked when unset.
            config.get_i32("Player", "BallAntiStretch").unwrap_or(1) != 0,
            // CompressTextures: VPX's own default is on.
            config.get_i32("Player", "CompressTextures").unwrap_or(1) != 0,
        )
    }

    fn load_input_mappings(config: &VpxConfig) -> Vec<InputAction> {
        let mut actions = inputs::default_actions();
        log::info!("Loading input mappings from ini...");
        for action in &mut actions {
            if let Some(mapping_str) = config.get_input_mapping(action.setting_id) {
                if mapping_str.is_empty() {
                    continue;
                }
                log::info!("  {} = {}", action.setting_id, mapping_str);
                if mapping_str.trim() == inputs::UNMAPPED {
                    action.unmapped = true;
                    continue;
                }
                // VPX alternatives (`a | b`) fill the two independent slots:
                // the first `Key;N` part lands in `keyboard`, the first
                // device part in `joystick`. `&` combos: keep the first leg,
                // like before.
                for part in mapping_str.split('|') {
                    let part = part.split('&').next().unwrap_or("").trim();
                    if let Some(sc_str) = part.strip_prefix("Key;") {
                        if action.keyboard.is_none()
                            && let Ok(sc_val) = sc_str.parse::<i32>()
                        {
                            let scancode = sdl3_sys::everything::SDL_Scancode(sc_val);
                            action.keyboard = Some(CapturedInput::Keyboard {
                                scancode,
                                name: inputs::scancode_name(scancode),
                            });
                        }
                    } else if let Some(pos) = part.find(';')
                        && action.joystick.is_none()
                    {
                        let device_id = part[..pos].to_string();
                        let rest = &part[pos + 1..];
                        if let Ok(button) = rest.split(';').next().unwrap_or("").parse::<u8>() {
                            action.joystick = Some(CapturedInput::JoystickButton {
                                device_id: device_id.clone(),
                                button,
                                name: format!("{} Button {}", device_id, button),
                            });
                        }
                    }
                }
                // A `Key;` part identical to the action's default is the
                // fallback older PinReady versions appended automatically —
                // treat it as "no custom key" so the UI keeps showing
                // "(default)" instead of a phantom customization.
                if let Some(CapturedInput::Keyboard { scancode, .. }) = &action.keyboard
                    && *scancode == action.default_scancode
                {
                    action.keyboard = None;
                }
                // The same goes for a default VPX has since dropped (Service5 on
                // 6, Service7 on -: they overlapped Credit4 and Volume Down).
                if let Some(CapturedInput::Keyboard { scancode, .. }) = &action.keyboard
                    && inputs::legacy_default_scancode(action.setting_id) == Some(*scancode)
                {
                    action.keyboard = None;
                }
            }
        }
        actions
    }

    fn load_updater_config(db: &Database) -> (String, String, String, String, VpxInstallMode) {
        let vpx_exe_path = db.get_config("vpx_exe_path").unwrap_or_default();
        let vpx_install_dir = db
            .get_config("vpx_install_dir")
            .unwrap_or_else(|| updater::default_install_dir().display().to_string());
        let vpx_fork_repo = db
            .get_config("vpx_fork_repo")
            .unwrap_or_else(|| updater::DEFAULT_FORK_REPO.to_string());
        let mut vpx_installed_tag = db.get_config("vpx_installed_tag").unwrap_or_default();
        let vpx_install_mode = if db.get_config("vpx_install_mode").as_deref() == Some("manual") {
            VpxInstallMode::Manual
        } else {
            VpxInstallMode::Auto
        };

        // Verify the executable still exists — if the install dir was deleted,
        // reset to fresh-install state so the user gets prompted to reinstall
        if !vpx_exe_path.is_empty() {
            let resolved = updater::resolve_vpx_exe(std::path::Path::new(&vpx_exe_path));
            if !resolved.is_file() {
                log::warn!(
                    "VPX executable no longer exists at {}, resetting install state",
                    resolved.display()
                );
                vpx_installed_tag.clear();
                let _ = db.set_config("vpx_installed_tag", "");
                let _ = db.set_config("vpx_exe_path", "");
                return (
                    String::new(),
                    vpx_install_dir,
                    vpx_fork_repo,
                    vpx_installed_tag,
                    vpx_install_mode,
                );
            }

            // For manual installs, always query the executable version at startup.
            // Do NOT cache this to the database — only the auto-download flow writes tags to DB.
            if vpx_install_mode == VpxInstallMode::Manual {
                if let Some(version) = crate::updater::query_vpx_version(&vpx_exe_path) {
                    log::info!("Detected VPX version from executable: {}", version);
                    vpx_installed_tag = version;
                } else {
                    log::debug!(
                        "Could not query VPX version from executable at {}",
                        vpx_exe_path
                    );
                }
            }
        }

        (
            vpx_exe_path,
            vpx_install_dir,
            vpx_fork_repo,
            vpx_installed_tag,
            vpx_install_mode,
        )
    }

    fn detect_language(db: &Database) -> usize {
        let selected = if let Some(saved_lang) = db.get_config("language") {
            LANGUAGE_OPTIONS
                .iter()
                .position(|(c, _)| *c == saved_lang)
                .unwrap_or_else(i18n::detect_system_language)
        } else {
            i18n::detect_system_language()
        };
        let (lang_code, _) = LANGUAGE_OPTIONS[selected];
        i18n::set_locale(lang_code);
        log::info!("Language: {} ({})", lang_code, LANGUAGE_OPTIONS[selected].1);
        selected
    }

    fn spawn_update_check(
        vpx_fork_repo: &str,
    ) -> Option<crossbeam_channel::Receiver<anyhow::Result<ReleaseInfo>>> {
        if vpx_fork_repo.is_empty() {
            return None;
        }
        let repo = vpx_fork_repo.to_string();
        log::info!("Checking for Visual Pinball updates from {repo}...");
        let (tx, rx) = crossbeam_channel::bounded(1);
        std::thread::spawn(move || {
            let result = updater::check_latest_release(&repo);
            let _ = tx.send(result);
        });
        Some(rx)
    }

    /// Spawn a background thread that queries the PinReady repo for the
    /// latest release and returns it via crossbeam channel.
    fn spawn_pinready_update_check()
    -> Option<crossbeam_channel::Receiver<anyhow::Result<ReleaseInfo>>> {
        log::info!(
            "Checking for PinReady updates from {}...",
            updater::PINREADY_REPO
        );
        let (tx, rx) = crossbeam_channel::bounded(1);
        std::thread::spawn(move || {
            let result = updater::check_pinready_release();
            let _ = tx.send(result);
        });
        Some(rx)
    }

    /// Second line of defence for the wizard window's size, after
    /// `screens::wizard_window_size`: once the window exists, egui knows the
    /// monitor it actually landed on, whatever SDL and winit think the screen
    /// order is. If the restored window is larger than that monitor, shrink
    /// it. A maximised or fullscreen window is the OS's business and is left
    /// alone. Runs once — after that the size is the user's.
    /// The UI zoom of this mode: the one the user picked last time, else a
    /// default scaled to the screen. Every later change (Ctrl + wheel,
    /// Ctrl +/-/0, the toolbar magnifier) is stored for next time.
    ///
    /// The default zooms were tuned on Linux, where the scale is 1. Windows
    /// adds its own display scale on top (150 % on most 4K screens), which
    /// made the wizard 3.6 times its natural size: the default is divided by
    /// that scale, so the result looks the same everywhere.
    fn sync_zoom(&mut self, ctx: &egui::Context) {
        let key = match self.mode {
            AppMode::Wizard => "ui_zoom_wizard",
            AppMode::Launcher => "ui_zoom_launcher",
        };
        let Some(saved) = self.zoom_saved else {
            let Some(native) = ctx.input(|i| i.viewport().native_pixels_per_point) else {
                return;
            };
            let zoom = self
                .db
                .get_config(key)
                .and_then(|v| v.parse::<f32>().ok())
                .filter(|z| z.is_finite())
                .unwrap_or_else(|| default_zoom(self.mode, native));
            ctx.set_zoom_factor(zoom.clamp(MIN_ZOOM, MAX_ZOOM));
            self.zoom_saved = Some(ctx.zoom_factor());
            return;
        };
        // Ctrl + wheel arrives as a zoom delta (egui turns it into one).
        let delta = ctx.input(|i| i.zoom_delta());
        if delta != 1.0 {
            ctx.set_zoom_factor((ctx.zoom_factor() * delta).clamp(MIN_ZOOM, MAX_ZOOM));
        }
        let zoom = ctx.zoom_factor();
        if (zoom - saved).abs() > 0.001 {
            let _ = self.db.set_config(key, &format!("{zoom:.3}"));
            self.zoom_saved = Some(zoom);
        }
    }

    fn fit_wizard_window(&mut self, ctx: &egui::Context) {
        // Let the first frames settle: the zoom factor is set from the app
        // creator, and the maximise request lands after window creation.
        const SETTLE_FRAMES: u64 = 3;
        // Some backends only report the monitor once the surface is mapped;
        // past this, give up rather than resize under the user's hands.
        const GIVE_UP_FRAMES: u64 = 120;
        let frame = ctx.cumulative_frame_nr();
        // An idle wizard does not repaint by itself: keep frames coming until
        // the check is done, or it would wait for the first mouse move.
        ctx.request_repaint();
        if frame < SETTLE_FRAMES {
            return;
        }
        let (maximized, fullscreen, inner, monitor) = ctx.input(|i| {
            let v = i.viewport();
            (
                v.maximized.unwrap_or(false),
                v.fullscreen.unwrap_or(false),
                v.inner_rect.map(|r| r.size()),
                v.monitor_size,
            )
        });
        if maximized || fullscreen {
            self.wizard_size_checked = true;
            return;
        }
        let (Some(inner), Some(monitor)) = (inner, monitor) else {
            if frame >= GIVE_UP_FRAMES {
                log::debug!("Wizard window: no monitor size reported, size left as is");
                self.wizard_size_checked = true;
            }
            return;
        };
        self.wizard_size_checked = true;
        if let Some([w, h]) =
            crate::screens::fit_within_monitor([inner.x, inner.y], [monitor.x, monitor.y])
        {
            log::info!(
                "Wizard window {:.0}x{:.0} pt larger than its monitor ({:.0}x{:.0} pt): resizing to {w:.0}x{h:.0}",
                inner.x,
                inner.y,
                monitor.x,
                monitor.y
            );
            ctx.send_viewport_cmd(egui::ViewportCommand::InnerSize(egui::vec2(w, h)));
        }
    }

    fn next_page(&mut self) {
        self.leave_page_hooks();
        let next = self.page.index() + 1;
        if let Some(page) = WizardPage::from_index(next) {
            self.save_current_page();
            self.page = page;
        }
    }

    /// Once per session, as soon as the VPX binary is available: run `VPX -h`
    /// in the background so the binary itself (re)writes the ini — creating
    /// the complete documented file on a fresh machine, or migrating an
    /// existing one to its current schema while preserving every value.
    fn maybe_normalize_ini(&mut self) {
        if self.ini_normalized {
            return;
        }
        let exe = updater::resolve_vpx_exe(std::path::Path::new(&self.vpx_exe_path));
        if !exe.is_file() {
            return;
        }
        self.ini_normalized = true;
        self.ini_norm_rx = Some(Self::spawn_vpx_ini_rewrite(
            exe,
            self.config.path().to_path_buf(),
        ));
    }

    /// Run `VPX -h` once in the background (see [`crate::vpx_ini_rewrite`]):
    /// VPX loads the settings (merging any existing ini) and saves the
    /// complete file before it runs any command. Skipped when the ini was
    /// already saved by this very VPX build; on Windows VPX runs on a desktop
    /// nobody sees, because its help ends in a modal box. Reports `true` when
    /// the ini was rewritten and exists afterwards.
    fn spawn_vpx_ini_rewrite(
        exe: std::path::PathBuf,
        ini: std::path::PathBuf,
    ) -> crossbeam_channel::Receiver<bool> {
        let (tx, rx) = crossbeam_channel::bounded(1);
        std::thread::spawn(move || {
            let _ = tx.send(crate::vpx_ini_rewrite::run(&exe, &ini));
        });
        rx
    }

    /// Reload the config from the file VPX just rewrote and re-derive the
    /// wizard state from it — including the Screens page when we are still on
    /// it, so an existing installation's values (cabinet dimensions, touch
    /// setting) land in the UI the user is looking at.
    ///
    /// Values only exist in memory until `finalize_wizard` flushes, so pages
    /// the user already validated are re-applied from the (intact) UI state
    /// onto the reloaded config, and only pages *beyond* the current one are
    /// re-derived from the file — never clobbering something being edited.
    fn reload_from_normalized_ini(&mut self) {
        let path = self.config.path().to_path_buf();
        match VpxConfig::load(Some(&path)) {
            Ok(config) => self.config = config,
            Err(e) => {
                log::warn!("Could not reload normalized ini: {e}");
                return;
            }
        }

        let current = self.page.index();
        for i in 0..current {
            if let Some(page) = WizardPage::from_index(i) {
                self.save_page(page);
            }
        }

        if current == WizardPage::Screens.index() {
            let (
                screen_inclination,
                lockbar_width,
                lockbar_height,
                player_x,
                player_y,
                player_z,
                player_height,
            ) = Self::load_cabinet_dimensions(&self.config);
            self.screen_inclination = screen_inclination;
            self.lockbar_width = lockbar_width;
            self.lockbar_height = lockbar_height;
            self.player_x = player_x;
            self.player_y = player_y;
            self.player_z = player_z;
            self.player_height = player_height;
            self.disable_touch = self
                .config
                .get_i32("Player", "NumberOfTimesToShowTouchMessage")
                .unwrap_or(10)
                == 0;
        }

        if current < WizardPage::Rendering.index() {
            let (
                aa_factor,
                msaa,
                fxaa,
                sharpen,
                pf_reflection,
                max_tex_dim,
                sync_mode,
                max_framerate,
                show_fps,
                ball_antistretch,
                compress_textures,
            ) = Self::load_rendering_config(&self.config);
            self.aa_factor = aa_factor;
            self.msaa = msaa;
            self.fxaa = fxaa;
            self.sharpen = sharpen;
            self.pf_reflection = pf_reflection;
            self.max_tex_dim = max_tex_dim;
            self.sync_mode = sync_mode;
            self.max_framerate = max_framerate;
            self.show_fps = show_fps;
            self.ball_antistretch = ball_antistretch;
            self.compress_textures = compress_textures;
            self.effects = effects::Effects::load(&self.config);
            self.normalize_max_framerate();
        }

        if current < WizardPage::ThreeD.index() {
            self.threed = threed::ThreeD::load(&self.config);
        }

        if current < WizardPage::Inputs.index() {
            self.actions = Self::load_input_mappings(&self.config);
            // Controller detection may already have run — re-apply its button
            // defaults, or the joystick column would come up empty until the
            // user toggles the profile combo.
            if self.pinscape_profile != inputs::PINSCAPE_PROFILE_NONE
                && let Some(vpx_id) = self.pinscape_id.clone()
            {
                self.apply_pinscape_defaults(&vpx_id);
            }
        }

        if current < WizardPage::Tilt.index() {
            self.tilt.load_from_config(&self.config);
        }
        if current < WizardPage::Audio.index() {
            self.audio.load_from_config(&self.config);
        }
        log::info!("Wizard state re-derived from the VPX-normalized ini");
    }

    fn prev_page(&mut self) {
        self.leave_page_hooks();
        if self.page.index() > 0
            && let Some(page) = WizardPage::from_index(self.page.index() - 1)
        {
            self.page = page;
        }
    }

    /// Called just before the wizard switches away from the current page.
    /// Ensures any background activity (pulse loops, etc.) is halted so it
    /// doesn't keep running invisibly on another page.
    fn leave_page_hooks(&mut self) {
        if self.page == WizardPage::Outputs && self.output_discovery.loop_running {
            self.output_discovery.stop_loop();
        }
    }

    /// Back to a blank wizard: the stored settings are already gone, so
    /// rebuild the in-memory state the same way a first run would and return
    /// to page one. Restarting the process would be simpler but would lose
    /// the window we are drawing in.
    /// Move the global VPinballX.ini aside, so the wizard rebuilds it from
    /// VPX's own documented defaults instead of layering answers onto a file
    /// whose history nobody remembers.
    ///
    /// Renamed rather than deleted: a cabinet's ini holds hand-tuned values
    /// that are nowhere else, and losing them to a misclick is not a
    /// recoverable mistake. One backup, overwritten on each reset.
    fn archive_vpx_ini() {
        let ini = crate::config::default_ini_path();
        if !ini.is_file() {
            return;
        }
        let backup = ini.with_extension("ini.reset-backup");
        match std::fs::rename(&ini, &backup) {
            Ok(()) => log::info!("VPX ini moved aside to {}", backup.display()),
            Err(e) => log::error!("Could not move the VPX ini aside: {e:#}"),
        }
    }

    pub(super) fn restart_wizard(&mut self) {
        // Rearm the once-per-session ini normalisation. With the old file
        // moved aside, `VPX -h` writes a fresh documented one, and the frame
        // loop then re-derives the wizard from it — otherwise PinReady keeps
        // answering from the config it still holds in memory, which is how a
        // reset could still report "DOF already enabled by the config".
        self.ini_normalized = false;
        self.ini_norm_rx = None;

        for page in 0..8 {
            if let Some(p) = WizardPage::from_index(page) {
                self.page = p;
                self.reset_current_page();
            }
        }
        self.page = WizardPage::Screens;
        self.tilt = crate::tilt::TiltConfig::default();
        self.tables_dir.clear();
        self.merge_src_root.clear();
        self.autostart = false;
        self.desktop_integration = false;
        self.mirror_base_url.clear();
    }

    fn reset_current_page(&mut self) {
        match self.page {
            WizardPage::Screens => {
                self.view_mode = if self.screen_count >= 2 { 1 } else { 0 };
                self.screen_inclination = 0.0;
                self.lockbar_width = 70.0;
                self.lockbar_height = 85.0;
                self.player_x = 0.0;
                self.player_y = -10.0;
                self.player_height = 167.0;
                self.player_z = (self.player_height - 12.0 - self.lockbar_height).max(0.0);
                self.external_dmd = false;
            }
            WizardPage::Rendering => {
                self.aa_factor = 1.0;
                self.msaa = 0;
                self.fxaa = 0;
                self.sharpen = 0;
                self.pf_reflection = 5;
                self.max_tex_dim = 16384;
                self.sync_mode = 3;
                self.max_framerate = -1.0;
                self.show_fps = true;
                self.ball_antistretch = true;
                self.compress_textures = true;
                self.effects = effects::Effects::default();
            }
            WizardPage::ThreeD => {
                self.threed = threed::ThreeD::default();
            }
            WizardPage::Inputs => {
                self.actions = crate::inputs::default_actions();
                self.capture_state = CaptureState::Idle;
                self.use_gamepad = false;
            }
            WizardPage::Outputs => {
                self.output_discovery.stop_session();
                self.output_discovery = DiscoveryState::default();
            }
            WizardPage::Tilt => {
                self.tilt = TiltConfig::default();
            }
            WizardPage::Audio => {
                self.audio = AudioConfig::default();
                self.audio.available_devices = AudioConfig::enumerate_devices();
            }
            WizardPage::TablesDir => {
                self.tables_dir = String::new();
            }
            WizardPage::System => {
                self.autostart = false;
                self.desktop_integration = false;
            }
        }
    }

    /// Advance the tilt plumb by the time elapsed since the previous sensor
    /// sample, applying the same chain VPX does: deadzone, then the
    /// accelerometer range as a unit conversion to m/s², then this sensor's
    /// strength factor.
    fn step_plumb(&mut self, x: f32, y: f32) {
        let deadzone = self.tilt.nudge_deadzone_pct / 100.0;
        let gate = |v: f32| {
            let magnitude = v.abs();
            if magnitude <= deadzone {
                0.0
            } else {
                v.signum() * (magnitude - deadzone) / (1.0 - deadzone)
            }
        };
        // The range converts the reading to m/s². Strength stays out of it
        // here — the nudge chain applies it, exactly where VPX does.
        let to_ms2 = self.tilt.nudge_range_g * 9.806_65;
        let accel = (gate(x) * to_ms2, gate(y) * to_ms2);
        let strength = self.tilt.nudge_scale_pct / 100.0;
        let threshold = crate::tilt::TiltConfig::threshold_angle(self.tilt.tilt_sensitivity_pct);

        let now = std::time::Instant::now();
        let elapsed_ms = self
            .plumb_last_step
            .map_or(8, |t| now.duration_since(t).as_millis().clamp(1, 50) as u32);
        self.plumb_last_step = Some(now);
        for _ in 0..elapsed_ms {
            // Sensor → nudge chain → cabinet acceleration → plumb, the same
            // order the engine uses.
            self.nudge_sim.step(
                accel,
                strength,
                crate::nudge_sim::DEFAULT_CAB_WEIGHT_KG,
                self.tilt.nudge_sensor_type,
            );
            self.plumb.step(
                self.nudge_sim.cabinet_acceleration(),
                self.tilt.plumb_damping,
                threshold,
            );
            if self.plumb.tilted {
                self.plumb_tilt_until = Some(now + std::time::Duration::from_millis(700));
            }
        }
    }

    /// Process joystick events during wizard mode (tilt viz, input capture, device detection).
    fn process_wizard_joystick_events(&mut self) {
        let events: Vec<JoystickEvent> = self
            .joystick_rx
            .as_ref()
            .map(|rx| rx.try_iter().collect())
            .unwrap_or_default();

        for event in events {
            match &event {
                JoystickEvent::AccelUpdate { x, y } => {
                    self.accel_x = *x;
                    self.accel_y = *y;
                    // Step the plumb here, on every sample, rather than once
                    // per frame: the board reports at ~125 Hz and a late
                    // nudge lasts a few milliseconds, so keeping only the
                    // last sample of each frame either misses the knock or
                    // smears it over three times its real duration. Either
                    // way the pendulum barely moved — which is exactly how
                    // it looked.
                    self.step_plumb(*x, *y);
                }
                JoystickEvent::ButtonDown {
                    device_id,
                    button,
                    name,
                } => {
                    if let CaptureState::Capturing(idx) = self.capture_state
                        && !(self.auto_map_active
                            && self.auto_map_device != AutoMapDevice::Joystick)
                    {
                        if idx < self.actions.len() {
                            // Fills the joystick slot only — the keyboard
                            // binding of the action is kept alongside.
                            self.actions[idx].unmapped = false;
                            self.actions[idx].joystick = Some(CapturedInput::JoystickButton {
                                device_id: device_id.clone(),
                                button: *button,
                                name: name.clone(),
                            });
                        }
                        // In auto-map mode, advance to the next action;
                        // otherwise just go Idle. Mirrors the keyboard-
                        // capture path in inputs_page.rs.
                        self.advance_capture_or_finish();
                    }
                }
                JoystickEvent::ButtonUp { .. } => {}
                JoystickEvent::AxisMotion { .. } => {}
                // Detection applies the profile's default buttons — unless the
                // user explicitly selected the "None" profile, which opts out
                // of any auto-mapping.
                JoystickEvent::PinscapeDetected { vpx_id } => {
                    if self.pinscape_profile != inputs::PINSCAPE_PROFILE_NONE {
                        self.apply_pinscape_defaults(vpx_id);
                    } else {
                        self.pinscape_id = Some(vpx_id.clone());
                    }
                }
                JoystickEvent::DudesCabDetected { vpx_id } => {
                    log::info!("DudesCab detected in UI: {}", vpx_id);
                    if self.pinscape_profile != inputs::PINSCAPE_PROFILE_NONE {
                        self.pinscape_profile = 2;
                        self.apply_pinscape_defaults(vpx_id);
                    } else {
                        self.pinscape_id = Some(vpx_id.clone());
                    }
                }
                JoystickEvent::PinOneDetected { vpx_id } => {
                    log::info!("CSD PinOne detected in UI: {}", vpx_id);
                    if self.pinscape_profile != inputs::PINSCAPE_PROFILE_NONE {
                        self.pinscape_profile = 3;
                        self.apply_pinscape_defaults(vpx_id);
                    } else {
                        self.pinscape_id = Some(vpx_id.clone());
                    }
                }
                JoystickEvent::GamepadDetected { vpx_id, name } => {
                    log::info!("Gamepad detected in UI: {} ({})", name, vpx_id);
                    self.gamepad_id = Some(vpx_id.clone());
                }
            }
        }
    }

    /// Apply Pinscape default button mapping when a controller is detected.
    /// Profile is selected by `pinscape_profile`: 0 = KL25Z, 1 = Pico (OpenPinballDevice).
    fn apply_pinscape_defaults(&mut self, vpx_id: &str) {
        log::info!("Pinscape detected in UI: {}", vpx_id);
        self.pinscape_id = Some(vpx_id.to_string());
        let defaults = pinscape_button_defaults(self.pinscape_profile);
        for (action_id, button) in defaults {
            if let Some(action) = self.actions.iter_mut().find(|a| a.setting_id == *action_id)
                && action.joystick.is_none()
                && !action.unmapped
            {
                action.joystick = Some(CapturedInput::JoystickButton {
                    device_id: vpx_id.to_string(),
                    button: *button,
                    name: format!("{} Button {}", vpx_id, button),
                });
            }
        }
    }
}

mod audio_page;
mod autostart;
mod bgcache;
mod desktop_integration;
mod effects;
mod help;
mod inputs_page;
mod launcher;
mod launcher_input;
mod launcher_ui;
mod outputs_page;
mod rendering_page;
mod save;
mod screens_page;
mod system_apply;
mod system_page;
mod tables_dir_page;
pub mod theme;
mod threed;
mod threed_page;
mod tilt_page;
mod vpinplay_link;

pub(crate) use help::help_marker;

use autostart::{is_autostart_enabled, set_autostart};
use desktop_integration::{is_desktop_integration_installed, set_desktop_integration};

impl eframe::App for App {
    /// The `RotationPlugin` (registered in `main.rs`) owns input rotation,
    /// primitive rotation, cursor drawing and OS-cursor hiding — none of
    /// which lives in this file anymore.
    ///
    /// The one bit that still needs a hook is a Wayland kiosk workaround:
    /// under `CursorGrab::Locked` the OS delivers only raw `MouseMoved`
    /// deltas, no `WindowEvent::CursorMoved`. egui's hover hit-test relies
    /// on `PointerMoved` to know where the pointer is, so we inject a
    /// synthetic one every frame the software cursor is captured. The
    /// value is a dummy: the plugin's own `input_hook` (which runs right
    /// after this) rewrites it to the current `virtual_pos` before egui
    /// consumes it.
    fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
        if raw_input.viewport_id != egui::ViewportId::ROOT || self.rotation.is_none() {
            return;
        }
        let has_virtual_cursor = ctx
            .with_plugin::<egui_rotate::RotationPlugin, _>(|p| {
                p.software_cursor().and_then(|c| c.virtual_pos()).is_some()
            })
            .unwrap_or(false);
        if has_virtual_cursor {
            raw_input
                .events
                .push(egui::Event::PointerMoved(egui::Pos2::ZERO));
        }
    }

    fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
        static FIRST_FRAME: std::sync::Once = std::sync::Once::new();
        FIRST_FRAME.call_once(|| {
            log::info!(
                "startup: first frame at +{} ms",
                crate::startup_timing::since_start_ms()
            )
        });
        self.sync_zoom(ui.ctx());
        if self.mode == AppMode::Wizard && !self.wizard_size_checked {
            self.fit_wizard_window(ui.ctx());
        }

        // Two-step VPX launch: when the launcher clicks a table it stashes
        // the path in `pending_vpx_launch`; this frame asks the compositor
        // for a fresh xdg-activation-v1 token, which eframe hands over a
        // frame or more later. A 500 ms deadline bails out if the compositor
        // never replies so the launch isn't held forever.
        if self.activation_token_wanted {
            self.activation_token_wanted = false;
            let _stale = frame.take_activation_token();
            frame.request_activation_token();
        }
        if let Some((path, requested_at)) = self.pending_vpx_launch.clone() {
            let token = frame.take_activation_token();
            let deadline_exceeded = requested_at.elapsed() >= std::time::Duration::from_millis(500);
            if token.is_some() || deadline_exceeded {
                self.pending_vpx_launch = None;
                if token.is_none() {
                    log::warn!(
                        "xdg-activation reply missed 500 ms deadline; launching VPX without token"
                    );
                }
                self.launch_table(&path, token);
            } else {
                ui.ctx().request_repaint();
            }
        }

        // Kiosk cursor: scale + lock + virtual-pos bootstrap. Disabled while
        // VPX is running so it can take over keyboard/mouse input cleanly.
        let vpx_running = self.vpx_running.load(Ordering::Relaxed);
        if self.kiosk_cursor && !vpx_running {
            let ctx = ui.ctx();
            // Force a repaint every frame. Mutter Wayland skips presenting
            // surfaces that don't have user-focus even when we submit fresh
            // frames; without this the cursor visibly freezes although
            // virtual_pos is updating internally each frame.
            ctx.request_repaint();

            // The SoftwareCursor lock and the OS-level pointer grab are owned
            // by the egui-rotate plugin since 1.1: the lock is set once at
            // construction (nothing toggles it anymore — VPX launch/resume
            // release and re-capture the *whole* cursor instead), and the
            // grab is sent on capture/release transitions with the right
            // per-platform mode (see `os_grab` in `main.rs`).
            //
            // `CursorVisible(false)` stays: the plugin only hides the OS
            // pointer while the software cursor is captured, and there is a
            // captureless gap right after VPX exits (until the warp latch
            // below re-seeds the cursor) where the OS pointer would flicker
            // on top of the playfield.
            // (Sent below, once the capture state is known: hiding the OS
            // pointer while nothing is captured leaves the screen with no
            // cursor at all.)

            // No focus, no pointer. A compositor only grants a pointer
            // constraint to a focused surface, so an unfocused playfield
            // means the cursor cannot be confined (it wanders onto the
            // backglass) and receives no motion (it sits still) — both at
            // once, which is exactly what a cabinet reports as "the mouse is
            // dead". Measured on the cabinet: the DMD cover takes the focus
            // when it maps — it is created after the playfield — and Mutter
            // then refuses every `Focus` we send, five in a row, because
            // asking is exactly what focus-stealing prevention blocks.
            //
            // So stop asking. A window that has just appeared gets the focus
            // without requesting it, and hiding then re-showing the playfield
            // maps it after the covers. One shot, and only in cabinet mode,
            // where the covers exist at all.
            let focused = ctx.input(|i| i.viewport().focused).unwrap_or(false);
            if focused {
                self.kiosk_focus_tries = 0;
            } else if self.kiosk_focus_tries < 3
                && self
                    .kiosk_focus_at
                    .is_none_or(|t| t.elapsed() >= std::time::Duration::from_secs(2))
            {
                self.kiosk_focus_tries += 1;
                self.kiosk_focus_at = Some(std::time::Instant::now());
                log::info!(
                    "kiosk: playfield unfocused, remapping (attempt {})",
                    self.kiosk_focus_tries
                );
                ctx.send_viewport_cmd(egui::ViewportCommand::Visible(false));
                ctx.send_viewport_cmd(egui::ViewportCommand::Visible(true));
                ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
                ctx.request_repaint();
            }

            // Read the plugin's cursor state once: track the most recent
            // virtual position so we can restore it after a spurious
            // capture loss (Mutter Wayland drops the pointer-constraints
            // lock during focus thrash), and detect said capture loss to
            // reset the warp latch.
            let (virtual_pos, is_captured, is_dormant, opacity) = ctx
                .with_plugin::<egui_rotate::RotationPlugin, _>(|p| {
                    let c = p.software_cursor();
                    (
                        c.and_then(|c| c.virtual_pos()),
                        c.is_some_and(|c| c.is_captured()),
                        c.is_some_and(|c| c.is_dormant()),
                        c.map_or(0.0, |c| c.opacity()),
                    )
                })
                .unwrap_or((None, false, false, 0.0));

            // Cursor diagnostics, once a second and only when something
            // changed: "it vanishes and never comes back" has at least three
            // distinct causes (dormancy that won't wake, a capture the
            // compositor dropped, a pointer that left for another surface)
            // and they are indistinguishable from the outside.
            if std::env::var("PINREADY_CURSOR_DIAG").is_ok() {
                // Rounded to 10 points: a cursor that moves (or does not) is the question
                let cell = virtual_pos.map(|p| ((p.x / 10.0) as i32, (p.y / 10.0) as i32));
                let state = (is_captured, is_dormant, focused, cell);
                let now = std::time::Instant::now();
                let due = self
                    .kiosk_diag_at
                    .is_none_or(|t| now.duration_since(t).as_millis() >= 1000);
                if due && self.kiosk_diag_state != Some(state) {
                    self.kiosk_diag_state = Some(state);
                    self.kiosk_diag_at = Some(now);
                    let (moves, keys, gone) = ctx.input(|i| {
                        i.raw.events.iter().fold((0, 0, 0), |(m, k, g), e| match e {
                            egui::Event::MouseMoved(_) | egui::Event::PointerMoved(_) => {
                                (m + 1, k, g)
                            }
                            egui::Event::Key { .. } | egui::Event::Text(_) => (m, k + 1, g),
                            egui::Event::PointerGone => (m, k, g + 1),
                            _ => (m, k, g),
                        })
                    });
                    log::info!(
                        "cursor: captured={is_captured} dormant={is_dormant} opacity={opacity:.2} \
                         focused={focused} pos={virtual_pos:?} events(move={moves} key={keys} gone={gone})"
                    );
                }
            }
            // Hide the OS pointer only while the software cursor is actually
            // drawn. The two vanish together otherwise: the pointer leaves
            // the window, `PointerGone` releases the software cursor in a
            // single frame, and a hidden OS pointer on top of that leaves the
            // screen with nothing to aim — and no way to click the playfield
            // back into focus.
            ctx.send_viewport_cmd(egui::ViewportCommand::CursorVisible(
                !(is_captured && virtual_pos.is_some()),
            ));

            if let Some(p) = virtual_pos {
                self.kiosk_last_virtual_pos = Some(p);
            }
            if self.kiosk_cursor_warped && !is_captured {
                self.kiosk_cursor_warped = false;
            }

            if !self.kiosk_cursor_warped {
                // Bootstrap the SoftwareCursor at the last known position
                // (or the viewport centre on first run).
                //
                // We use `ctx.viewport_rect()` rather than
                // `viewport().inner_rect` because the latter relies on
                // `winit::Window::inner_position()`, which returns None
                // under Wayland (the protocol doesn't expose absolute
                // window positions to clients).
                //
                // Reject the egui placeholder default
                // `Rect::from_min_size(0, vec2(10_000, 10_000))` — surfaced
                // as ~8333×8333 after `round_ui` — by detecting a square
                // viewport_rect with both dimensions ≥ 4000 logical points.
                // No real cabinet display is perfectly square at that size.
                let vr = ctx.viewport_rect();
                let placeholder =
                    (vr.width() == vr.height() && vr.width() > 4000.0) || vr.area() <= 1.0;
                if !placeholder {
                    // Clamp the restore position inside a safe inner rect.
                    // The cursor arrow is anchored at its tip and extends
                    // ~60 logical points down-right (scale 3 × 16-20 base);
                    // under CW90 the inverse rotation maps "down-right" to
                    // "up-left" physically, so a virtual_pos within ~60
                    // points of the right or bottom edge clips half the
                    // arrow off-screen and the cursor disappears visually.
                    let safe_margin = 64.0;
                    let safe = vr.shrink(safe_margin);
                    let target = self
                        .kiosk_last_virtual_pos
                        .map(|p| {
                            egui::pos2(
                                p.x.clamp(safe.min.x, safe.max.x),
                                p.y.clamp(safe.min.y, safe.max.y),
                            )
                        })
                        .unwrap_or_else(|| vr.center());
                    Self::with_software_cursor(ctx, |c| c.set_virtual_pos(target));
                    // Re-assert the OS grab by hand. The plugin only sends
                    // `CursorGrab` when its own captured/released state
                    // flips, and it still believes it holds one — but Mutter
                    // silently dropped the pointer constraint when focus
                    // thrashed. Without this the cursor is captured on our
                    // side and free on the compositor's: it drifts off onto
                    // the backglass and stops moving.
                    ctx.send_viewport_cmd(egui::ViewportCommand::CursorGrab(
                        if cfg!(target_os = "macos") {
                            egui::viewport::CursorGrab::Locked
                        } else {
                            egui::viewport::CursorGrab::Confined
                        },
                    ));
                    self.kiosk_cursor_warped = true;
                }
                ctx.request_repaint();
            }
        }

        // Scheduled close, set by `finalize_wizard`.
        if let Some(deadline) = self.close_at {
            if std::time::Instant::now() >= deadline {
                ui.ctx().send_viewport_cmd(egui::ViewportCommand::Close);
                return;
            }
            ui.ctx().request_repaint();
        }

        // Another launch asked us to raise our window. We now actually
        // reach this branch immediately because `register_egui_ctx` lets
        // the socket listener call `request_repaint()` on wake.
        //
        // `Focus` alone is often refused by focus-stealing prevention
        // (Mutter X11 & Wayland, KWin…). The AlwaysOnTop toggle forces a
        // z-order bump even when the WM blocks direct raise; we drop back
        // to Normal 300ms later so the window isn't permanently pinned.
        if crate::pidlock::take_focus_request() {
            log::info!("Focus request from second launch — raising window");
            let ctx = ui.ctx();
            ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false));
            ctx.send_viewport_cmd(egui::ViewportCommand::Visible(true));
            ctx.send_viewport_cmd(egui::ViewportCommand::WindowLevel(
                egui::WindowLevel::AlwaysOnTop,
            ));
            ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
            ctx.send_viewport_cmd(egui::ViewportCommand::RequestUserAttention(
                egui::UserAttentionType::Informational,
            ));
            self.focus_reset_at =
                Some(std::time::Instant::now() + std::time::Duration::from_millis(300));
            ctx.request_repaint();
        }
        if let Some(deadline) = self.focus_reset_at {
            if std::time::Instant::now() >= deadline {
                ui.ctx()
                    .send_viewport_cmd(egui::ViewportCommand::WindowLevel(
                        egui::WindowLevel::Normal,
                    ));
                self.focus_reset_at = None;
            } else {
                ui.ctx().request_repaint();
            }
        }

        // Route based on mode — joystick events are handled per-mode
        if self.mode == AppMode::Launcher {
            self.render_launcher(ui);
            return;
        }

        self.process_wizard_joystick_events();

        // Have VPX rewrite the ini once per session, as soon as its binary is
        // available (present at startup, picked manually, or just downloaded —
        // this per-frame guard covers all three). `VPX -h` loads the existing
        // ini (or nothing), then saves the complete, documented, migrated file
        // without showing anything: the authoritative binary owns the schema,
        // PinReady only layers its values on top. When it lands, the wizard
        // state is re-derived from the normalized file.
        self.maybe_normalize_ini();
        if let Some(rx) = &self.ini_norm_rx {
            match rx.try_recv() {
                Ok(ok) => {
                    self.ini_norm_rx = None;
                    if ok {
                        self.reload_from_normalized_ini();
                    }
                }
                Err(crossbeam_channel::TryRecvError::Empty) => {
                    ui.ctx().request_repaint();
                }
                Err(crossbeam_channel::TryRecvError::Disconnected) => {
                    self.ini_norm_rx = None;
                }
            }
        }

        // === Wizard mode ===

        self.render_about_window(ui.ctx());

        // Push the scrollbar flush to the window edge — default bar_outer_margin
        // leaves a small gap on the right that looks awkward on this layout.
        ui.style_mut().spacing.scroll.bar_outer_margin = 0.0;

        // Header: the wordmark and the toolbar, then the steps as a strip of
        // pills that wraps on a narrow (rotated) window.
        let p = theme::pal(ui.ctx());
        egui::Panel::top("wizard_header")
            .frame(
                egui::Frame::new()
                    .fill(p.bar)
                    .stroke(egui::Stroke::new(1.0, p.border))
                    .inner_margin(egui::Margin::symmetric(14, 10)),
            )
            .show(ui, |ui| {
                egui::Sides::new().show(
                    ui,
                    |ui| {
                        theme::dmd_wordmark(ui, 3.0)
                            .on_hover_text(format!("PinReady v{}", env!("CARGO_PKG_VERSION")));
                    },
                    |ui| {
                        // The right side fills right to left; give the
                        // toolbar a left-to-right box as wide as it measured
                        // last frame, so it reads in order and stays right.
                        let id = egui::Id::unique("wizard_toolbar_width");
                        let width = ui.data(|d| d.get_temp::<f32>(id)).unwrap_or(160.0);
                        let resp = ui.allocate_ui_with_layout(
                            egui::vec2(width, ui.spacing().interact_size.y),
                            egui::Layout::left_to_right(egui::Align::Center),
                            |ui| {
                                let toolbar_size = (ui.spacing().interact_size.y - 4.0).max(14.0);
                                let ctx = ui.ctx().clone();
                                self.toolbar_toggles(&ctx, ui, toolbar_size);
                                ui.min_rect().width()
                            },
                        );
                        let used = resp.inner;
                        if (used - width).abs() > 0.5 {
                            ui.data_mut(|d| d.insert_temp(id, used));
                            ui.ctx().request_repaint();
                        }
                    },
                );
                ui.add_space(8.0);
                // The whole strip needs about 800 points; narrower (a rotated
                // playfield, a zoomed-in window) shows the current step and
                // where it stands, since egui cannot wrap the pills.
                let current = self.page.index();
                let count = WizardPage::count();
                let compact = ui.available_width() < 800.0;
                ui.horizontal(|ui| {
                    ui.spacing_mut().item_spacing = egui::vec2(5.0, 5.0);
                    for i in 0..count {
                        if compact && i != current {
                            continue;
                        }
                        let page =
                            WizardPage::from_index(i).expect("WizardPage index within count()");
                        let (fill, fg) = match i.cmp(&current) {
                            std::cmp::Ordering::Less => (p.raised, p.text_muted),
                            std::cmp::Ordering::Equal => (p.accent, p.on_accent),
                            std::cmp::Ordering::Greater => {
                                (egui::Color32::TRANSPARENT, p.text_faint)
                            }
                        };
                        egui::Frame::new()
                            .fill(fill)
                            .stroke(if i > current {
                                egui::Stroke::new(1.0, p.border)
                            } else {
                                egui::Stroke::NONE
                            })
                            .corner_radius(egui::CornerRadius::same(theme::RADIUS_SMALL))
                            .inner_margin(egui::Margin::symmetric(9, 3))
                            .show(ui, |ui| {
                                ui.horizontal(|ui| {
                                    ui.spacing_mut().item_spacing.x = 5.0;
                                    ui.label(
                                        egui::RichText::new((i + 1).to_string())
                                            .monospace()
                                            .color(fg)
                                            .strong(),
                                    );
                                    let title = egui::RichText::new(page.title()).color(fg);
                                    ui.label(if i == current { title.strong() } else { title });
                                });
                            });
                    }
                    if compact {
                        ui.label(
                            egui::RichText::new(format!("{} / {count}", current + 1))
                                .monospace()
                                .color(p.text_faint),
                        );
                    }
                });
            });

        // Navigation footer
        egui::Panel::bottom("wizard_nav")
            .frame(
                egui::Frame::new()
                    .fill(p.bar)
                    .stroke(egui::Stroke::new(1.0, p.border))
                    .inner_margin(egui::Margin::symmetric(14, 10)),
            )
            .show(ui, |ui| {
                ui.horizontal(|ui| {
                    if self.page.index() > 0
                        && ui
                            .add(theme::secondary_button(
                                format!(
                                    "\u{2190}  {}",
                                    t!("wizard_previous").trim_start_matches(['<', ' '])
                                ),
                                &p,
                            ))
                            .clicked()
                    {
                        self.prev_page();
                    }

                    // Leaves without writing anything: the settings of the pages
                    // already validated only live in memory until the last page.
                    if ui
                        .add(theme::secondary_button(t!("wizard_quit_nosave"), &p))
                        .clicked()
                    {
                        ui.ctx().send_viewport_cmd(egui::ViewportCommand::Close);
                    }

                    if ui
                        .add(
                            egui::Button::new(
                                egui::RichText::new(t!("wizard_reset")).color(p.text_muted),
                            )
                            .frame(false),
                        )
                        .clicked()
                    {
                        self.reset_current_page();
                    }

                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        // Block navigation on Screens page if VPX is not installed or downloading
                        let on_screens_page = self.page == WizardPage::Screens;
                        let downloading = self.update_downloading && on_screens_page;
                        let vpx_missing = on_screens_page && {
                            let resolved =
                                updater::resolve_vpx_exe(std::path::Path::new(&self.vpx_exe_path));
                            self.vpx_exe_path.is_empty() || !resolved.is_file()
                        };
                        // Tables dir is mandatory before leaving the Tables page —
                        // skipping it would land the user in a launcher that has
                        // nothing to scan and shows an empty grid.
                        let on_tables_page = self.page == WizardPage::TablesDir;
                        let tables_dir_missing = on_tables_page
                            && (self.tables_dir.is_empty()
                                || !std::path::Path::new(&self.tables_dir).is_dir());
                        // Finish was pressed: the window is closing.
                        let finishing = self.close_at.is_some();
                        let blocked = downloading || vpx_missing || tables_dir_missing || finishing;

                        if self.page.index() < WizardPage::count() - 1 {
                            let label = t!("wizard_next").trim_end_matches(['>', ' ']).to_string();
                            let btn =
                                theme::primary_button(format!("{label}  \u{2192}"), &p, !blocked);
                            if ui.add_enabled(!blocked, btn).clicked() {
                                self.next_page();
                            }
                        } else {
                            let btn = theme::primary_button(t!("wizard_finish"), &p, !blocked);
                            if ui.add_enabled(!blocked, btn).clicked() {
                                self.finalize_wizard(ui.ctx());
                            }
                        }
                        if vpx_missing && !downloading {
                            ui.colored_label(p.warning, t!("vpx_required"));
                        }
                        if tables_dir_missing {
                            ui.colored_label(p.warning, t!("tables_path_required_inline"));
                        }
                        if downloading {
                            let (current, total) = self.update_progress;
                            if total > 0 {
                                let pct = current as f32 / total as f32;
                                let mb = current / (1024 * 1024);
                                let total_mb = total / (1024 * 1024);
                                ui.add(
                                    egui::ProgressBar::new(pct)
                                        .text(format!("{mb}/{total_mb} MB"))
                                        .desired_width(200.0),
                                );
                            } else {
                                ui.spinner();
                            }
                            ui.ctx().request_repaint();
                        }
                    });
                });
            });

        // Main content — zero right/bottom inner+outer margins and no stroke
        // so the scrollbar sits flush against the window edge.
        egui::CentralPanel::default()
            .frame(
                egui::Frame::central_panel(ui.style())
                    .inner_margin(egui::Margin {
                        left: 18,
                        right: 0,
                        top: 14,
                        bottom: 0,
                    })
                    .outer_margin(egui::Margin::ZERO)
                    .stroke(egui::Stroke::NONE),
            )
            .show(ui, |ui| {
                egui::ScrollArea::vertical()
                    .auto_shrink([false, false])
                    .scroll_bar_visibility(
                        egui::scroll_area::ScrollBarVisibility::VisibleWhenNeeded,
                    )
                    .show(ui, |ui| {
                        ui.add_space(0.0); // ensure full width
                        let _ = ui.available_width(); // force layout to use full width
                        // Process VPX download progress on every page so the
                        // download completes even when the user navigates away
                        // from the Screens page.
                        self.process_update_check();
                        self.process_pinready_update_check(ui.ctx());

                        // The cards keep clear of the flush scrollbar
                        egui::Frame::new()
                            .inner_margin(egui::Margin {
                                left: 0,
                                right: 18,
                                top: 0,
                                bottom: 12,
                            })
                            .show(ui, |ui| match self.page {
                                WizardPage::Screens => self.render_screens_page(ui),
                                WizardPage::Rendering => self.render_rendering_page(ui),
                                WizardPage::ThreeD => self.render_threed_page(ui),
                                WizardPage::Inputs => self.render_inputs_page(ui),
                                WizardPage::Outputs => self.render_outputs_page(ui),
                                WizardPage::Tilt => self.render_tilt_page(ui),
                                WizardPage::Audio => self.render_audio_page(ui),
                                WizardPage::TablesDir => self.render_tables_dir_page(ui),
                                WizardPage::System => self.render_system_page(ui),
                            });
                    });
            });
    }
}

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

    #[test]
    fn default_zoom_is_divided_by_the_display_scale() {
        // Linux at scale 1: unchanged.
        assert_eq!(default_zoom(AppMode::Wizard, 1.0), 2.4);
        assert_eq!(default_zoom(AppMode::Launcher, 1.0), 1.2);
        // Windows at 150 %: the same physical size as on Linux.
        assert!((default_zoom(AppMode::Wizard, 1.5) * 1.5 - 2.4).abs() < 1e-6);
        // Never below 1: a 250 % screen keeps egui's own size.
        assert_eq!(default_zoom(AppMode::Launcher, 2.5), 1.0);
    }
}