pinready 0.27.1

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
use super::*;

/// Whether the cover windows (backglass, DMD, topper) let the pointer through.
///
/// Needed under Mutter, which otherwise hands a cover the pointer focus and
/// strands the arrow on the backglass (see `render_cover_viewports`). Never
/// on Windows: winit implements pass-through there by making the window
/// layered (`WS_EX_LAYERED | WS_EX_TRANSPARENT`) without ever calling
/// `SetLayeredWindowAttributes`, and an OpenGL window in that state is not
/// guaranteed to show what it renders — the likely reason a cabinet reported
/// the backglass blank on the first launch and then frozen on one picture
/// while browsing (`log_backglass_cover` tells the two apart). Windows has
/// no use for it anyway: the kiosk cursor is confined to the playfield
/// window with `ClipCursor`, so the pointer never reaches a cover.
const COVER_MOUSE_PASSTHROUGH: bool = !cfg!(target_os = "windows");

/// On Windows the backglass cover is drawn as an immediate viewport, inside the
/// playfield's own pass. As a deferred viewport it got its first pass when its
/// window was created and none after: a field log showed the cover painted
/// once, then silent while the selection moved through several tables. It
/// stayed on the first table's picture, or black when that first pass ran
/// before the picture was decoded. Immediate costs a second window draw per
/// playfield frame, which the launcher can afford; the static DMD and topper
/// covers stay deferred, one pass is all they need.
const BACKGLASS_COVER_IMMEDIATE: bool = cfg!(target_os = "windows");

impl App {
    pub(super) fn render_launcher(&mut self, ui: &mut egui::Ui) {
        // Install image loaders once
        egui_extras::install_image_loaders(ui.ctx());

        // About window: painted on top of everything when open.
        self.render_about_window(ui.ctx());

        self.process_index();
        self.process_vpinplay();
        self.process_bg_extraction();
        self.process_vbs_extraction();
        self.process_b2s_dmd();
        self.process_preview_audio(ui.ctx());
        // Process VPX status before the joystick handler so the post-exit
        // input grace window (armed in `process_vpx_status`) is already set
        // on the very first frame `vpx_running` reads false — otherwise the
        // exit button leaks one frame of nav before suppression kicks in.
        self.process_vpx_status(ui.ctx());
        self.handle_launcher_joystick(ui);
        self.process_update_check();
        self.process_pinready_update_check(ui.ctx());
        // Only repaint when needed: bg extraction in progress, VPX running, joystick connected, or update in progress
        if self.bg_rx.is_some()
            || self.index_rx.is_some()
            || self.vpinplay_rx.is_some()
            || self.vpx_running.load(Ordering::Relaxed)
            || self.joystick_rx.is_some()
            || self.update_downloading
            || self.update_check_rx.is_some()
        {
            ui.ctx().request_repaint();
        }

        // Keyboard + (cabinet-only) mouse wheel nav. The collection
        // and string-vs-enum mapping live in `launcher_input` so this
        // call site stays a one-liner. Joystick events go through the
        // same `apply_launcher_action` dispatch from
        // `handle_launcher_joystick`.
        if !self.vpx_running.load(Ordering::Relaxed) {
            if self.launcher_input_suppressed() {
                // Drop what is queued rather than merely skipping our own
                // reader: the exit key that closed VPX is still in flight,
                // and anything left in the queue fires the moment the window
                // closes — which is the bug this window exists to prevent.
                ui.input_mut(|i| i.events.clear());
            } else if !self.tables.is_empty() {
                for action in
                    launcher_input::collect_actions(ui, self.rotation, self.table_filter.is_empty())
                {
                    self.apply_launcher_action(action, ui.ctx());
                }
            }
        }

        // Window placement handled via ViewportBuilder::with_monitor (main PF)
        // and render_cover_viewports (BG/DMD/Topper).

        // The launcher draws straight on the root Ui, with no panel behind
        // it: give it the theme's ground, or the clear color shows through.
        let ground = ui.max_rect();
        ui.painter()
            .rect_filled(ground, 0.0, theme::pal(ui.ctx()).bg);

        // Header size: 2% of the window's smaller side, rounded up to the
        // next integer. Scales with the screen — readable on 4K cabinet PFs,
        // compact on desktop/windowed. The smaller side, not the height: a
        // rotated playfield is tall and narrow, and a header sized on its
        // height ran out of width.
        let h_size = (ui.available_height().min(ui.available_width()) * 0.02).ceil();
        ui.add_space(6.0);
        // The row is laid out in three parts, each in its own child Ui: the
        // toolbar and Rebuild on the left, Configuration and Quit on the
        // right, and the search field in the middle, centred between them
        // and as wide as what is typed. The side groups are drawn first so
        // the middle knows how much room is left.
        let hrow_w = ui.available_size_before_wrap().x;
        let row_h = (h_size * 1.8).max(ui.spacing().interact_size.y);
        let (row_rect, _) = ui.allocate_exact_size(egui::vec2(hrow_w, row_h), egui::Sense::hover());
        let ctx = ui.ctx().clone();
        let p = theme::pal(&ctx);
        let header_button = |text: String| {
            egui::Button::new(egui::RichText::new(text).size(h_size).color(p.text))
                .fill(egui::Color32::TRANSPARENT)
                .stroke(egui::Stroke::new(1.0, p.border))
        };

        let mut left = ui.new_child(
            egui::UiBuilder::new()
                .max_rect(row_rect)
                .layout(egui::Layout::left_to_right(egui::Align::Center)),
        );
        // The DMD wordmark when the row has room for it (a rotated
        // playfield is narrow, the search field matters more).
        if hrow_w > 900.0 {
            theme::dmd_wordmark(&mut left, (h_size * 0.17).max(2.0));
            left.add_space(12.0);
        }
        // Toolbar toggles (theme + rotation + info). The version string
        // used to sit here but ate too much width on rotated viewports; it
        // now lives inside the About window opened by the info icon.
        self.toolbar_toggles(&ctx, &mut left, h_size);
        left.add_space(16.0);
        // Rebuild button: single click, flushes backglass +
        // vbs_patches caches and re-scans from scratch. The
        // mtime-invalidation inside `scan_tables` already
        // handles "new tables" and "source file changed"
        // cases transparently on every scan.
        let label = t!("launcher_rebuild").to_string();
        if left.add(header_button(label)).clicked() {
            log::info!("Rebuild: flushing backglass + vbs_patches caches, full re-scan");
            if let Err(e) = self.db.clear_backglass() {
                log::error!("clear_backglass failed: {e}");
            }
            if let Err(e) = self.db.clear_vbs_patches() {
                log::error!("clear_vbs_patches failed: {e}");
            }
            if let Err(e) = self.db.clear_b2s_dmd() {
                log::error!("clear_b2s_dmd failed: {e}");
            }
            self.tables.iter_mut().for_each(|t| t.has_bg = false);
            self.scan_tables();
        }

        // Sort order: one button that goes through the choices (the S key
        // does the same). Favourites are toggled with F or the ball-launch
        // button, ratings 0 to 5 with the number keys.
        let sort_label = format!("{}: {}", t!("launcher_sort"), self.sort_mode.label());
        if left.add(header_button(sort_label)).clicked() {
            self.cycle_sort();
        }

        // Update counter — surfaces tables flagged `update_available` by the
        // catalog worker. The per-card badge is the primary affordance.
        // Update buttons/progress used to live in this row, but any
        // transition (available → downloading → gone) resized it and
        // shifted the other buttons around: they render as full-width
        // banners below the header, see `render_update_banners`.
        let updates = self.tables.iter().filter(|t| t.update_available).count();
        if updates > 0 {
            left.label(
                egui::RichText::new(format!("↑ {updates}"))
                    .size(h_size)
                    .color(p.info),
            );
        }
        let left_end = left.min_rect().right();

        let mut right = ui.new_child(
            egui::UiBuilder::new()
                .max_rect(row_rect)
                .layout(egui::Layout::right_to_left(egui::Align::Center)),
        );
        if right
            .add(header_button(t!("launcher_quit").to_string()))
            .clicked()
        {
            self.quit_launcher(&ctx);
        }
        if right
            .add(header_button(t!("launcher_config").to_string()))
            .clicked()
        {
            // Signal main.rs to relaunch this eframe session in
            // Wizard mode with a fresh viewport (windowed on the
            // primary display), then close this one. Cover
            // viewports go first to keep the Mutter destruction
            // order deterministic — same reason as in
            // `quit_launcher`.
            // Stop any currently-playing table preview audio
            // before the mode switch so the user doesn't hear
            // it linger into the wizard. The audio thread
            // itself stays alive — the wizard needs it for
            // its test sequence.
            if let Some(tx) = &self.audio_cmd_tx {
                let _ = tx.send(AudioCommand::PreviewStop);
                let _ = tx.send(AudioCommand::StopAll);
            }
            self.preview_playing = false;
            self.preview_due_at = None;
            crate::app::request_mode_switch(AppMode::Wizard);
            Self::close_cover_viewports(&ctx);
            ctx.send_viewport_cmd(egui::ViewportCommand::Close);
        }
        let right_start = right.min_rect().left();

        // Search: a magnifier and a field that grows with what is typed (or
        // with the hint while empty), between a minimum and a maximum, and
        // centred on the row unless the side groups push it off-centre.
        let search_font = (h_size - 2.0).max(1.0);
        let hint = t!("launcher_search", count = self.tables.len()).to_string();
        let shown = if self.table_filter.is_empty() {
            hint.clone()
        } else {
            self.table_filter.clone()
        };
        let text_w = ui
            .painter()
            .layout_no_wrap(
                shown,
                egui::FontId::proportional(search_font),
                egui::Color32::WHITE,
            )
            .size()
            .x;
        let gap = h_size;
        let icon_w = h_size * 1.6;
        let room = (right_start - left_end - 2.0 * gap - icon_w).max(0.0);
        let field_w = (text_w + h_size * 2.5)
            .clamp(h_size * 7.0, h_size * 30.0)
            .min(room);
        let total_w = icon_w + field_w;
        let lo = left_end + gap;
        let hi = (right_start - gap - total_w).max(lo);
        let x0 = (row_rect.center().x - total_w / 2.0).clamp(lo, hi);
        let mut center = ui.new_child(
            egui::UiBuilder::new()
                .max_rect(egui::Rect::from_min_size(
                    egui::pos2(x0, row_rect.top()),
                    egui::vec2(total_w, row_h),
                ))
                .layout(egui::Layout::left_to_right(egui::Align::Center)),
        );
        center.label(egui::RichText::new("🔍").size(h_size));
        // Scoped visuals tweak — thicker + lighter bg_stroke so the search
        // frame is visible on glossy / bright pincab playfields. The default
        // inactive stroke is gray(60), which washes out; we force a brighter
        // light-gray + 3px width on all widget states.
        let search_resp = center
            .scope(|ui| {
                let stroke = egui::Stroke::new(3.0, p.text_muted);
                let v = ui.visuals_mut();
                v.widgets.inactive.bg_stroke = stroke;
                v.widgets.hovered.bg_stroke = stroke;
                v.widgets.active.bg_stroke = stroke;
                v.widgets.noninteractive.bg_stroke = stroke;
                v.widgets.open.bg_stroke = stroke;
                ui.add(
                    egui::TextEdit::singleline(&mut self.table_filter)
                        .font(egui::FontId::proportional(search_font))
                        .hint_text(egui::RichText::new(hint).size(search_font))
                        .desired_width(field_w),
                )
            })
            .inner;
        let mut filter_changed = false;
        if search_resp.changed() {
            self.table_filter_lower = self.table_filter.to_lowercase();
            filter_changed = true;
        }

        // Type-anywhere-to-search: when no text field has focus
        // and a printable character is typed, append it to the
        // filter and grab focus on the search bar so the next
        // keystrokes go directly into the field. Skipped while
        // VPX is running (game owns the input) and while a text
        // edit already has focus (avoid double-insertion: the
        // TextEdit will consume the same Event::Text natively).
        if !ui.ctx().text_edit_focused() && !self.vpx_running.load(Ordering::Relaxed) {
            let typed: String = ui.input(|i| {
                i.events
                    .iter()
                    .filter_map(|e| match e {
                        egui::Event::Text(s) => Some(s.as_str()),
                        _ => None,
                    })
                    .collect::<Vec<_>>()
                    .join("")
            });
            let mut appended: String = typed.chars().filter(|c| !c.is_control()).collect();
            // F, + and - are hot keys while the search is empty (favourite,
            // rating): they must not start a search.
            if self.table_filter.is_empty() && launcher_input::is_hotkey_text(&appended) {
                appended.clear();
            }
            if !appended.is_empty() {
                self.table_filter.push_str(&appended);
                self.table_filter_lower = self.table_filter.to_lowercase();
                filter_changed = true;
                // Place the caret at the end of the buffer so
                // subsequent typing appends instead of inserting
                // before the freshly-typed characters.
                let id = search_resp.id;
                let mut state = egui::TextEdit::load_state(ui.ctx(), id).unwrap_or_default();
                let end = self.table_filter.chars().count();
                state
                    .cursor
                    .set_char_range(Some(egui::text::CCursorRange::one(
                        egui::text::CCursor::new(end),
                    )));
                state.store(ui.ctx(), id);
                search_resp.request_focus();
            }
        }

        // When the filter changes, snap the selection to the
        // first match so Enter launches a table that's actually
        // visible in the filtered grid. Skip if the current
        // selection still satisfies the new filter (lets the
        // user refine without losing their place).
        if filter_changed && !self.table_filter_lower.is_empty() {
            let f = self.table_filter_lower.as_str();
            let current_matches = self
                .tables
                .get(self.selected_table)
                .map(|t| t.name.to_lowercase().contains(f))
                .unwrap_or(false);
            if !current_matches
                && let Some(idx) = self
                    .tables
                    .iter()
                    .position(|t| t.name.to_lowercase().contains(f))
            {
                self.selected_table = idx;
                self.scroll_to_selected = true;
            }
        }

        ui.add_space(8.0);

        // Full-width update banners (one per pending update). Rendering
        // below the header keeps the button row stable — the header never
        // shifts when an update appears or completes.
        self.render_update_banners(ui);

        // VPX loading overlay — show spinner/progress but don't return, viewports need to render below
        let vpx_loading =
            self.vpx_running.load(Ordering::Relaxed) && !self.vpx_loading_msg.is_empty();
        if vpx_loading {
            ui.vertical_centered(|ui| {
                ui.add_space(40.0);
                if let Some(pct) = self.vpx_loading_pct {
                    ui.add(
                        egui::ProgressBar::new(pct)
                            .text(&self.vpx_loading_msg)
                            .desired_width(400.0),
                    );
                } else {
                    ui.spinner();
                    ui.add_space(8.0);
                    ui.label(
                        egui::RichText::new(&self.vpx_loading_msg)
                            .size(18.0)
                            .strong(),
                    );
                }
            });
        }

        // VPX error popup. A `Modal`, not a `Window`: it takes an
        // input-grabbing layer above everything else in this viewport, so
        // nothing painted afterwards can end up in front of it.
        if self.vpx_error_log.is_some() {
            let mut close = false;
            // Keyboard first. A cabinet often has no mouse at all, and a
            // report nobody can act on is a report nobody sends.
            let (esc, copy_key, save_key) = ui.ctx().input_mut(|i| {
                (
                    i.consume_key(egui::Modifiers::NONE, egui::Key::Escape),
                    i.consume_key(egui::Modifiers::CTRL, egui::Key::C),
                    i.consume_key(egui::Modifiers::CTRL, egui::Key::S),
                )
            });
            if let Some(log) = self.vpx_error_log.clone() {
                if copy_key {
                    ui.ctx().output_mut(|o| {
                        o.commands.push(egui::OutputCommand::CopyText(log.clone()))
                    });
                    self.vpx_error_copied_at = Some(std::time::Instant::now());
                    self.vpx_error_saved = None;
                }
                if save_key {
                    self.vpx_error_saved = save_error_log(&log);
                }
            }
            close |= esc;
            egui::Modal::new(egui::Id::unique("vpx-error-modal")).show(ui.ctx(), |ui| {
                ui.set_max_width(720.0);
                ui.label(
                    egui::RichText::new(t!("launcher_vpx_crashed").to_string())
                        .size(16.0)
                        .strong()
                        .color(egui::Color32::RED),
                );
                ui.add_space(8.0);
                if let Some(log) = self.vpx_error_log.clone() {
                    // Both scrollbars stay visible: egui's default
                    // `AlwaysHidden` only shows them on hover, easy to miss
                    // on a kiosk screen. Horizontal too — log lines carry
                    // long paths, and wrapping them makes a stack of
                    // aligned entries unreadable.
                    egui::ScrollArea::both()
                        .max_height(300.0)
                        .auto_shrink([false, false])
                        .scroll_bar_visibility(
                            egui::scroll_area::ScrollBarVisibility::AlwaysVisible,
                        )
                        .show(ui, |ui| {
                            let job = highlight_error_keywords(&log, ui.style());
                            ui.add(egui::Label::new(job).wrap_mode(egui::TextWrapMode::Extend));
                        });
                    ui.add_space(8.0);
                    ui.horizontal(|ui| {
                        // Confirmation flash: a clipboard write leaves no
                        // trace on screen, so a working button and a dead one
                        // look exactly alike — which is the doubt a field
                        // report just described.
                        const FLASH: f32 = 0.9;
                        let flashing = self
                            .vpx_error_copied_at
                            .is_some_and(|t| t.elapsed().as_secs_f32() < FLASH);
                        let copy_label = if flashing {
                            format!("✔ {}", t!("launcher_error_copy"))
                        } else {
                            format!("{} (Ctrl+C)", t!("launcher_error_copy"))
                        };
                        let mut copy_btn = egui::Button::new(copy_label);
                        if flashing {
                            copy_btn = copy_btn
                                .fill(theme::pal(ui.ctx()).tint(theme::pal(ui.ctx()).success, 120));
                            // Keep repainting so it fades on its own, even if
                            // nothing else ever moves.
                            ui.ctx().request_repaint();
                        }
                        if ui
                            .add(copy_btn)
                            .on_hover_text(t!("launcher_error_copy_hint").to_string())
                            .clicked()
                        {
                            ui.ctx().output_mut(|o| {
                                o.commands.push(egui::OutputCommand::CopyText(log.clone()))
                            });
                            self.vpx_error_copied_at = Some(std::time::Instant::now());
                            self.vpx_error_saved = None;
                        }
                        if ui
                            .button(format!("{} (Ctrl+S)", t!("launcher_error_save")))
                            .on_hover_text(t!("launcher_error_save_hint").to_string())
                            .clicked()
                        {
                            self.vpx_error_saved = save_error_log(&log);
                        }
                        if ui
                            .button(format!("{} (Esc)", t!("launcher_close")))
                            .clicked()
                        {
                            close = true;
                        }
                    });
                    match &self.vpx_error_saved {
                        Some(Ok(path)) => {
                            ui.label(
                                egui::RichText::new(
                                    t!("launcher_error_saved", path = path.as_str()).to_string(),
                                )
                                .color(theme::pal(ui.ctx()).success),
                            );
                        }
                        Some(Err(e)) => {
                            ui.label(
                                egui::RichText::new(
                                    t!("launcher_error_save_failed", error = e.as_str())
                                        .to_string(),
                                )
                                .color(egui::Color32::LIGHT_RED),
                            );
                        }
                        None => {}
                    }
                } else {
                    ui.add_space(8.0);
                    if ui.button(t!("launcher_close").to_string()).clicked() {
                        close = true;
                    }
                }
            });
            if close {
                self.vpx_error_log = None;
                self.vpx_error_saved = None;
                self.vpx_error_copied_at = None;
            }
        }

        if self.tables.is_empty() {
            ui.label(t!("launcher_no_tables").to_string());
            return;
        }

        // Table grid with backglass images
        let mut launch_idx: Option<usize> = None;
        let mut fav_toggle: Option<usize> = None;
        let mut rate_set: Option<(usize, u8)> = None;
        let card_width = 400.0;
        let card_height = 520.0;
        let img_height = 400.0;
        let card_spacing = 8.0;
        let available_width = ui.available_width();
        let cols = ((available_width / (card_width + card_spacing)) as usize).max(1);
        self.launcher_cols = cols;
        let row_height = card_height + card_spacing;

        // Extra keyboard navigation for long lists.
        // Home/End jump to first/last table. PageUp/PageDown jump by one
        // viewport worth of rows, keeping alignment consistent with joystick nav.
        if !self.vpx_running.load(Ordering::Relaxed) {
            let home = ui.input(|i| i.key_pressed(egui::Key::Home));
            let end = ui.input(|i| i.key_pressed(egui::Key::End));
            let page_up = ui.input(|i| i.key_pressed(egui::Key::PageUp));
            let page_down = ui.input(|i| i.key_pressed(egui::Key::PageDown));

            if home {
                self.selected_table = 0;
                self.scroll_to_selected = true;
            }
            if end {
                self.selected_table = self.tables.len().saturating_sub(1);
                self.scroll_to_selected = true;
            }

            if page_up || page_down {
                let visible_rows = (ui.available_height() / row_height).floor().max(1.0) as usize;
                let page_size = visible_rows.saturating_mul(cols).max(1);
                if page_up {
                    self.selected_table = self.selected_table.saturating_sub(page_size);
                }
                if page_down {
                    self.selected_table = self
                        .selected_table
                        .saturating_add(page_size)
                        .min(self.tables.len().saturating_sub(1));
                }
                self.scroll_to_selected = true;
            }
        }

        // Boost line-based mouse wheel input so stronger wheel flicks scroll farther.
        // Keep trackpad behavior untouched (trackpads usually report point deltas).
        let line_wheel_strength: f32 = ui.input(|i| {
            i.events
                .iter()
                .filter_map(|e| match e {
                    egui::Event::MouseWheel {
                        unit: egui::MouseWheelUnit::Line,
                        delta,
                        ..
                    } => Some(delta.y.abs()),
                    _ => None,
                })
                .sum()
        });
        let wheel_boost = (1.0 + line_wheel_strength * 1.25).clamp(1.0, 8.0);

        let mut scroll_area = egui::ScrollArea::vertical()
            .scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysVisible)
            .wheel_scroll_multiplier(egui::vec2(1.0, wheel_boost));

        // Compute the filtered grid once — both the scroll-target
        // calculation and the rendering closure need it. Without this,
        // `selected_row = self.selected_table / cols` would index into
        // the unfiltered grid and scroll to the wrong y-offset when a
        // search is active.
        // `visible_indices` also applies the sort order, so the cards follow
        // the sort button and the joystick navigation sees the same order.
        let filtered: Vec<usize> = self.visible_indices();

        // Auto-scroll to selected table when navigating with joystick.
        // Keep the selected row centered in the viewport; clamp at start/end
        // so we don't scroll past the content. Skip the scroll reset when the
        // computed target_y hasn't changed (horizontal flipper inside a row,
        // or row change that clamps to the same max_top on the last rows) —
        // repeatedly calling vertical_scroll_offset with the same value
        // causes visible reflow.
        if self.scroll_to_selected {
            self.scroll_to_selected = false;
            let selected_pos = filtered
                .iter()
                .position(|&i| i == self.selected_table)
                .unwrap_or(0);
            let selected_row = selected_pos / cols;
            let total_rows = filtered.len().div_ceil(cols);
            let visible_rows = (ui.available_height() / row_height).floor() as usize;
            let half = visible_rows / 2;
            let top_row = selected_row
                .saturating_sub(half)
                .min(total_rows.saturating_sub(visible_rows));
            let target_y = top_row as f32 * row_height;
            if self.last_scroll_target != Some(target_y) {
                self.last_scroll_target = Some(target_y);
                scroll_area = scroll_area.vertical_scroll_offset(target_y);
            }
        }

        // Positions (in `filtered`) of the cards drawn on screen this frame.
        let mut visible_pos: Vec<usize> = Vec::new();
        scroll_area.show(ui, |ui| {
            for row_start in (0..filtered.len()).step_by(cols) {
                // Center the row
                let row_count = (filtered.len() - row_start).min(cols);
                let row_width = row_count as f32 * (card_width + 8.0) - 8.0;
                let left_pad = ((available_width - row_width) / 2.0).max(0.0);

                ui.horizontal(|ui| {
                    ui.add_space(left_pad);
                    for col in 0..cols {
                        let fi = row_start + col;
                        if fi >= filtered.len() {
                            break;
                        }
                        let idx = filtered[fi];
                        let table = &self.tables[idx];

                        let (rect, response) = ui.allocate_exact_size(
                            egui::vec2(card_width, card_height),
                            egui::Sense::click(),
                        );
                        if ui.is_rect_visible(rect) {
                            visible_pos.push(fi);
                        }

                        // Only let hover drive selection when the cursor is actively
                        // moving. If the user presses a flipper/magna (no mouse motion),
                        // joystick/keyboard navigation wins and the stale hover doesn't
                        // snap selected_table back under the cursor.
                        let mouse_moved_recently = ui
                            .ctx()
                            .input(|i| i.pointer.time_since_last_movement() < 0.3);
                        if response.hovered() && mouse_moved_recently {
                            self.selected_table = idx;
                        }
                        if response.clicked() {
                            launch_idx = Some(idx);
                        }

                        let painter = ui.painter_at(rect);
                        let is_selected = idx == self.selected_table;

                        // Card background: the selected table glows in the
                        // DMD's orange, as if its playfield lights came on.
                        let p = theme::pal(ui.ctx());
                        let bg_color = if is_selected {
                            p.tint(p.accent, 48)
                        } else if response.hovered() {
                            p.raised
                        } else {
                            p.surface
                        };
                        painter.rect_filled(rect, 8.0, bg_color);

                        // Selection border (inside to avoid clipping by painter_at)
                        if is_selected {
                            painter.rect_stroke(
                                rect,
                                8.0,
                                egui::Stroke::new(4.0, p.accent),
                                egui::StrokeKind::Inside,
                            );
                        } else {
                            painter.rect_stroke(
                                rect,
                                8.0,
                                egui::Stroke::new(1.0, p.border),
                                egui::StrokeKind::Inside,
                            );
                        }

                        // Backglass image (centered in image area)
                        let img_area = egui::Rect::from_min_size(
                            rect.min + egui::vec2(4.0, 4.0),
                            egui::vec2(card_width - 8.0, img_height - 8.0),
                        );
                        if table.has_bg {
                            // The thumbnail made for the grid, in the GPU
                            // for every table (see `bgcache`); a plain tile
                            // while it is still on its way.
                            if let Some(tex) = self.bg_cache.thumb(idx) {
                                egui::Image::from_texture(egui::load::SizedTexture::new(
                                    tex.id(),
                                    tex.size_vec2(),
                                ))
                                .shrink_to_fit()
                                .corner_radius(egui::CornerRadius::same(4))
                                .paint_at(ui, img_area);
                            } else {
                                painter.rect_filled(img_area, 4.0, p.bg);
                            }
                        } else {
                            // Localized "missing image" placeholder. Tells the user
                            // exactly which two filenames they can drop in to fix
                            // it. Rendered live rather than pre-generated so the
                            // hint re-localizes when the user switches language.
                            painter.rect_filled(img_area, 4.0, p.bg);
                            let cx = img_area.center().x;
                            let h = img_area.height();
                            painter.text(
                                egui::pos2(cx, img_area.min.y + h * 0.30),
                                egui::Align2::CENTER_CENTER,
                                t!("launcher_missing_title", table = table.name.clone()),
                                egui::FontId::proportional(18.0),
                                p.text_muted,
                            );
                            painter.text(
                                egui::pos2(cx, img_area.min.y + h * 0.52),
                                egui::Align2::CENTER_CENTER,
                                t!("launcher_missing_hint_launcher"),
                                egui::FontId::proportional(14.0),
                                p.text_faint,
                            );
                            painter.text(
                                egui::pos2(cx, img_area.min.y + h * 0.68),
                                egui::Align2::CENTER_CENTER,
                                t!("launcher_missing_hint_b2s"),
                                egui::FontId::proportional(14.0),
                                p.text_faint,
                            );
                        }

                        // Table name (centered, bigger, bold)
                        let text_center = egui::pos2(
                            rect.center().x,
                            rect.min.y + img_height + (card_height - img_height) / 2.0,
                        );
                        painter.text(
                            text_center,
                            egui::Align2::CENTER_CENTER,
                            &table.name,
                            egui::FontId::new(24.0, egui::FontFamily::Proportional),
                            if is_selected { p.accent_text } else { p.text },
                        );

                        // Favourite star (right, big and bright when set) and
                        // rating (bottom-left, five stars with the empty ones in
                        // black so the scale is visible; a fraction of a star is
                        // a fraction of its surface: 3.2 stars). Painted shapes
                        // (no font needed), both clickable and allocated after
                        // the card so a click on them is not a click on the
                        // card (which launches the table).
                        let fav_center = egui::pos2(img_area.max.x - 30.0, img_area.max.y - 34.0);
                        let fav_resp = ui.interact(
                            egui::Rect::from_center_size(fav_center, egui::vec2(52.0, 52.0)),
                            ui.scope_id().with(("favorite", idx)),
                            egui::Sense::click(),
                        );
                        if table.user.favorite {
                            // A glow, then a big bright star with a pale heart.
                            painter.circle_filled(fav_center, 30.0, STAR_GOLD.gamma_multiply(0.22));
                            painter.circle_filled(fav_center, 24.0, STAR_GOLD.gamma_multiply(0.38));
                            paint_star(&painter, fav_center, 21.0, STAR_BRIGHT);
                            paint_star(
                                &painter,
                                fav_center,
                                9.0,
                                egui::Color32::from_rgb(255, 248, 200),
                            );
                        } else if is_selected || fav_resp.hovered() {
                            painter.circle_filled(
                                fav_center,
                                17.0,
                                egui::Color32::from_black_alpha(160),
                            );
                            let color = if fav_resp.hovered() {
                                STAR_GOLD.gamma_multiply(0.8)
                            } else {
                                egui::Color32::from_gray(110)
                            };
                            paint_star(&painter, fav_center, 13.0, color);
                        }
                        if fav_resp.hovered() {
                            ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
                        }
                        if fav_resp.clicked() {
                            fav_toggle = Some(idx);
                        }
                        // The community rating (VPinPlay), when there is one.
                        let community = table
                            .vps_id
                            .as_ref()
                            .and_then(|id| self.community.get(id))
                            .map(|r| r.avg);
                        if table.user.rating_tenths > 0 || is_selected || community.is_some() {
                            const STEP: f32 = 22.0;
                            let row = egui::Rect::from_min_size(
                                egui::pos2(img_area.min.x + 6.0, img_area.max.y - 32.0),
                                egui::vec2(10.0 + 5.0 * STEP, 26.0),
                            );
                            painter.rect_filled(row, 13.0, egui::Color32::from_black_alpha(190));
                            // Gold: the player's own rating. Blue: the community's,
                            // shown while the player has not rated the table.
                            let (rating, fill) = if table.user.rating_tenths > 0 {
                                (table.user.rating_tenths as f32 / 10.0, STAR_GOLD)
                            } else if let Some(avg) = community {
                                (avg, STAR_COMMUNITY)
                            } else {
                                (0.0, STAR_GOLD)
                            };
                            for k in 0..5 {
                                let c = egui::pos2(
                                    row.min.x + 5.0 + STEP / 2.0 + k as f32 * STEP,
                                    row.center().y,
                                );
                                paint_rating_star(
                                    &painter,
                                    c,
                                    9.5,
                                    (rating - k as f32).clamp(0.0, 1.0),
                                    fill,
                                );
                            }
                            let rating_resp = ui.interact(
                                row,
                                ui.scope_id().with(("rating", idx)),
                                egui::Sense::click(),
                            );
                            if rating_resp.hovered() {
                                ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
                            }
                            if rating_resp.clicked()
                                && let Some(pos) = rating_resp.interact_pointer_pos()
                            {
                                // Where in the row was the click: 0 to 5 stars, to a
                                // tenth. Clicking the current value clears it.
                                let stars = (pos.x - (row.min.x + 5.0)) / STEP;
                                let tenths = (stars * 10.0).round().clamp(0.0, 50.0) as u8;
                                let new = if tenths == table.user.rating_tenths {
                                    0
                                } else {
                                    tenths
                                };
                                rate_set = Some((idx, new));
                            }
                        }

                        // Community rating from VPinPlay (top-left): a small
                        // star and the average, when the table has one.
                        if let Some(rating) =
                            table.vps_id.as_ref().and_then(|id| self.community.get(id))
                        {
                            let text = format!("{:.1}", rating.avg);
                            let pill = egui::Rect::from_min_size(
                                egui::pos2(img_area.min.x + 6.0, img_area.min.y + 6.0),
                                egui::vec2(58.0, 24.0),
                            );
                            painter.rect_filled(pill, 12.0, egui::Color32::from_black_alpha(190));
                            paint_star(
                                &painter,
                                egui::pos2(pill.min.x + 14.0, pill.center().y),
                                8.5,
                                STAR_COMMUNITY,
                            );
                            painter.text(
                                egui::pos2(pill.min.x + 26.0, pill.center().y),
                                egui::Align2::LEFT_CENTER,
                                text,
                                egui::FontId::new(15.0, egui::FontFamily::Proportional),
                                egui::Color32::WHITE,
                            );
                        }

                        // Update-available badge: small "↑" disk in the
                        // top-right corner of the image area. Set by the
                        // catalog worker when the live VPSDB Game.updated_at
                        // has moved past the value recorded at link time.
                        // Click → open the VPS catalog page for this game
                        // in the user's browser; allocated AFTER the card
                        // so egui's hit-testing routes the click here
                        // instead of triggering the card's launch handler.
                        if table.update_available {
                            let badge_radius = 14.0;
                            let badge_center = egui::pos2(
                                img_area.max.x - badge_radius - 4.0,
                                img_area.min.y + badge_radius + 4.0,
                            );
                            let badge_rect = egui::Rect::from_center_size(
                                badge_center,
                                egui::vec2(badge_radius * 2.0, badge_radius * 2.0),
                            );
                            let badge_resp = ui.interact(
                                badge_rect,
                                ui.scope_id().with(("update_badge", idx)),
                                egui::Sense::click(),
                            );
                            let bg_color = if badge_resp.hovered() {
                                p.tint(p.info, 200)
                            } else {
                                p.info
                            };
                            painter.circle_filled(badge_center, badge_radius, bg_color);
                            painter.circle_stroke(
                                badge_center,
                                badge_radius,
                                egui::Stroke::new(1.5, egui::Color32::from_rgb(20, 80, 140)),
                            );
                            painter.text(
                                badge_center,
                                egui::Align2::CENTER_CENTER,
                                "↑",
                                egui::FontId::new(20.0, egui::FontFamily::Proportional),
                                egui::Color32::WHITE,
                            );
                            if badge_resp.hovered() {
                                ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
                            }
                            // Tooltip on hover — replaces the previous
                            // bare circle with a friendly hint that
                            // explains what clicking does. The egui
                            // tooltip uses the response's hover state
                            // and renders a small floating panel near
                            // the cursor.
                            let badge_resp =
                                badge_resp.on_hover_text(t!("launcher_update_badge_tooltip"));
                            if badge_resp.clicked()
                                && let Some(ref vid) = table.vps_id
                            {
                                let url = format!(
                                    "https://virtualpinballspreadsheet.github.io/games?game={vid}"
                                );
                                log::info!("Opening VPS page: {url}");
                                ui.ctx().open_url(egui::OpenUrl::new_tab(url));
                            }
                        }
                    }
                });
                ui.add_space(4.0);
            }
        });

        // Which pictures to hold: the page on screen (plus the selection, if
        // it was jumped to) in the GPU at full size, the page before and the
        // page after in RAM.
        {
            let on_screen: Vec<usize> = {
                let mut v: Vec<usize> = visible_pos.iter().map(|&fi| filtered[fi]).collect();
                if let Some(sel) = self
                    .tables
                    .get(self.selected_table)
                    .map(|_| self.selected_table)
                    && !v.contains(&sel)
                {
                    v.push(sel);
                }
                v
            };
            let mut near: Vec<usize> = Vec::new();
            if let (Some(&first), Some(&last)) = (visible_pos.first(), visible_pos.last()) {
                let page = last - first + 1;
                near.extend(filtered[first.saturating_sub(page)..first].iter().copied());
                near.extend(
                    filtered[(last + 1).min(filtered.len())..(last + 1 + page).min(filtered.len())]
                        .iter()
                        .copied(),
                );
            }
            let tables_dir = self.tables_dir.clone();
            let paths: Vec<std::path::PathBuf> =
                self.tables.iter().map(|t| t.path.clone()).collect();
            let rel = move |idx: usize| -> Option<String> {
                paths
                    .get(idx)?
                    .strip_prefix(&tables_dir)
                    .ok()
                    .map(|p| p.to_string_lossy().into_owned())
            };
            self.bg_cache.update(ui.ctx(), &on_screen, &near, &rel);
        }

        if let Some(idx) = fav_toggle {
            self.selected_table = idx;
            self.toggle_favorite_selected();
            self.scroll_to_selected = false;
        }
        if let Some((idx, rating)) = rate_set {
            self.selected_table = idx;
            self.rate_selected(rating);
            self.scroll_to_selected = false;
        }
        if let Some(idx) = launch_idx {
            self.selected_table = idx;
            let path = self.tables[idx].path.clone();
            let ctx = ui.ctx().clone();
            self.begin_table_launch(path, &ctx);
        }

        // Covers stay down while the crash report is up. They are documented
        // right below as taking the pointer focus when the cursor grazes their
        // screen — which strands the arrow on the backglass. Bringing them back
        // at the exact moment the user has to click Copy or Save is how a
        // report ends up unreachable, which is what a field report described.
        if !self.vpx_hide_covers && self.vpx_error_log.is_none() {
            self.render_cover_viewports(ui);
        }
    }

    /// Backglass image on BG, VPX logo cover on DMD and Topper.
    /// Uses `with_monitor(idx)` to place each viewport — same mechanism as the
    /// main PF viewport. Monitor index = position in `self.displays`.
    /// Report, once per focus change, whether a cover viewport is the one
    /// holding the keyboard focus. Only a viewport can tell for itself, so
    /// the answer has to come from inside its own render closure.
    fn diag_cover_focus(ctx: &egui::Context, name: &str) {
        if std::env::var("PINREADY_CURSOR_DIAG").is_err() {
            return;
        }
        let focused = ctx.input(|i| i.viewport().focused).unwrap_or(false);
        let id = egui::Id::unique(("cover_focus_diag", name));
        let previous = ctx.data(|d| d.get_temp::<bool>(id));
        if previous != Some(focused) {
            ctx.data_mut(|d| d.insert_temp(id, focused));
            log::info!("cover {name}: focused={focused}");
        }
    }

    /// Log, once per change, what the backglass cover is painting. Written
    /// from inside the cover's own pass: when the screen stays blank or stuck
    /// while these lines follow the selection, the cover is being drawn and
    /// the picture is lost on its way to the screen; when they stop, the
    /// cover itself is no longer being run.
    fn log_backglass_cover(ctx: &egui::Context, uri: &str, table: &str, has_image: bool) {
        let id = egui::Id::unique("backglass_cover_painted");
        let current = (uri.to_owned(), has_image);
        let previous = ctx.data(|d| d.get_temp::<(String, bool)>(id));
        if previous.as_ref() != Some(&current) {
            log::info!(
                "Backglass cover: painting {table} ({})",
                if has_image {
                    uri
                } else {
                    "no image yet, showing its name"
                }
            );
            ctx.data_mut(|d| d.insert_temp(id, current));
        }
    }

    /// Body of the backglass cover: the selected table's picture, or its name
    /// while the picture is not there yet.
    fn paint_backglass_cover(
        ui: &mut egui::Ui,
        uri: &str,
        table_name: &str,
        bg: Option<&egui::TextureHandle>,
    ) {
        let ctx = ui.ctx().clone();
        Self::diag_cover_focus(&ctx, "backglass");
        Self::log_backglass_cover(&ctx, uri, table_name, bg.is_some());
        egui::CentralPanel::default()
            .frame(egui::Frame::NONE.fill(egui::Color32::BLACK))
            .show(ui, |ui| {
                if let Some(tex) = bg {
                    ui.centered_and_justified(|ui| {
                        ui.add(
                            egui::Image::from_texture(egui::load::SizedTexture::new(
                                tex.id(),
                                tex.size_vec2(),
                            ))
                            .shrink_to_fit(),
                        );
                    });
                } else {
                    ui.centered_and_justified(|ui| {
                        ui.colored_label(
                            egui::Color32::WHITE,
                            egui::RichText::new(table_name).size(32.0),
                        );
                    });
                }
            });
    }

    fn render_cover_viewports(&self, ui: &mut egui::Ui) {
        // Diagnostic escape hatch: the playfield never gets focus in cabinet
        // mode, and the covers are the prime suspect — they map after it, and
        // Mutter is known to ignore their `with_active(false)` (which is why
        // egui-keyfunnel exists at all). Running without them says whether
        // they are the ones holding the focus.
        if std::env::var("PINREADY_NO_COVERS").is_ok() {
            return;
        }

        // Backglass image
        if let Some(bg_idx) = self
            .displays
            .iter()
            .find(|d| d.role == DisplayRole::Backglass)
            .map(|d| d.monitor_index)
            && !self.tables.is_empty()
        {
            let selected = self.selected_table.min(self.tables.len() - 1);
            let table_name = self.tables[selected].name.clone();
            // The full picture if the page's pictures are in the GPU, else
            // its thumbnail, else nothing yet (the cover shows the name).
            let bg_tex = self.bg_cache.best(selected);
            let uri = format!("table {}/{selected}", self.scan_generation);

            let bg_viewport_id = egui::ViewportId::from_hash_of(BG_VIEWPORT);
            let builder = egui::ViewportBuilder::default()
                .with_title("PinReady — Backglass")
                .with_decorations(false)
                .with_monitor(bg_idx)
                .with_active(false)
                // A cover is a picture, never a target. Left
                // clickable, Mutter hands it the pointer focus when
                // the cursor grazes the backglass screen, which drops
                // the playfield's pointer constraint: the arrow
                // escapes onto the backglass and freezes there,
                // because the moves it needs are now being delivered
                // to this window.
                .with_mouse_passthrough(COVER_MOUSE_PASSTHROUGH);
            if BACKGLASS_COVER_IMMEDIATE {
                ui.ctx()
                    .show_viewport_immediate(bg_viewport_id, builder, move |ui, _class| {
                        Self::paint_backglass_cover(ui, &uri, &table_name, bg_tex.as_ref());
                    });
            } else {
                ui.ctx().request_repaint_of(bg_viewport_id);
                ui.ctx()
                    .show_viewport_deferred(bg_viewport_id, builder, move |ui, _class| {
                        Self::paint_backglass_cover(ui, &uri, &table_name, bg_tex.as_ref());
                    });
            }
        }

        // DMD cover
        if let Some(dmd_idx) = self
            .displays
            .iter()
            .find(|d| d.role == DisplayRole::Dmd)
            .map(|d| d.monitor_index)
        {
            Self::show_logo_viewport(ui, DMD_VIEWPORT, "PinReady — DMD", dmd_idx);
        }

        // Topper cover
        if let Some(tp_idx) = self
            .displays
            .iter()
            .find(|d| d.role == DisplayRole::Topper)
            .map(|d| d.monitor_index)
        {
            Self::show_logo_viewport(ui, TOPPER_VIEWPORT, "PinReady — Topper", tp_idx);
        }
    }

    /// Show a viewport with the VPX logo on a grey background, placed
    /// borderless fullscreen on the given monitor index.
    fn show_logo_viewport(ui: &mut egui::Ui, id: &'static str, title: &str, monitor_idx: usize) {
        let viewport_id = egui::ViewportId::from_hash_of(id);
        ui.ctx().show_viewport_deferred(
            viewport_id,
            egui::ViewportBuilder::default()
                .with_title(title)
                .with_decorations(false)
                .with_monitor(monitor_idx)
                .with_active(false)
                // See the backglass cover: covers must not attract the pointer.
                .with_mouse_passthrough(COVER_MOUSE_PASSTHROUGH),
            move |ui, _class| {
                let ctx = ui.ctx().clone();
                Self::diag_cover_focus(&ctx, id);
                egui_extras::install_image_loaders(&ctx);
                ctx.include_bytes("bytes://vpx_logo", VPX_LOGO);
                egui::CentralPanel::default()
                    .frame(egui::Frame::NONE.fill(egui::Color32::from_rgb(80, 80, 85)))
                    .show(ui, |ui| {
                        ui.centered_and_justified(|ui| {
                            let img = egui::Image::new("bytes://vpx_logo")
                                .max_size(egui::vec2(512.0, 512.0))
                                .tint(egui::Color32::from_rgba_premultiplied(180, 180, 190, 200));
                            ui.add(img);
                        });
                    });
            },
        );
    }

    /// Render one full-width banner per pending update (VPX + PinReady).
    /// Each banner shows either a clickable "available" button, a live
    /// progress bar during download, or an error label. Text is centered
    /// (ProgressBar centers by default; the button spans full width via
    /// `add_sized`). Rendering here — below the header, not inside it —
    /// keeps the button row height stable across state transitions.
    fn render_update_banners(&mut self, ui: &mut egui::Ui) {
        let has_vpx = self.update_downloading
            || self.vpx_latest_release.is_some()
            || self.update_error.is_some();
        let has_pinready = self.pinready_updating
            || self.pinready_latest_release.is_some()
            || self.pinready_update_error.is_some();
        // Head tracking decides for itself further down — it has to poll its
        // worker and its version check first, and both can turn the bar on.
        let has_ht = self.ht_banner_wanted();
        if !has_vpx && !has_pinready && !has_ht {
            return;
        }

        // Same 2%-of-height sizing rule as the header — banners keep
        // parity with the buttons above them across desktop/4K PF.
        let text_size = (ui.available_height() * 0.02).ceil().max(12.0);
        let bar_h = (text_size * 1.8).ceil();
        let full_w = ui.available_width();

        let render_error = |ui: &mut egui::Ui, msg: String| {
            ui.add_sized(
                [full_w, bar_h],
                egui::Label::new(
                    egui::RichText::new(msg)
                        .size(text_size)
                        .color(theme::pal(ui.ctx()).error),
                ),
            );
        };

        if has_vpx {
            if self.update_downloading {
                let (current, total) = self.update_progress;
                let (progress, txt) = if total > 0 {
                    let pct = (current as f32 / total as f32 * 100.0) as u32;
                    let mb = current / (1024 * 1024);
                    let total_mb = total / (1024 * 1024);
                    (
                        current as f32 / total as f32,
                        t!("update_progress", mb = mb, total = total_mb, pct = pct).to_string(),
                    )
                } else {
                    (0.0, t!("update_extracting").to_string())
                };
                ui.add(
                    egui::ProgressBar::new(progress)
                        .desired_width(full_w)
                        .desired_height(bar_h)
                        .text(egui::RichText::new(txt).size(text_size).strong()),
                );
            } else if let Some(release) = self.vpx_latest_release.clone() {
                let label = t!("update_button", tag = release.tag.as_str()).to_string();
                let btn = ui.add_sized(
                    [full_w, bar_h],
                    egui::Button::new(
                        egui::RichText::new(label)
                            .size(text_size)
                            .strong()
                            .color(theme::pal(ui.ctx()).success),
                    ),
                );
                if btn.clicked() {
                    self.start_vpx_download(&release);
                }
            }
            if let Some(err) = self.update_error.clone() {
                render_error(ui, t!("update_error", msg = err.as_str()).to_string());
            }
        }

        if has_vpx && has_pinready {
            ui.add_space(4.0);
        }

        if has_pinready {
            if self.pinready_updating {
                let (current, total) = self.pinready_update_progress;
                let (progress, txt) = if total > 0 {
                    let pct = (current as f32 / total as f32 * 100.0) as u32;
                    let mb = current / (1024 * 1024);
                    let total_mb = total / (1024 * 1024);
                    (
                        current as f32 / total as f32,
                        t!(
                            "pinready_update_progress",
                            mb = mb,
                            total = total_mb,
                            pct = pct
                        )
                        .to_string(),
                    )
                } else {
                    (0.0, t!("pinready_update_extracting").to_string())
                };
                ui.add(
                    egui::ProgressBar::new(progress)
                        .desired_width(full_w)
                        .desired_height(bar_h)
                        .text(egui::RichText::new(txt).size(text_size).strong()),
                );
            } else if let Some(release) = self.pinready_latest_release.clone() {
                let label = t!("pinready_update_button", tag = release.tag.as_str()).to_string();
                let btn = ui.add_sized(
                    [full_w, bar_h],
                    egui::Button::new(
                        egui::RichText::new(label)
                            .size(text_size)
                            .strong()
                            .color(theme::pal(ui.ctx()).info),
                    ),
                );
                if btn.clicked() {
                    self.start_pinready_download(&release);
                }
            }
            if let Some(err) = self.pinready_update_error.clone() {
                render_error(
                    ui,
                    t!("pinready_update_error", msg = err.as_str()).to_string(),
                );
            }
        }

        if has_ht {
            if has_vpx || has_pinready {
                ui.add_space(4.0);
            }
            self.render_ht_banner(ui, text_size, bar_h, full_w);
        }

        ui.add_space(4.0);
    }

    /// Is there anything to say about head tracking right now?
    ///
    /// Only for someone who actually runs it: the plugin has to be installed
    /// **and** enabled. Offering an update for something you don't use is
    /// noise, and the launcher bar is prime real estate on a cabinet.
    ///
    /// Also where the version check is kicked off — lazily, once, and only
    /// under those same conditions, so a desktop user without the plugin never
    /// makes the network call.
    fn ht_banner_wanted(&mut self) -> bool {
        use crate::headtracking_install as ht;
        if ht::platform_asset_suffix().is_none() {
            return false;
        }
        let install_dir = std::path::PathBuf::from(&self.vpx_install_dir);
        let installed = self
            .ht_installed_version
            .get_or_insert_with(|| ht::installed_version(&install_dir))
            .clone();
        if installed.is_none() {
            return false;
        }
        // Absent key = on, matching what the wizard defaults a freshly
        // installed plugin to.
        if self.config.get_i32("Plugin.HeadTracking", "Enable") == Some(0) {
            return false;
        }

        // Drain the installer worker.
        let mut finished = false;
        if let Some(rx) = &self.ht_install_rx {
            while let Ok(ev) = rx.try_recv() {
                match ev {
                    ht::HtEvent::Status(key) => self.ht_status_key = Some(key),
                    ht::HtEvent::Done { tag } => {
                        self.ht_done_tag = Some(tag);
                        self.ht_installed_version = None; // re-read from disk
                        self.ht_latest_version = None;
                        finished = true;
                    }
                    ht::HtEvent::Error(msg) => {
                        self.ht_error = Some(msg);
                        finished = true;
                    }
                }
            }
        }
        if finished {
            self.ht_install_rx = None;
            self.ht_status_key = None;
        }

        // Ask GitHub once what the button would install.
        if self.ht_latest_rx.is_none() && self.ht_latest_version.is_none() {
            self.ht_latest_rx = Some(ht::spawn_latest_version());
        }
        if let Some(rx) = &self.ht_latest_rx
            && let Ok(version) = rx.try_recv()
        {
            self.ht_latest_version = Some(version);
            self.ht_latest_rx = None;
        }

        let update_available = match (&installed, &self.ht_latest_version) {
            (Some(from), Some(Some(to))) => from != to,
            _ => false,
        };
        update_available
            || self.ht_install_rx.is_some()
            || self.ht_done_tag.is_some()
            || self.ht_error.is_some()
    }

    /// The head-tracking bar itself. No byte progress here: the installer
    /// reports named steps, not a download size, so the running state is a
    /// label rather than a progress bar that would have to lie.
    fn render_ht_banner(&mut self, ui: &mut egui::Ui, text_size: f32, bar_h: f32, full_w: f32) {
        use crate::headtracking_install as ht;
        if self.ht_install_rx.is_some() {
            let txt = self.ht_status_key.map_or_else(
                || t!("ht_status_installing").to_string(),
                |k| t!(k).to_string(),
            );
            ui.add_sized(
                [full_w, bar_h],
                egui::Label::new(egui::RichText::new(txt).size(text_size).strong()),
            );
            ui.ctx()
                .request_repaint_after(std::time::Duration::from_millis(300));
        } else {
            let installed = self.ht_installed_version.clone().flatten();
            let latest = self.ht_latest_version.clone().flatten();
            if let (Some(from), Some(to)) = (installed, latest)
                && from != to
            {
                let label = t!(
                    "ht_update_button_to",
                    from = from.as_str(),
                    to = to.as_str()
                )
                .to_string();
                let btn = ui.add_sized(
                    [full_w, bar_h],
                    egui::Button::new(
                        egui::RichText::new(label)
                            .size(text_size)
                            .strong()
                            .color(theme::pal(ui.ctx()).warning),
                    ),
                );
                if btn.clicked() {
                    self.ht_error = None;
                    self.ht_done_tag = None;
                    let dir = std::path::PathBuf::from(&self.vpx_install_dir);
                    self.ht_install_rx = Some(ht::spawn_install(dir));
                }
            }
        }
        if let Some(tag) = self.ht_done_tag.clone() {
            ui.add_sized(
                [full_w, bar_h],
                egui::Label::new(
                    egui::RichText::new(t!("ht_banner_done", tag = tag.as_str()).to_string())
                        .size(text_size)
                        .color(theme::pal(ui.ctx()).success),
                ),
            );
        }
        if let Some(err) = self.ht_error.clone() {
            ui.add_sized(
                [full_w, bar_h],
                egui::Label::new(
                    egui::RichText::new(format!("⚠ {err}"))
                        .size(text_size)
                        .color(theme::pal(ui.ctx()).error),
                ),
            );
        }
    }
}

/// Build a `LayoutJob` from a multi-line log, painting common
/// crash/error vocabulary in red so the user can spot the meaningful
/// lines at a glance. Case-insensitive matching, longest-keyword-wins
/// to avoid double-coloring "segmentation" then "fault" separately.
fn highlight_error_keywords(text: &str, style: &egui::Style) -> egui::text::LayoutJob {
    use egui::text::{LayoutJob, TextFormat};
    // Sorted longest-first so e.g. "segmentation fault" wins over "fault".
    const KEYWORDS: &[&str] = &[
        "segmentation fault",
        "stack overflow",
        "buffer overrun",
        "heap corruption",
        "core dumped",
        "core dump",
        "access violation",
        "killed by",
        "panicked",
        "panic",
        "exception",
        "assertion",
        "assert",
        "segfault",
        "coredump",
        "aborted",
        "abort",
        "crashed",
        "crash",
        "failed",
        "failure",
        "fatal",
        "errors",
        "errored",
        "error",
        "warning",
        "warn",
    ];
    let font = egui::FontId::monospace(style.text_styles[&egui::TextStyle::Monospace].size);
    let normal = TextFormat {
        font_id: font.clone(),
        color: style.visuals.text_color(),
        ..Default::default()
    };
    let highlight = TextFormat {
        font_id: font,
        color: egui::Color32::from_rgb(255, 110, 110),
        ..Default::default()
    };

    let mut job = LayoutJob::default();
    let lower = text.to_ascii_lowercase();
    let bytes = text.as_bytes();
    let mut i = 0;
    // Compare in byte-space: all keywords are pure ASCII so byte-level
    // `eq_ignore_ascii_case` is correct, and unlike `&str[i..j]` slicing
    // it does NOT panic when `j` falls inside a multibyte UTF-8 char
    // (the `·` separators in the system header are 2-byte chars and
    // triggered exactly that panic on non-ASCII content). We only
    // re-enter `&str` when we know both ends are valid char boundaries —
    // in `job.append(&text[start..end], …)`, where `start`/`end` are
    // either 0, `text.len()`, a position we walked to via
    // `chars().next().len_utf8()`, or `i + kw.len()` (kw is ASCII =
    // ends on a char boundary because we scan from a char boundary).
    let lower_bytes = lower.as_bytes();
    while i < text.len() {
        // Try to match a keyword at this byte offset.
        let mut matched: Option<usize> = None;
        for kw in KEYWORDS {
            let kw_bytes = kw.as_bytes();
            let end = i + kw_bytes.len();
            if end <= lower_bytes.len() && lower_bytes[i..end].eq_ignore_ascii_case(kw_bytes) {
                // Word-ish boundary: don't highlight inside another word
                // (so "panicked" doesn't paint on "panickedness", and
                // "warn" stops short of "warning" handling above since
                // we sort longest-first).
                let before_ok = i == 0 || !is_word_char(bytes[i - 1]);
                let after_ok = end == bytes.len() || !is_word_char(bytes[end]);
                if before_ok && after_ok {
                    matched = Some(kw_bytes.len());
                    break;
                }
            }
        }
        if let Some(len) = matched {
            job.append(&text[i..i + len], 0.0, highlight.clone());
            i += len;
        } else {
            // Walk forward one char (UTF-8 safe) into the normal segment,
            // batched until we hit the next keyword start.
            let start = i;
            let next_char_len = text[i..].chars().next().map(|c| c.len_utf8()).unwrap_or(1);
            i += next_char_len;
            // Greedy fast-path: extend as long as no keyword starts here.
            'extend: while i < text.len() {
                for kw in KEYWORDS {
                    let kw_bytes = kw.as_bytes();
                    let end = i + kw_bytes.len();
                    if end <= lower_bytes.len()
                        && lower_bytes[i..end].eq_ignore_ascii_case(kw_bytes)
                    {
                        let before_ok = !is_word_char(bytes[i - 1]);
                        let after_ok = end == bytes.len() || !is_word_char(bytes[end]);
                        if before_ok && after_ok {
                            break 'extend;
                        }
                    }
                }
                let step = text[i..].chars().next().map(|c| c.len_utf8()).unwrap_or(1);
                i += step;
            }
            job.append(&text[start..i], 0.0, normal.clone());
        }
    }
    job
}

fn is_word_char(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b == b'_'
}

/// Write the error report where the user chooses. Returns the path written, or
/// why it could not be — never a silent success: on a cabinet the file has to
/// be findable again, and "it saved somewhere" is not findable.
///
/// `None` when the picker is cancelled, which is a normal answer and leaves the
/// previous feedback line alone.
fn save_error_log(log: &str) -> Option<Result<String, String>> {
    let stamp = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or_default();
    let path = rfd::FileDialog::new()
        .set_title(t!("launcher_error_save").to_string())
        .set_file_name(format!("pinready-vpx-error-{stamp}.log"))
        .save_file()?;
    Some(match std::fs::write(&path, log) {
        Ok(()) => {
            log::info!("VPX error report saved to {}", path.display());
            Ok(path.display().to_string())
        }
        Err(e) => {
            log::warn!(
                "could not save the VPX error report to {}: {e}",
                path.display()
            );
            Err(e.to_string())
        }
    })
}

const STAR_GOLD: egui::Color32 = egui::Color32::from_rgb(255, 200, 40);
const STAR_BRIGHT: egui::Color32 = egui::Color32::from_rgb(255, 222, 70);
/// The community's rating, to tell it from the player's own (gold).
const STAR_COMMUNITY: egui::Color32 = egui::Color32::from_rgb(90, 175, 255);

/// The ten corners of a five-pointed star (outer, inner, outer...).
fn star_points(center: egui::Pos2, radius: f32) -> Vec<egui::Pos2> {
    (0..10)
        .map(|k| {
            let angle = -std::f32::consts::FRAC_PI_2 + k as f32 * std::f32::consts::PI / 5.0;
            let r = if k % 2 == 0 { radius } else { radius * 0.45 };
            center + egui::vec2(angle.cos() * r, angle.sin() * r)
        })
        .collect()
}

/// A five-pointed star, drawn as a triangle fan (egui's convex polygons
/// do not cover a star).
fn paint_star(painter: &egui::Painter, center: egui::Pos2, radius: f32, color: egui::Color32) {
    use egui::epaint::{Vertex, WHITE_UV};
    let mut mesh = egui::Mesh::default();
    mesh.vertices.push(Vertex {
        pos: center,
        uv: WHITE_UV,
        color,
    });
    for pos in star_points(center, radius) {
        mesh.vertices.push(Vertex {
            pos,
            uv: WHITE_UV,
            color,
        });
    }
    for k in 0..10u32 {
        mesh.indices.extend([0, 1 + k, 1 + (k + 1) % 10]);
    }
    painter.add(egui::Shape::mesh(mesh));
}

/// A rating star: black, outlined so it shows on a dark ground, with the
/// left `fraction` (0 to 1) of its width filled in gold.
fn paint_rating_star(
    painter: &egui::Painter,
    center: egui::Pos2,
    radius: f32,
    fraction: f32,
    fill: egui::Color32,
) {
    paint_star(painter, center, radius, egui::Color32::BLACK);
    painter.add(egui::Shape::closed_line(
        star_points(center, radius),
        egui::Stroke::new(1.0, egui::Color32::from_gray(150)),
    ));
    if fraction > 0.0 {
        let clip = egui::Rect::from_min_max(
            egui::pos2(center.x - radius - 1.0, center.y - radius - 1.0),
            egui::pos2(
                center.x - radius
                    + 2.0 * radius * fraction.min(1.0)
                    + if fraction >= 1.0 { 1.0 } else { 0.0 },
                center.y + radius + 1.0,
            ),
        );
        paint_star(&painter.with_clip_rect(clip), center, radius, fill);
    }
}

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

    /// Regression: the system header contains middle-dot `·` (2 bytes
    /// in UTF-8). The previous implementation sliced `&str` directly
    /// and panicked when a keyword's byte window happened to end inside
    /// a `·`. The byte-space comparison fixes it; this test pins the
    /// behaviour so we don't regress.
    #[test]
    fn highlight_does_not_panic_on_multibyte_separators() {
        let style = egui::Style::default();
        let text = "$ /home/nico/visual_pinball/vpinballx_bgfx -play /home/nico/tables/avatar/avatar.vpx\n  cwd:    /home/nico\n  system: ubuntu 24.04.4 lts · x11 · gnome (mutter)\n  client: pinready v0.12.1\n\nvisual pinball exited with status: signal: 11 (sigsegv) (core dumped)\n";
        let _ = highlight_error_keywords(text, &style);
    }

    #[test]
    fn highlight_finds_keywords_in_ascii_text() {
        let style = egui::Style::default();
        let _ = highlight_error_keywords("error: panicked at foo.rs", &style);
    }

    #[test]
    fn highlight_handles_french_accents_in_path() {
        let style = egui::Style::default();
        let _ = highlight_error_keywords(
            "cwd: /home/sylvain/Téléchargements/Apollo 13/error.log\n",
            &style,
        );
    }
}