vb6runtime 0.2.0

VB6 runtime library - value system, type conversions, and standard library implementations
Documentation
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
//! Native implementation of user interaction operations.
//!
//! Uses real process environment and OS primitives. Suitable for
//! Windows, Linux, macOS, and wasm32 (where it is the default backend).
//!
//! `MsgBox` rendering is platform-specific:
//!
//! - **Windows**: the Win32 `MessageBoxW` API (exact VB6 parity).
//! - **macOS**: `osascript` driving `display dialog`.
//! - **Linux**: `zenity`, when installed.
//! - **wasm32**: the browser's modal `alert`/`confirm` dialogs.
//! - **Anything else / headless**: the request is logged to stderr and the
//!   default button is returned, so programs remain runnable without a GUI.
//!
//! `InputBox` follows the same pattern:
//!
//! - **Windows**: a modal `DialogBoxIndirectParamW` dialog built from an
//!   in-memory template (label, edit box seeded with the default response,
//!   OK/Cancel buttons); honors `xpos`/`ypos`.
//! - **macOS**: `osascript display dialog ... default answer`.
//! - **Linux**: `zenity --entry`.
//! - **wasm32**: the browser's modal `prompt` (title prepended to the
//!   message; browsers cannot position dialogs, so `xpos`/`ypos` are
//!   ignored).
//! - **Anything else / headless**: the request is logged to stderr and the
//!   default response is returned, so programs remain runnable without a
//!   GUI. Cancel always yields `""`, matching VB6.
//!
//! `AppActivate` follows it too:
//!
//! - **Windows**: `EnumWindows` matching captions by prefix (then suffix,
//!   per VB6 rules; numeric titles additionally try Shell task IDs via
//!   process id), raised with `SetForegroundWindow`.
//! - **macOS**: `osascript` driving System Events (`frontmost`, window
//!   raise).
//! - **Linux (X11)**: `wmctrl -l -a`.
//! - **Anything else / headless**: the request is logged to stderr and the
//!   call succeeds, so programs remain runnable without a GUI.
//!
//! On every platform that *does* have a working window facility but no
//! matching window, the statement raises VB6 error 5 ("Invalid procedure
//! call or argument"), exactly as real VB6 does.
//!
//! `Shell` follows the same philosophy:
//!
//! - **Windows**: `CreateProcessW` passing the command line through intact,
//!   with the requested window style applied via `STARTF_USESHOWWINDOW`
//!   (`SW_HIDE` ... `SW_SHOWMINNOACTIVE`) — exact VB6 parity. The returned
//!   task ID is the new process id, which is also what `AppActivate`'s
//!   numeric form matches against.
//! - **Linux/macOS**: the command line is split into program + arguments
//!   (double quotes honored), then spawned detached in its own process
//!   group with its standard streams disconnected; the window style has no
//!   equivalent and is ignored.
//! - **wasm32**: browsers cannot start processes, so the request is logged
//!   to stderr and a synthetic task ID is returned so programs remain
//!   runnable.
//!
//! A spawn failure raises VB6 error 53 ("File not found") when the program
//! does not exist and error 70 ("Permission denied") when it cannot be
//! executed, matching VB6's trappable errors.
//!
//! `SendKeys` completes the set:
//!
//! - **Windows**: `SendInput` feeding one key-down/key-up pair per decoded
//!   stroke, with Shift/Ctrl/Alt pressed around it; characters resolve
//!   through the active keyboard layout (`VkKeyScanW`) so `^c` reaches the
//!   target as a genuine Ctrl+C, falling back to `KEYEVENTF_UNICODE` events
//!   for characters the layout cannot produce.
//! - **macOS**: a single `osascript` driving System Events (`keystroke` for
//!   text, `key code` for named keys, `using {…down}` for modifiers).
//! - **Linux (X11)**: `xdotool` — `type` for literal character runs,
//!   `key --clearmodifiers` for named keys and modifier combinations.
//! - **Anything else / headless**: the request is logged to stderr and the
//!   call succeeds, so programs remain runnable without an input injector.

use crate::error::{err_number, VBError, VBResult};

use super::appactivate::AppActivateRequest;
use super::backend::InteractionBackend;
use super::inputbox::InputBoxRequest;
use super::msgbox::{MsgBoxButton, MsgBoxRequest};
use super::sendkeys::SendKeysRequest;
use super::shell::ShellRequest;

/// Native interaction backend using real OS facilities.
pub struct NativeBackend;

impl NativeBackend {
    /// Create a new native backend.
    pub fn new() -> Self {
        Self
    }
}

impl Default for NativeBackend {
    fn default() -> Self {
        Self::new()
    }
}

impl InteractionBackend for NativeBackend {
    fn command_args(&self) -> Vec<String> {
        std::env::args().skip(1).collect()
    }

    fn do_events(&self) -> i16 {
        std::thread::yield_now();
        0
    }

    fn beep(&self) {
        // Write the terminal bell character to stderr — works on all
        // major terminal emulators across Windows, Linux, and macOS.
        use std::io::Write;
        let _ = std::io::stderr().write_all(b"\x07");
    }

    fn stop(&self) {
        // No interactive debugger is attached for native batch runs; the
        // interpreter falls back to the compiled-`.exe` behavior
        // (`Stop` acts like `End`).
    }

    fn msg_box(&self, request: &MsgBoxRequest) -> VBResult<MsgBoxButton> {
        show_dialog(request)
    }

    fn input_box(&self, request: &InputBoxRequest) -> VBResult<String> {
        show_input_dialog(request)
    }

    fn app_activate(&self, request: &AppActivateRequest) -> VBResult<()> {
        activate_window(request)
    }

    fn send_keys(&self, request: &SendKeysRequest) -> VBResult<()> {
        deliver_keystrokes(request)
    }

    fn shell(&self, request: &ShellRequest) -> VBResult<f64> {
        launch(request).map_err(|err| {
            // The OS error alone ("No such file or directory (os error 2)")
            // never names the program; real VB6's error 53 is understood to
            // be about the pathname that was passed, so include it.
            let mapped = VBError::from(err);
            VBError::with_description(
                mapped.number,
                format!("\"{}\": {}", request.pathname, mapped.description),
            )
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

/// Show a real dialog where the platform provides one; log-and-default
/// everywhere else. Never fails: a missing dialog tool degrades to the
/// fallback so a `MsgBox` cannot abort an otherwise runnable program.
fn show_dialog(request: &MsgBoxRequest) -> VBResult<MsgBoxButton> {
    #[cfg(target_os = "windows")]
    {
        // Win32 MessageBoxW always answers with a VbMsgBoxResult value.
        Ok(windows::message_box(request))
    }
    #[cfg(target_os = "macos")]
    {
        Ok(macos::display_dialog(request).unwrap_or_else(|| fallback(request)))
    }
    #[cfg(all(unix, not(target_os = "macos")))]
    {
        Ok(linux::zenity_dialog(request).unwrap_or_else(|| fallback(request)))
    }
    #[cfg(target_arch = "wasm32")]
    {
        // Browser alert/confirm are modal and always answer, so this
        // cannot fail either.
        Ok(wasm::display_dialog(request))
    }
    #[cfg(not(any(windows, unix, target_arch = "wasm32")))]
    {
        let _ = request;
        Ok(fallback(request))
    }
}

/// Show a real input dialog where the platform provides one; log-and-default
/// everywhere else. Never fails: a missing dialog tool degrades to the
/// fallback so an `InputBox` cannot abort an otherwise runnable program.
fn show_input_dialog(request: &InputBoxRequest) -> VBResult<String> {
    #[cfg(target_os = "windows")]
    {
        Ok(windows::input_dialog(request).unwrap_or_else(|| input_fallback(request)))
    }
    #[cfg(target_os = "macos")]
    {
        Ok(macos::input_dialog(request).unwrap_or_else(|| input_fallback(request)))
    }
    #[cfg(all(unix, not(target_os = "macos")))]
    {
        Ok(linux::entry_dialog(request).unwrap_or_else(|| input_fallback(request)))
    }
    #[cfg(target_arch = "wasm32")]
    {
        // Browser prompt is modal and always answers (None = Cancel).
        Ok(wasm::prompt_dialog(request).unwrap_or_default())
    }
    #[cfg(not(any(windows, unix, target_arch = "wasm32")))]
    {
        let _ = request;
        Ok(input_fallback(request))
    }
}

/// Log the request to stderr and answer with its default button.
///
/// Used when no dialog facility exists (headless Linux without zenity,
/// CI machines) so batch runs keep going instead of hanging or failing.
#[cfg_attr(target_arch = "wasm32", allow(dead_code))] // still exercised by tests
fn fallback(request: &MsgBoxRequest) -> MsgBoxButton {
    let title = request.title.as_deref().unwrap_or("MsgBox");
    let buttons = request
        .offered_buttons()
        .iter()
        .map(|b| b.name())
        .collect::<Vec<_>>()
        .join("|");
    eprintln!("[MsgBox] {title}: {} [{buttons}]", request.prompt);
    request.default_button_value()
}

/// Log the request to stderr and answer with its default response.
///
/// Used when no dialog facility exists (headless Linux without zenity,
/// CI machines) so batch runs keep going instead of hanging or failing.
#[cfg_attr(target_arch = "wasm32", allow(dead_code))] // still exercised by tests
fn input_fallback(request: &InputBoxRequest) -> String {
    let title = request.title.as_deref().unwrap_or("InputBox");
    eprintln!(
        "[InputBox] {title}: {} [{}]",
        request.prompt, request.default_response
    );
    request.default_response.clone()
}

/// Activate a matching window where the platform provides one; log-and-
/// succeed everywhere else. Only a platform with a working window facility
/// that cannot find the window raises VB6 error 5 — a headless machine has
/// no windows to find, so failing every call would abort otherwise runnable
/// programs.
fn activate_window(request: &AppActivateRequest) -> VBResult<()> {
    #[cfg(target_os = "windows")]
    {
        if windows::activate_window(request) {
            Ok(())
        } else {
            Err(no_such_window(&request.title))
        }
    }
    #[cfg(target_os = "macos")]
    {
        match macos::activate_window(request) {
            Some(true) => Ok(()),
            Some(false) => Err(no_such_window(&request.title)),
            None => {
                activate_fallback(request);
                Ok(())
            }
        }
    }
    #[cfg(all(unix, not(target_os = "macos")))]
    {
        match linux::activate_window(request) {
            Some(true) => Ok(()),
            Some(false) => Err(no_such_window(&request.title)),
            None => {
                activate_fallback(request);
                Ok(())
            }
        }
    }
    #[cfg(not(any(unix, windows)))]
    {
        // Browsers (wasm32) and exotic targets expose no OS windows.
        let _ = request;
        activate_fallback(request);
        Ok(())
    }
}

/// Build the error 5 raised when a platform with real windows has none
/// matching `title`.
#[cfg_attr(
    not(any(windows, unix)),
    allow(dead_code) // exercised by tests; consumed by the platform backends
)]
fn no_such_window(title: &str) -> VBError {
    VBError::with_description(
        err_number::INVALID_PROCEDURE_CALL,
        format!(
            "Invalid procedure call or argument: AppActivate found no window titled \
             \"{title}\""
        ),
    )
}

/// Log the request to stderr and report success.
///
/// Used when no window facility exists (headless machines, wasm32) so
/// batch runs keep going instead of failing.
#[cfg_attr(target_arch = "wasm32", allow(dead_code))] // still exercised by tests
fn activate_fallback(request: &AppActivateRequest) {
    if request.wait {
        eprintln!("[AppActivate] {} [wait]", request.title);
    } else {
        eprintln!("[AppActivate] {}", request.title);
    }
}

// ---- SendKeys ----

/// Synthesize `request`'s keystrokes into the active window.
///
/// Platform dispatch for `SendKeys`: a real input injector where the OS
/// provides one (`SendInput` on Windows, System Events via `osascript` on
/// macOS, `xdotool` on Linux), log-and-succeed elsewhere so a headless or
/// browser run cannot abort a program that merely sends keys. Malformed key
/// strings never reach this far — [`SendKeysRequest::parse`] rejects them —
/// so delivery itself has no error path.
fn deliver_keystrokes(request: &SendKeysRequest) -> VBResult<()> {
    #[cfg(target_os = "windows")]
    {
        windows::send_keys(request);
    }
    #[cfg(target_os = "macos")]
    {
        if !macos::send_keys(request) {
            sendkeys_fallback(request);
        }
    }
    #[cfg(all(unix, not(target_os = "macos")))]
    {
        if !linux::send_keys(request) {
            sendkeys_fallback(request);
        }
    }
    #[cfg(not(any(unix, windows)))]
    {
        // Browsers (wasm32) and exotic targets cannot inject keystrokes
        // into an OS input queue that does not exist.
        let _ = request;
        sendkeys_fallback(request);
    }
    Ok(())
}

/// Log the request to stderr and report success.
///
/// Used when no keyboard facility exists (headless machines, wasm32) so
/// batch runs keep going instead of failing.
#[cfg_attr(target_arch = "wasm32", allow(dead_code))] // still exercised by tests
fn sendkeys_fallback(request: &SendKeysRequest) {
    if request.wait {
        eprintln!("[SendKeys] {} [wait]", request.keys);
    } else {
        eprintln!("[SendKeys] {}", request.keys);
    }
}

// ---- Shell ----

/// Source of task IDs on platforms that cannot start processes at all;
/// monotonically increasing so successive launches stay distinguishable
/// (and truthy — VB6 uses 0/absence to mean failure).
#[cfg(not(any(windows, unix)))]
static SYNTHETIC_TASK_IDS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

/// Next synthetic task ID for platforms without process creation.
#[cfg(not(any(windows, unix)))]
fn next_synthetic_task_id() -> f64 {
    use std::sync::atomic::Ordering;
    1.0 + SYNTHETIC_TASK_IDS.fetch_add(1, Ordering::Relaxed) as f64
}

/// Start `request`'s program without waiting for it and report its task ID.
///
/// Platform dispatch for `Shell`: real process creation where the OS
/// provides one, log-and-synthesize elsewhere so a browser run cannot crash
/// a program that merely shells out. The returned task ID is the child's
/// process id, which is what `AppActivate`'s numeric form matches against.
fn launch(request: &ShellRequest) -> std::io::Result<f64> {
    #[cfg(target_os = "windows")]
    {
        windows::spawn_process(request)
    }
    #[cfg(unix)]
    {
        posix::spawn_process(request)
    }
    #[cfg(not(any(windows, unix)))]
    {
        let _ = request;
        eprintln!("[Shell] {}", request.pathname);
        Ok(next_synthetic_task_id())
    }
}

#[cfg(target_os = "windows")]
mod windows {
    use std::cell::RefCell;
    use std::ffi::OsStr;
    use std::os::windows::ffi::OsStrExt;

    use windows_sys::Win32::Foundation::{HWND, LPARAM, LRESULT, WPARAM};
    use windows_sys::Win32::UI::WindowsAndMessaging::{
        DialogBoxIndirectParamW, EndDialog, GetDialogBaseUnits, GetDlgItemTextW, MessageBoxW,
        SetDlgItemTextW, BS_DEFPUSHBUTTON, BS_PUSHBUTTON, DS_CENTER, DS_MODALFRAME, ES_AUTOHSCROLL,
        IDCANCEL, IDOK, MB_ABORTRETRYIGNORE, MB_DEFBUTTON1, MB_DEFBUTTON2, MB_DEFBUTTON3,
        MB_DEFBUTTON4, MB_HELP, MB_ICONERROR, MB_ICONINFORMATION, MB_ICONQUESTION, MB_ICONWARNING,
        MB_OK, MB_OKCANCEL, MB_RETRYCANCEL, MB_RIGHT, MB_RTLREADING, MB_SETFOREGROUND,
        MB_SYSTEMMODAL, MB_YESNO, MB_YESNOCANCEL, WM_COMMAND, WM_INITDIALOG, WS_BORDER, WS_CAPTION,
        WS_CHILD, WS_GROUP, WS_POPUP, WS_SYSMENU, WS_TABSTOP, WS_VISIBLE,
    };

    use super::super::appactivate::AppActivateRequest;
    use super::super::inputbox::InputBoxRequest;
    use super::super::msgbox::{
        MsgBoxButton, MsgBoxButtonSet, MsgBoxIcon, MsgBoxModality, MsgBoxRequest,
    };

    /// Encode a Rust string as a NUL-terminated UTF-16 buffer.
    fn wide(s: &str) -> Vec<u16> {
        use std::iter::once;
        std::ffi::OsStr::new(s)
            .encode_wide()
            .chain(once(0))
            .collect()
    }

    /// Show the dialog with `MessageBoxW` and map the result back.
    ///
    /// If the call fails (returns 0) or the user picks Help, the request's
    /// default button is returned so callers always get a valid answer.
    pub(super) fn message_box(request: &MsgBoxRequest) -> MsgBoxButton {
        let text = wide(&request.prompt);
        let caption = wide(request.title.as_deref().unwrap_or(""));

        let mut flags = match request.button_set {
            MsgBoxButtonSet::OkOnly => MB_OK,
            MsgBoxButtonSet::OkCancel => MB_OKCANCEL,
            MsgBoxButtonSet::AbortRetryIgnore => MB_ABORTRETRYIGNORE,
            MsgBoxButtonSet::YesNoCancel => MB_YESNOCANCEL,
            MsgBoxButtonSet::YesNo => MB_YESNO,
            MsgBoxButtonSet::RetryCancel => MB_RETRYCANCEL,
        } | match request.icon {
            MsgBoxIcon::None => 0,
            MsgBoxIcon::Critical => MB_ICONERROR,
            MsgBoxIcon::Question => MB_ICONQUESTION,
            MsgBoxIcon::Exclamation => MB_ICONWARNING,
            MsgBoxIcon::Information => MB_ICONINFORMATION,
        } | match request.default_button {
            1 => MB_DEFBUTTON1,
            2 => MB_DEFBUTTON2,
            3 => MB_DEFBUTTON3,
            _ => MB_DEFBUTTON4,
        };
        flags |= match request.modality {
            MsgBoxModality::Application => 0,
            MsgBoxModality::System => MB_SYSTEMMODAL,
        };
        if request.help_button {
            flags |= MB_HELP;
        }
        if request.set_foreground {
            flags |= MB_SETFOREGROUND;
        }
        if request.right_aligned {
            flags |= MB_RIGHT;
        }
        if request.rtl_reading {
            flags |= MB_RTLREADING;
        }

        let hwnd: *mut core::ffi::c_void = std::ptr::null_mut();
        let result = unsafe { MessageBoxW(hwnd, text.as_ptr(), caption.as_ptr(), flags) };

        MsgBoxButton::from_id(result as i16).unwrap_or_else(|| request.default_button_value())
    }

    // ---- AppActivate ----

    /// One top-level window seen by [`activate_window`]'s enumeration.
    struct WindowInfo {
        hwnd: isize,
        title: String,
        pid: u32,
    }

    /// Bring the window matching `request` to the foreground.
    ///
    /// Mirrors VB6 matching: numeric titles are tried as Shell task IDs
    /// (process ids) first; otherwise an exact caption match wins over a
    /// case-insensitive prefix match, which in turn wins over a
    /// case-insensitive suffix match. Returns whether a window was found
    /// and focused.
    pub(super) fn activate_window(request: &AppActivateRequest) -> bool {
        use windows_sys::Win32::UI::WindowsAndMessaging::{
            EnumWindows, IsIconic, SetForegroundWindow, ShowWindow, SW_RESTORE,
        };

        unsafe extern "system" fn enum_proc(hwnd: HWND, lparam: LPARAM) -> windows_sys::core::BOOL {
            use windows_sys::Win32::UI::WindowsAndMessaging::{
                GetWindowTextLengthW, GetWindowTextW, GetWindowThreadProcessId, IsWindowVisible,
            };

            let windows = &mut *(lparam as *mut Vec<WindowInfo>);
            if IsWindowVisible(hwnd) != 0 {
                let mut title = String::new();
                let len = GetWindowTextLengthW(hwnd);
                if len > 0 {
                    let mut buffer = vec![0u16; len as usize + 1];
                    let copied =
                        GetWindowTextW(hwnd, buffer.as_mut_ptr(), buffer.len() as i32) as usize;
                    buffer.truncate(copied);
                    title = String::from_utf16_lossy(&buffer);
                }
                let mut pid: u32 = 0;
                GetWindowThreadProcessId(hwnd, &mut pid);
                windows.push(WindowInfo {
                    hwnd: hwnd as isize,
                    title,
                    pid,
                });
            }
            1 // keep enumerating
        }

        let mut windows: Vec<WindowInfo> = Vec::new();
        unsafe {
            EnumWindows(Some(enum_proc), &mut windows as *mut _ as LPARAM);
        }

        let needle = request.title.to_lowercase();

        // Task-id form (`AppActivate Shell(...)`) matches by process id;
        // string form walks VB6's exact → prefix → suffix ladder.
        let target = if let Some(task_id) = request.as_task_id() {
            windows
                .iter()
                .find(|w| w.pid == task_id as u32)
                .map(|w| w.hwnd)
                .or_else(|| find_string_match(&windows, &needle))
        } else {
            find_string_match(&windows, &needle)
        };

        let Some(hwnd) = target else {
            return false;
        };

        unsafe {
            let hwnd = hwnd as HWND;
            if IsIconic(hwnd) != 0 {
                ShowWindow(hwnd, SW_RESTORE);
            }
            SetForegroundWindow(hwnd);
        }
        true
    }

    /// Walk the exact → prefix → suffix caption ladder for `needle`.
    ///
    /// Comparisons fold case, mirroring VB6's case-insensitive title
    /// matching.
    fn find_string_match(windows: &[WindowInfo], needle: &str) -> Option<isize> {
        let folded: Vec<(isize, String)> = windows
            .iter()
            .map(|w| (w.hwnd, w.title.to_lowercase()))
            .collect();
        folded
            .iter()
            .find(|(_, title)| title == needle)
            .or_else(|| folded.iter().find(|(_, title)| title.starts_with(needle)))
            .or_else(|| folded.iter().find(|(_, title)| title.ends_with(needle)))
            .map(|(hwnd, _)| *hwnd)
    }

    // ---- SendKeys ----

    /// Inject every decoded stroke with `SendInput`.
    ///
    /// Each [`Keystroke`](super::super::sendkeys::Keystroke) becomes a
    /// modifier-down / key-down / key-up / modifier-up event group, so
    /// VB6's per-stroke modifiers (`^c`, `%{F4}`) reach the focused window
    /// exactly as if typed.
    pub(super) fn send_keys(request: &SendKeysRequest) {
        use windows_sys::Win32::UI::Input::KeyboardAndMouse::{
            KEYEVENTF_KEYUP, VK_CONTROL, VK_MENU, VK_SHIFT,
        };

        let mut inputs: Vec<windows_sys::Win32::UI::Input::KeyboardAndMouse::INPUT> = Vec::new();
        for stroke in &request.strokes {
            // Modifiers explicitly requested by the notation go first.
            let mut held: Vec<u16> = Vec::new();
            if stroke.shift {
                held.push(VK_SHIFT);
            }
            if stroke.ctrl {
                held.push(VK_CONTROL);
            }
            if stroke.alt {
                held.push(VK_MENU);
            }

            let key_event = match stroke.key {
                SendKey::Char(c) => {
                    // Resolve through the live keyboard layout so the
                    // receiving application sees real shortcut keys; the
                    // layout may itself require Shift (e.g. 'A'), which
                    // joins the held set.
                    match layout_key(c) {
                        Some((vk_code, layout_shift)) => {
                            if layout_shift && !stroke.shift {
                                held.push(VK_SHIFT);
                            }
                            Event::Virtual(vk_code)
                        }
                        None => Event::Unicode(c),
                    }
                }
                named => Event::Virtual(virtual_key_code(named)),
            };

            for vk in &held {
                inputs.push(key_input(*vk, 0, 0));
            }
            match key_event {
                Event::Virtual(vk) => {
                    inputs.push(key_input(vk, 0, 0));
                    inputs.push(key_input(vk, 0, KEYEVENTF_KEYUP));
                }
                Event::Unicode(c) => push_unicode(&mut inputs, c),
            }
            for vk in held.iter().rev() {
                inputs.push(key_input(*vk, 0, KEYEVENTF_KEYUP));
            }
        }

        if inputs.is_empty() {
            return;
        }
        let sent = unsafe {
            use windows_sys::Win32::UI::Input::KeyboardAndMouse::SendInput;
            SendInput(
                inputs.len() as u32,
                inputs.as_mut_ptr(),
                std::mem::size_of::<windows_sys::Win32::UI::Input::KeyboardAndMouse::INPUT>()
                    as i32,
            )
        };
        if sent != inputs.len() as u32 {
            eprintln!(
                "[SendKeys] SendInput delivered {sent} of {} events",
                inputs.len()
            );
        }
    }

    /// One synthesized event: a virtual key code or a Unicode character.
    enum Event {
        Virtual(u16),
        Unicode(char),
    }

    /// Map `c` onto this layout's virtual key plus required Shift state;
    /// `None` when the layout cannot type it at all.
    fn layout_key(c: char) -> Option<(u16, bool)> {
        use windows_sys::Win32::UI::Input::KeyboardAndMouse::VkKeyScanW;

        let scanned = unsafe { VkKeyScanW(c as u16) };
        if scanned == -1 {
            return None;
        }
        let vk_code = (scanned & 0xFF) as u16;
        if vk_code == 0xFF {
            return None;
        }
        let shift_state = ((scanned >> 8) & 0xFF) as u8;
        Some((vk_code, shift_state & 1 != 0))
    }

    /// Characters the layout cannot produce ride in as Unicode events
    /// (surrogate pairs split into their two UTF-16 units).
    fn push_unicode(
        inputs: &mut Vec<windows_sys::Win32::UI::Input::KeyboardAndMouse::INPUT>,
        c: char,
    ) {
        use windows_sys::Win32::UI::Input::KeyboardAndMouse::{KEYEVENTF_KEYUP, KEYEVENTF_UNICODE};

        let mut units = [0u16; 2];
        let count = c.encode_utf16(&mut units).len();
        for unit in &units[..count] {
            inputs.push(key_input(0, *unit, KEYEVENTF_UNICODE));
            inputs.push(key_input(0, *unit, KEYEVENTF_UNICODE | KEYEVENTF_KEYUP));
        }
    }

    /// Assemble one `KEYBDINPUT` event.
    fn key_input(
        wvk: u16,
        scan: u16,
        flags: u32,
    ) -> windows_sys::Win32::UI::Input::KeyboardAndMouse::INPUT {
        use windows_sys::Win32::UI::Input::KeyboardAndMouse::{
            INPUT, INPUT_0, INPUT_KEYBOARD, KEYBDINPUT,
        };
        INPUT {
            r#type: INPUT_KEYBOARD,
            Anonymous: INPUT_0 {
                ki: KEYBDINPUT {
                    wVk: wvk,
                    wScan: scan,
                    dwFlags: flags,
                    time: 0,
                    dwExtraInfo: 0,
                },
            },
        }
    }

    /// Map a decoded key name onto its Win32 virtual-key code.
    fn virtual_key_code(key: SendKey) -> u16 {
        use windows_sys::Win32::UI::Input::KeyboardAndMouse::{
            VK_BACK, VK_CANCEL, VK_CAPITAL, VK_DELETE, VK_DOWN, VK_END, VK_ESCAPE, VK_F1, VK_HELP,
            VK_HOME, VK_INSERT, VK_LEFT, VK_NEXT, VK_NUMLOCK, VK_PRIOR, VK_RETURN, VK_RIGHT,
            VK_SCROLL, VK_SNAPSHOT, VK_TAB, VK_UP,
        };
        match key {
            SendKey::Backspace => VK_BACK,
            SendKey::Break => VK_CANCEL,
            SendKey::CapsLock => VK_CAPITAL,
            SendKey::Delete => VK_DELETE,
            SendKey::Down => VK_DOWN,
            SendKey::End => VK_END,
            SendKey::Enter => VK_RETURN,
            SendKey::Esc => VK_ESCAPE,
            SendKey::Help => VK_HELP,
            SendKey::Home => VK_HOME,
            SendKey::Insert => VK_INSERT,
            SendKey::Left => VK_LEFT,
            SendKey::NumLock => VK_NUMLOCK,
            SendKey::PageDown => VK_NEXT,
            SendKey::PageUp => VK_PRIOR,
            SendKey::PrintScreen => VK_SNAPSHOT,
            SendKey::Right => VK_RIGHT,
            SendKey::ScrollLock => VK_SCROLL,
            SendKey::Tab => VK_TAB,
            SendKey::Up => VK_UP,
            SendKey::Function(n) => VK_F1 + (n.max(1).min(24) as u16 - 1),
            // Characters never reach here: they resolve through the layout
            // (or Unicode events) inside `send_keys`.
            SendKey::Char(_) => unreachable!("character keys are handled by the layout mapping"),
        }
    }

    // ---- InputBox ----

    thread_local! {
        /// Answer collected by the dialog procedure for the current modal
        /// run; `None` means the user cancelled or the dialog failed.
        static INPUT_ANSWER: RefCell<Option<String>> = const { RefCell::new(None) };
    }

    /// Control id of the edit box inside the input dialog template.
    const ID_EDIT: i32 = 1001;

    /// Predefined window-class atoms for dialog items.
    const CLASS_BUTTON: u16 = 0x0080;
    const CLASS_EDIT: u16 = 0x0081;
    const CLASS_STATIC: u16 = 0x0082;

    /// Show a modal input box via `DialogBoxIndirectParamW`.
    ///
    /// The dialog is built from an in-memory template (prompt label, single
    /// line edit seeded with the default response, OK and Cancel buttons).
    /// Returns `None` when the dialog cannot be created, letting the caller
    /// fall back to logging. Enter accepts; Esc and Cancel both yield
    /// `""` at the caller, mirroring VB6.
    pub(super) fn input_dialog(request: &InputBoxRequest) -> Option<String> {
        let template = build_template(request);
        INPUT_ANSWER.with(|slot| *slot.borrow_mut() = None);
        let failed = unsafe {
            DialogBoxIndirectParamW(
                std::ptr::null_mut(), // template references no resources
                template.as_ptr().cast(),
                std::ptr::null_mut(),
                Some(input_dialog_proc),
                request as *const InputBoxRequest as isize,
            ) == -1
        };
        if failed {
            return None;
        }
        INPUT_ANSWER.with(|slot| slot.borrow_mut().take())
    }

    /// Assemble the raw `DLGTEMPLATE` for an input box.
    ///
    /// When the request carries a position, the dialog's origin is placed at
    /// that screen location (twips converted through the system dialog base
    /// units); otherwise the dialog centers on the screen.
    fn build_template(request: &InputBoxRequest) -> Vec<u16> {
        let mut style =
            WS_POPUP | WS_CAPTION | WS_SYSMENU | DS_MODALFRAME as u32 | DS_CENTER as u32;
        let (mut x, mut y) = (0i16, 0i16);
        if let (Some(xpos), Some(ypos)) = (request.xpos, request.ypos) {
            (x, y) = position_in_dialog_units(xpos, ypos);
            style &= !(DS_CENTER as u32);
        }

        let mut b = TemplateBuilder::dialog(style, x, y, 210, 94, request.title.as_deref());
        // Prompt label (style 0 == SS_LEFT), then edit box, then buttons.
        b.item(
            WS_CHILD | WS_VISIBLE | WS_GROUP,
            10,
            8,
            190,
            44,
            0,
            CLASS_STATIC,
            &request.prompt,
        );
        b.item(
            WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP | ES_AUTOHSCROLL as u32,
            10,
            56,
            190,
            13,
            ID_EDIT as u16,
            CLASS_EDIT,
            "",
        );
        b.item(
            WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_DEFPUSHBUTTON as u32,
            92,
            76,
            50,
            14,
            IDOK as u16,
            CLASS_BUTTON,
            "OK",
        );
        b.item(
            WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON as u32,
            148,
            76,
            50,
            14,
            IDCANCEL as u16,
            CLASS_BUTTON,
            "Cancel",
        );
        b.finish()
    }

    /// Convert a requested twips offset into dialog units at 96 DPI.
    fn position_in_dialog_units(xpos: i32, ypos: i32) -> (i16, i16) {
        // LOWORD: average character width; HIWORD: average character height.
        let base = unsafe { GetDialogBaseUnits() };
        let base_x = (base & 0xFFFF).max(1) as i32;
        let base_y = ((base >> 16) & 0xFFFF).max(1) as i32;
        // 1440 twips per inch at 96 dpi => 15 twips per pixel; pixels =>
        // dialog units by the standard base-unit ratios (4 and 8).
        let dlu_x = (xpos / 15) * 4 / base_x;
        let dlu_y = (ypos / 15) * 8 / base_y;
        (
            dlu_x.clamp(i16::MIN as i32, i16::MAX as i32) as i16,
            dlu_y.clamp(i16::MIN as i32, i16::MAX as i32) as i16,
        )
    }

    /// The modal dialog procedure backing [`input_dialog`].
    ///
    /// The request rides in `dwInitParam`; the accepted answer travels back
    /// out through [`INPUT_ANSWER`] because the modal loop runs on the
    /// calling thread. Cancel/Esc end the dialog without touching it.
    unsafe extern "system" fn input_dialog_proc(
        hwnd: HWND,
        message: u32,
        wparam: WPARAM,
        lparam: LPARAM,
    ) -> LRESULT {
        match message {
            WM_INITDIALOG => {
                let request = &*(lparam as *const InputBoxRequest);
                let default_text = wide(&request.default_response);
                SetDlgItemTextW(hwnd, ID_EDIT, default_text.as_ptr());
                0 // let the system focus the first tab stop (the edit box)
            }
            WM_COMMAND => match wparam & 0xFFFF {
                id if id == IDOK as usize => {
                    let text = read_edit_text(hwnd);
                    INPUT_ANSWER.with(|slot| *slot.borrow_mut() = Some(text));
                    EndDialog(hwnd, 1);
                    1
                }
                id if id == IDCANCEL as usize => {
                    EndDialog(hwnd, 0);
                    0
                }
                _ => 0,
            },
            _ => 0,
        }
    }

    /// Read the current contents of the edit box, growing until it fits.
    unsafe fn read_edit_text(hwnd: HWND) -> String {
        let mut capacity = 260usize;
        loop {
            let mut buffer = vec![0u16; capacity];
            let copied =
                GetDlgItemTextW(hwnd, ID_EDIT, buffer.as_mut_ptr(), capacity as i32) as usize;
            if copied + 1 < capacity {
                buffer.truncate(copied);
                return String::from_utf16_lossy(&buffer);
            }
            capacity *= 2;
        }
    }

    /// Builder for a NUL-free sequence of words forming a `DLGTEMPLATE`
    /// plus its items, keeping every field DWORD-aligned as required.
    struct TemplateBuilder {
        words: Vec<u16>,
    }

    impl TemplateBuilder {
        /// Start a dialog header with the given geometry and title.
        fn dialog(style: u32, x: i16, y: i16, cx: i16, cy: i16, title: Option<&str>) -> Self {
            let mut b = Self { words: Vec::new() };
            b.dword(style);
            b.dword(0); // dwExtendedStyle
            b.word(0); // cdit, patched by finish()
            b.word(x as u16);
            b.word(y as u16);
            b.word(cx as u16);
            b.word(cy as u16);
            b.word(0); // menu: none
            b.word(0); // class: system dialog class
            b.text(&title.unwrap_or("Input"));
            b
        }

        /// Append one control item.
        #[allow(clippy::too_many_arguments)]
        fn item(
            &mut self,
            style: u32,
            x: i16,
            y: i16,
            cx: i16,
            cy: i16,
            id: u16,
            class_atom: u16,
            text: &str,
        ) {
            self.align_dword();
            self.dword(style);
            self.dword(0); // dwExtendedStyle
            self.word(x as u16);
            self.word(y as u16);
            self.word(cx as u16);
            self.word(cy as u16);
            self.word(id);
            self.word(0xFFFF);
            self.word(class_atom);
            self.text(text);
            self.word(0); // no creation data
        }

        fn word(&mut self, value: u16) {
            self.words.push(value);
        }

        fn dword(&mut self, value: u32) {
            self.words.push(value as u16);
            self.words.push((value >> 16) as u16);
        }

        fn align_dword(&mut self) {
            if self.words.len() % 2 != 0 {
                self.word(0);
            }
        }

        fn text(&mut self, value: &str) {
            self.words.extend(OsStr::new(value).encode_wide());
            self.word(0);
        }

        /// Patch in the item count and terminate on a DWORD boundary.
        fn finish(mut self) -> Vec<u16> {
            self.align_dword();
            self.words[6] = 4; // cdit: prompt, edit, OK, Cancel
            self.words
        }
    }

    // ---- Shell ----

    /// Spawn `request.pathname` via `CreateProcessW` and return the new
    /// process id as its task ID.
    ///
    /// The command line is passed through intact — VB6 lets `Shell` carry
    /// arguments, so Windows' own parser splits it. The requested window
    /// style rides in `STARTUPINFOW` (`STARTF_USESHOWWINDOW`), giving the
    /// child exactly the show state VB6 promises; a failed spawn surfaces
    /// the OS error so callers map it onto error 53/70.
    pub(super) fn spawn_process(request: &ShellRequest) -> std::io::Result<f64> {
        use windows_sys::Win32::Foundation::CloseHandle;
        use windows_sys::Win32::System::Threading::{
            CreateProcessW, CREATE_UNICODE_ENVIRONMENT, PROCESS_INFORMATION, STARTF_USESHOWWINDOW,
            STARTUPINFOW,
        };

        // NUL-terminated UTF-16 command line; CreateProcessW may write back
        // a normalized form into this buffer, hence mutability.
        let mut command_line: Vec<u16> = std::ffi::OsStr::new(&request.pathname)
            .encode_wide()
            .chain(std::iter::once(0))
            .collect();

        let mut startup: STARTUPINFOW = unsafe { std::mem::zeroed() };
        startup.cb = std::mem::size_of::<STARTUPINFOW>() as u32;
        startup.dwFlags = STARTF_USESHOWWINDOW;
        startup.wShowWindow = show_window_flag(request.window_style);
        let mut process: PROCESS_INFORMATION = unsafe { std::mem::zeroed() };

        let started = unsafe {
            CreateProcessW(
                std::ptr::null(), // derive application name from the command line
                command_line.as_mut_ptr(),
                std::ptr::null(),
                std::ptr::null(),
                0, // no handle inheritance: Shell shares nothing with the child
                CREATE_UNICODE_ENVIRONMENT,
                std::ptr::null(), // inherit our environment block
                std::ptr::null(), // inherit our current directory
                &startup,
                &mut process,
            )
        };
        if started == 0 {
            return Err(std::io::Error::last_os_error());
        }

        // The task ID outlives these handles; dropping them releases our
        // interest without disturbing the running child.
        unsafe {
            CloseHandle(process.hThread);
            CloseHandle(process.hProcess);
        }
        Ok(f64::from(process.dwProcessId))
    }

    /// Map a VB6 window style onto the Win32 `SW_*` constant that requests
    /// the same initial show state.
    fn show_window_flag(style: super::super::shell::WindowStyle) -> u16 {
        use super::super::shell::WindowStyle;
        match style {
            WindowStyle::Hide => 0,             // SW_HIDE
            WindowStyle::NormalFocus => 1,      // SW_SHOWNORMAL
            WindowStyle::MinimizedFocus => 2,   // SW_SHOWMINIMIZED
            WindowStyle::MaximizedFocus => 3,   // SW_SHOWMAXIMIZED
            WindowStyle::NormalNoFocus => 4,    // SW_SHOWNOACTIVATE
            WindowStyle::MinimizedNoFocus => 7, // SW_SHOWMINNOACTIVE
        }
    }
}

#[cfg(target_os = "macos")]
mod macos {
    use std::process::Command;

    use super::super::appactivate::AppActivateRequest;
    use super::super::msgbox::{MsgBoxButton, MsgBoxIcon, MsgBoxRequest};

    /// Escape a string for embedding in a double-quoted AppleScript literal.
    fn escape(s: &str) -> String {
        s.replace('\\', "\\\\").replace('"', "\\\"")
    }

    /// Show the dialog via `osascript display dialog`.
    ///
    /// Returns `None` when osascript is unavailable or fails (headless
    /// machines), letting the caller fall back to logging.
    pub(super) fn display_dialog(request: &MsgBoxRequest) -> Option<MsgBoxButton> {
        let offered = request.offered_buttons();
        let labels = offered
            .iter()
            .map(|b| format!("\"{}\"", escape(b.name())))
            .collect::<Vec<_>>()
            .join(", ");
        let default_label = request.default_button_value().name();

        let mut script = format!(
            "display dialog \"{}\" buttons {{{labels}}} default button \"{}\"",
            escape(&request.prompt),
            escape(default_label),
        );
        if let Some(title) = &request.title {
            script.push_str(&format!(" with title \"{}\"", escape(title)));
        }
        script.push_str(match request.icon {
            MsgBoxIcon::Critical => " with icon stop",
            MsgBoxIcon::Question | MsgBoxIcon::Exclamation => " with icon caution",
            MsgBoxIcon::Information => " with icon note",
            MsgBoxIcon::None => "",
        });

        let output = Command::new("osascript")
            .arg("-e")
            .arg(&script)
            .output()
            .ok()?;
        if !output.status.success() {
            // Esc maps to Cancel when that button exists, mirroring VB6.
            if offered.contains(&MsgBoxButton::Cancel) {
                return Some(MsgBoxButton::Cancel);
            }
            return None;
        }

        let stdout = String::from_utf8_lossy(&output.stdout);
        stdout
            .trim()
            .strip_prefix("button returned:")
            .and_then(MsgBoxButton::from_name)
            .or(Some(request.default_button_value()))
    }

    /// Show an input box via `osascript display dialog`.
    ///
    /// The edit box is seeded with `default answer`; osascript reports the
    /// accepted text back as `text returned:...`. Esc and Cancel exit with a
    /// failure status, which VB6 reads as the empty string. Returns `None`
    /// when osascript is unavailable or cannot run (headless machines),
    /// letting the caller fall back to logging.
    pub(super) fn input_dialog(request: &InputBoxRequest) -> Option<String> {
        let mut script = format!(
            "display dialog \"{}\" default answer \"{}\" \
             buttons {{\"OK\", \"Cancel\"}} default button \"OK\"",
            escape(&request.prompt),
            escape(&request.default_response),
        );
        if let Some(title) = &request.title {
            script.push_str(&format!(" with title \"{}\"", escape(title)));
        }

        let output = Command::new("osascript")
            .arg("-e")
            .arg(&script)
            .output()
            .ok()?;
        if !output.status.success() {
            return Some(String::new());
        }

        // Success output looks like "button returned:OK, text returned:hi".
        // rsplit keeps us honest if the typed text itself contains a
        // ", text returned:" lookalike; strip only the trailing newline.
        let stdout = String::from_utf8_lossy(&output.stdout);
        let (_, value) = stdout.rsplit_once("text returned:")?;
        Some(value.strip_suffix('\n').unwrap_or(value).to_string())
    }

    // ---- AppActivate ----

    /// Bring a window whose title matches to the foreground via
    /// `osascript` + System Events.
    ///
    /// Two passes mirror VB6 matching: process/window names that begin
    /// with the requested title win first, ones that end with it second;
    /// comparisons are case-insensitive. Returns:
    ///
    /// - `Some(true)` / `Some(false)` when osascript ran (match found or
    ///   not),
    /// - `None` when osascript is unavailable or refuses to run (headless
    ///   machines, automation permissions), letting the caller fall back.
    pub(super) fn activate_window(request: &AppActivateRequest) -> Option<bool> {
        let title = escape(&request.title);

        for comparison in ["begins with", "ends with"] {
            let script = format!(
                "tell application \"System Events\"\n\
                 \x20 repeat with p in (every application process whose visible is true)\n\
                 \x20   if name of p {comparison} \"{title}\" then\n\
                 \x20     set frontmost of p to true\n\
                 \x20     return \"activated\"\n\
                 \x20   end if\n\
                 \x20   try\n\
                 \x20     repeat with w in (every window of p)\n\
                 \x20       if name of w {comparison} \"{title}\" then\n\
                 \x20         perform action \"AXRaise\" of w\n\
                 \x20         set frontmost of p to true\n\
                 \x20         return \"activated\"\n\
                 \x20       end if\n\
                 \x20     end repeat\n\
                 \x20   end try\n\
                 \x20 end repeat\n\
                 end tell\n\
                 return \"missing\""
            );

            let output = Command::new("osascript")
                .arg("-e")
                .arg(&script)
                .output()
                .ok()?;
            if !output.status.success() {
                return None;
            }
            if String::from_utf8_lossy(&output.stdout).trim() == "activated" {
                return Some(true);
            }
        }
        Some(false)
    }

    // ---- SendKeys ----

    /// macOS virtual key codes for the decoded key names.
    ///
    /// Keys with no macOS equivalent (`BREAK`, `{PRTSC}`, `{SCROLLLOCK}`,
    /// `{INSERT}`) are skipped with a note rather than mis-synthesized.
    fn macos_key_code(key: SendKey) -> Option<i32> {
        let code = match key {
            SendKey::Backspace => 51,
            SendKey::Delete => 117, // forward delete
            SendKey::Tab => 48,
            SendKey::Enter => 36,
            SendKey::Esc => 53,
            SendKey::Home => 115,
            SendKey::End => 119,
            SendKey::PageUp => 116,
            SendKey::PageDown => 121,
            SendKey::Up => 126,
            SendKey::Down => 125,
            SendKey::Left => 123,
            SendKey::Right => 124,
            SendKey::Help => 114,
            SendKey::CapsLock => 57,
            SendKey::NumLock => 71, // Clear
            SendKey::Function(n) => match n {
                1 => 122,
                2 => 120,
                3 => 99,
                4 => 118,
                5 => 96,
                6 => 97,
                7 => 98,
                8 => 100,
                9 => 101,
                10 => 109,
                11 => 103,
                12 => 111,
                13 => 105,
                14 => 107,
                15 => 113,
                _ => 106, // F16
            },
            SendKey::Break | SendKey::PrintScreen | SendKey::ScrollLock | SendKey::Insert => {
                return None
            }
            SendKey::Char(_) => return None, // handled by `keystroke`
        };
        Some(code)
    }

    /// AppleScript name of a notation modifier.
    fn modifier_clause(stroke: &super::super::sendkeys::Keystroke) -> String {
        let mut names = Vec::new();
        if stroke.shift {
            names.push("shift down");
        }
        if stroke.ctrl {
            names.push("control down");
        }
        if stroke.alt {
            names.push("option down");
        }
        if names.is_empty() {
            String::new()
        } else {
            format!(" using {{{}}}", names.join(", "))
        }
    }

    /// Deliver every decoded stroke via one System Events script.
    ///
    /// Unmodified characters accumulate into a single `keystroke "text"`
    /// statement (so typing stays fast and Unicode-safe); modified
    /// characters and named keys become one `keystroke`/`key code`
    /// statement apiece. Returns whether osascript ran the script; a
    /// failure (no osascript, no automation permission) lets the caller
    /// fall back to logging.
    pub(super) fn send_keys(request: &SendKeysRequest) -> bool {
        use super::super::sendkeys::SendKey;

        let mut lines: Vec<String> = Vec::new();
        let mut text_run = String::new();
        for stroke in &request.strokes {
            match stroke.key {
                SendKey::Char(c) if !stroke.shift && !stroke.ctrl && !stroke.alt => {
                    text_run.push(c);
                }
                SendKey::Char(c) => {
                    if !text_run.is_empty() {
                        lines.push(format!("keystroke \"{}\"", escape(&text_run)));
                        text_run.clear();
                    }
                    lines.push(format!(
                        "keystroke \"{}\"{}",
                        escape(&c.to_string()),
                        modifier_clause(stroke)
                    ));
                }
                named => {
                    if !text_run.is_empty() {
                        lines.push(format!("keystroke \"{}\"", escape(&text_run)));
                        text_run.clear();
                    }
                    match macos_key_code(named) {
                        Some(code) => {
                            lines.push(format!("key code {code}{}", modifier_clause(stroke)))
                        }
                        None => eprintln!(
                            "[SendKeys] {} has no macOS equivalent; skipped",
                            named.name()
                        ),
                    }
                }
            }
        }
        if !text_run.is_empty() {
            lines.push(format!("keystroke \"{}\"", escape(&text_run)));
        }
        if lines.is_empty() {
            return true;
        }

        let script = format!(
            "tell application \"System Events\"\n{}\nend tell",
            lines.join("\n")
        );
        Command::new("osascript")
            .arg("-e")
            .arg(&script)
            .output()
            .map(|output| output.status.success())
            .unwrap_or(false)
    }
}

#[cfg(all(unix, not(target_os = "macos")))]
mod linux {
    use std::process::Command;

    use super::super::appactivate::AppActivateRequest;
    use super::super::inputbox::InputBoxRequest;
    use super::super::msgbox::{MsgBoxButton, MsgBoxIcon, MsgBoxRequest};
    use super::super::sendkeys::{Keystroke, SendKey, SendKeysRequest};

    /// Whether no display server is reachable, so GUI dialogs would either
    /// fail slowly or hang; headless runs (CI, SSH sessions) go straight to
    /// the logging fallback.
    fn headless() -> bool {
        std::env::var_os("DISPLAY").is_none_or(|v| v.is_empty())
            && std::env::var_os("WAYLAND_DISPLAY").is_none_or(|v| v.is_empty())
    }

    /// Show the dialog via `zenity`.
    ///
    /// Zenity has no first-class multi-button message box, so the offered
    /// buttons are mapped onto its ok/cancel/extra-button slots: exit
    /// status 0 means the first (ok-label) button, any other status means
    /// the second (cancel-label) button — mirroring Esc-as-Cancel — and a
    /// pressed extra button prints its label on stdout. Returns `None`
    /// when zenity is not installed or cannot show the dialog.
    pub(super) fn zenity_dialog(request: &MsgBoxRequest) -> Option<MsgBoxButton> {
        if headless() {
            return None;
        }

        let offered = request.offered_buttons();

        let mut command = Command::new("zenity");
        command.arg(match request.icon {
            MsgBoxIcon::Critical => "--error",
            MsgBoxIcon::Question => "--question",
            MsgBoxIcon::Exclamation => "--warning",
            MsgBoxIcon::Information | MsgBoxIcon::None => "--info",
        });
        command.arg("--no-wrap");
        command.arg("--text").arg(&request.prompt);
        if let Some(title) = &request.title {
            command.arg("--title").arg(title);
        }

        let first = offered[0];
        let second = offered.get(1).copied();
        let third = offered.get(2).copied();
        command.arg("--ok-label").arg(first.name());
        if let Some(second) = second {
            command.arg("--cancel-label").arg(second.name());
        }
        if let Some(third) = third {
            command.arg("--extra-button").arg(third.name());
        }

        let output = command.output().ok()?;

        if let Some(third) = third {
            let label = String::from_utf8_lossy(&output.stdout);
            if label.trim().eq_ignore_ascii_case(third.name()) {
                return Some(third);
            }
        }
        if output.status.success() {
            Some(first)
        } else {
            second
        }
    }

    /// Show an input box via `zenity --entry`.
    ///
    /// The entry field is seeded with `--entry-text`; zenity prints the
    /// accepted text on stdout, and a non-zero exit (Cancel/Esc) reads as
    /// the empty string, mirroring VB6. Position arguments have no zenity
    /// equivalent and are ignored. Returns `None` when zenity is not
    /// installed or no display server is reachable.
    pub(super) fn entry_dialog(request: &InputBoxRequest) -> Option<String> {
        if headless() {
            return None;
        }

        let mut command = Command::new("zenity");
        command.arg("--entry");
        command.arg("--text").arg(&request.prompt);
        command.arg("--entry-text").arg(&request.default_response);
        if let Some(title) = &request.title {
            command.arg("--title").arg(title);
        }

        let output = command.output().ok()?;
        if !output.status.success() {
            return Some(String::new());
        }
        // Zenity appends exactly one newline to the typed text; keep any
        // trailing spaces the user actually entered.
        let mut text = String::from_utf8_lossy(&output.stdout).into_owned();
        if text.ends_with('\n') {
            text.pop();
        }
        Some(text)
    }

    /// Bring a window whose title matches to the foreground via `wmctrl`.
    ///
    /// The window list from `wmctrl -l` is matched in Rust so VB6's rules
    /// apply exactly: case-insensitive prefix first, suffix second (exact
    /// matches win inside both). Returns:
    ///
    /// - `Some(true)` / `Some(false)` when wmctrl ran (match found and
    ///   activated, or no match),
    /// - `None` when wmctrl is unavailable or cannot reach a display
    ///   (headless machines, Wayland sessions without XWayland), letting
    ///   the caller fall back.
    pub(super) fn activate_window(request: &AppActivateRequest) -> Option<bool> {
        let listing = Command::new("wmctrl").arg("-l").output().ok()?;
        if !listing.status.success() {
            return None;
        }

        let needle = request.title.to_lowercase();
        let windows: Vec<(String, String)> = String::from_utf8_lossy(&listing.stdout)
            .lines()
            .filter_map(|line| {
                let mut parts = line.splitn(4, char::is_whitespace);
                let id = parts.next()?.to_string();
                parts.next()?; // desktop number
                parts.next()?; // hostname
                Some((id, parts.next()?.to_lowercase()))
            })
            .collect();

        let find = |predicate: &dyn Fn(&str) -> bool| -> Option<String> {
            windows
                .iter()
                .find(|(_, title)| predicate(title))
                .map(|(id, _)| id.clone())
        };
        let target = find(&|t| t == needle)
            .or_else(|| find(&|t| t.starts_with(&needle)))
            .or_else(|| find(&|t| t.ends_with(&needle)))?;

        Command::new("wmctrl")
            .args(["-i", "-a"])
            .arg(target)
            .status()
            .ok()
            .map(|status| status.success())
    }

    // ---- SendKeys ----

    /// Deliver every decoded stroke via `xdotool`.
    ///
    /// Runs of unmodified characters go through `xdotool type` (which
    /// handles layout and Unicode); named keys and modifier combinations go
    /// through `xdotool key --clearmodifiers`, one invocation each, so
    /// VB6's per-stroke modifiers apply exactly (`^c`, `%{F4}`). Returns
    /// whether at least one xdotool invocation ran successfully; a missing
    /// tool or no reachable display lets the caller fall back.
    pub(super) fn send_keys(request: &SendKeysRequest) -> bool {
        /// Type an accumulated run of plain characters.
        fn flush_type(run: &mut String, ran_any: &mut bool) {
            if run.is_empty() {
                return;
            }
            let ok = Command::new("xdotool")
                .arg("type")
                .arg(std::mem::take(run))
                .status()
                .map(|status| status.success())
                .unwrap_or(false);
            *ran_any |= ok;
        }

        /// Synthesize one named-key or modified-character stroke.
        fn press(stroke: &Keystroke, ran_any: &mut bool) {
            let mut parts: Vec<String> = Vec::new();
            if stroke.shift {
                parts.push("shift".into());
            }
            if stroke.ctrl {
                parts.push("ctrl".into());
            }
            if stroke.alt {
                parts.push("alt".into());
            }
            parts.push(xdotool_key_name(stroke.key));
            let ok = Command::new("xdotool")
                .arg("key")
                .arg("--clearmodifiers")
                .arg(parts.join("+"))
                .status()
                .map(|status| status.success())
                .unwrap_or(false);
            *ran_any |= ok;
        }

        if headless() {
            return false;
        }

        let mut ran_any = false;
        let mut text_run = String::new();
        for stroke in &request.strokes {
            if let SendKey::Char(c) = stroke.key {
                if !stroke.shift && !stroke.ctrl && !stroke.alt {
                    // Plain typing accumulates so one `type` call carries
                    // the whole run.
                    text_run.push(c);
                    continue;
                }
            }
            flush_type(&mut text_run, &mut ran_any);
            press(stroke, &mut ran_any);
        }
        flush_type(&mut text_run, &mut ran_any);
        ran_any
    }

    /// Keysym spelling of a decoded key for `xdotool key`.
    ///
    /// Printable ASCII doubles as its own keysym name; other characters use
    /// xdotool's `Uxxxx` codepoint form; named keys use their X keysyms.
    fn xdotool_key_name(key: SendKey) -> String {
        match key {
            SendKey::Char(' ') => "space".into(),
            SendKey::Char('\t') => "Tab".into(),
            SendKey::Char('\n' | '\r') => "Return".into(),
            SendKey::Char(c) if c.is_ascii_graphic() => c.to_string(),
            SendKey::Char(c) => format!("U{:04x}", c as u32),
            SendKey::Backspace => "BackSpace".into(),
            SendKey::Break => "Break".into(),
            SendKey::CapsLock => "Caps_Lock".into(),
            SendKey::Delete => "Delete".into(),
            SendKey::Down => "Down".into(),
            SendKey::End => "End".into(),
            SendKey::Enter => "Return".into(),
            SendKey::Esc => "Escape".into(),
            SendKey::Help => "Help".into(),
            SendKey::Home => "Home".into(),
            SendKey::Insert => "Insert".into(),
            SendKey::Left => "Left".into(),
            SendKey::NumLock => "Num_Lock".into(),
            SendKey::PageDown => "Next".into(),
            SendKey::PageUp => "Prior".into(),
            SendKey::PrintScreen => "Print".into(),
            SendKey::Right => "Right".into(),
            SendKey::ScrollLock => "Scroll_Lock".into(),
            SendKey::Tab => "Tab".into(),
            SendKey::Up => "Up".into(),
            SendKey::Function(n) => format!("F{n}"),
        }
    }
}

/// Shell process creation shared by Linux and macOS.
///
/// POSIX has no single-command-line spawn: the program and its arguments
/// are separate. VB6 programs are written against Windows' command-line
/// conventions, so this module splits the line itself (double quotes
/// honored) before spawning.
#[cfg(unix)]
mod posix {
    use std::process::{Command, Stdio};

    use super::super::shell::ShellRequest;

    /// Spawn `request.pathname` detached and return its process id.
    ///
    /// The child runs in its own process group so it outlives our signal
    /// delivery; its standard streams are disconnected because VB6's Shell
    /// offers no way to capture them anyway; and a background thread reaps
    /// the exit status so short-lived programs do not linger as zombies
    /// while a host keeps running. The requested window style has no POSIX
    /// equivalent and is ignored, mirroring how `InputBox` ignores
    /// unsupported positioning.
    pub(super) fn spawn_process(request: &ShellRequest) -> std::io::Result<f64> {
        let (program, arguments) = split_command_line(&request.pathname);
        let mut command = Command::new(program);
        command.args(arguments);
        command
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null());

        use std::os::unix::process::CommandExt;
        command.process_group(0);

        let mut child = command.spawn()?;
        let pid = child.id();

        // Shell never waits (VB6 launches asynchronously), but an unreaped
        // child would hold a zombie entry until the interpreter exits.
        std::thread::spawn(move || {
            let _ = child.wait();
        });
        Ok(f64::from(pid))
    }

    /// Split a command line into its program and arguments.
    ///
    /// Whitespace separates tokens unless enclosed in double quotes; quote
    /// characters themselves do not reach the argument values. An empty or
    /// all-whitespace line yields an empty program name, which the spawn
    /// then reports as "file not found" — the same error real VB6 raises
    /// for `Shell ""`.
    pub(super) fn split_command_line(line: &str) -> (String, Vec<String>) {
        let mut tokens: Vec<String> = Vec::new();
        let mut current = String::new();
        let mut in_quotes = false;
        let mut token_started = false;
        for ch in line.chars() {
            match ch {
                '"' => {
                    in_quotes = !in_quotes;
                    token_started = true;
                }
                c if c.is_whitespace() && !in_quotes => {
                    if token_started {
                        tokens.push(std::mem::take(&mut current));
                        token_started = false;
                    }
                }
                c => {
                    current.push(c);
                    token_started = true;
                }
            }
        }
        if token_started {
            tokens.push(current);
        }
        if tokens.is_empty() {
            return (String::new(), Vec::new());
        }

        let program = tokens.drain(..1).next().unwrap_or_default();
        (program, tokens)
    }
}

/// Compose the message for a one-button (`alert`) or first-step
/// (`confirm`) browser dialog: browsers have no title bar, so the title is
/// prepended to the prompt.
#[cfg_attr(
    not(target_arch = "wasm32"),
    allow(dead_code) // exercised by tests; consumed by the wasm32 backend
)]
fn browser_message(title: Option<&str>, prompt: &str) -> String {
    match title {
        Some(title) => format!("{title}\n\n{prompt}"),
        None => prompt.to_string(),
    }
}

/// Compose the message for a three-button dialog's second `confirm` step.
///
/// Browsers only offer OK/Cancel, so a tri-state VB6 dialog (Yes/No/Cancel,
/// Abort/Retry/Ignore) becomes two confirms; this step's text spells out
/// which choice maps to which button so the flow stays understandable.
#[cfg_attr(
    not(target_arch = "wasm32"),
    allow(dead_code) // exercised by tests; consumed by the wasm32 backend
)]
fn browser_secondary_message(
    title: Option<&str>,
    prompt: &str,
    second: &str,
    third: &str,
) -> String {
    format!(
        "{}\n\n(OK = {second}, Cancel = {third})",
        browser_message(title, prompt)
    )
}

#[cfg(target_arch = "wasm32")]
mod wasm {
    use wasm_bindgen::prelude::*;

    use super::super::inputbox::InputBoxRequest;
    use super::super::msgbox::{MsgBoxButton, MsgBoxRequest};
    use super::{browser_message, browser_secondary_message};

    #[wasm_bindgen]
    extern "C" {
        /// The browser's modal message dialog (OK button only).
        #[wasm_bindgen(js_namespace = window)]
        fn alert(message: &str);

        /// The browser's modal OK/Cancel question dialog.
        #[wasm_bindgen(js_namespace = window, js_name = confirm)]
        fn window_confirm(message: &str) -> bool;

        /// The browser's modal text-input dialog (`None` = Cancel).
        #[wasm_bindgen(js_namespace = window, js_name = prompt)]
        fn window_prompt(message: &str, default_value: &str) -> Option<String>;
    }

    /// Show the dialog with browser primitives and map the answer back.
    ///
    /// One offered button maps to `alert`; two map onto `confirm`'s
    /// OK/Cancel; three run a chained pair of confirms (first button vs.
    /// the rest, then second vs. third). Icons, default-button placement,
    /// and modality have no browser equivalent and are ignored.
    pub(super) fn display_dialog(request: &MsgBoxRequest) -> MsgBoxButton {
        let title = request.title.as_deref();
        let prompt = request.prompt.as_str();
        let offered = request.offered_buttons();

        match offered {
            [only] => {
                alert(&browser_message(title, prompt));
                *only
            }
            [first, second] => {
                if window_confirm(&browser_message(title, prompt)) {
                    *first
                } else {
                    *second
                }
            }
            [first, second, third] => {
                if window_confirm(&browser_message(title, prompt)) {
                    *first
                } else if window_confirm(&browser_secondary_message(
                    title,
                    prompt,
                    second.name(),
                    third.name(),
                )) {
                    *second
                } else {
                    *third
                }
            }
            _ => request.default_button_value(),
        }
    }

    /// Show the input box with the browser's `prompt` primitive.
    ///
    /// Browsers have no title bar, so the title is prepended to the message;
    /// they also cannot position dialogs, so `xpos`/`ypos` are ignored.
    /// Cancel (`null` from `prompt`) reads as the empty string, matching
    /// VB6.
    pub(super) fn prompt_dialog(request: &InputBoxRequest) -> Option<String> {
        let message = browser_message(request.title.as_deref(), &request.prompt);
        window_prompt(&message, &request.default_response)
    }
}

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

    #[test]
    fn command_args_skips_program_name() {
        // We can't control std::env::args() in a unit test, but we can
        // verify the method doesn't panic and returns a Vec.
        let backend = NativeBackend::new();
        let _args = backend.command_args();
    }

    #[test]
    fn do_events_returns_zero() {
        let backend = NativeBackend::new();
        assert_eq!(backend.do_events(), 0);
    }

    #[test]
    fn fallback_answers_default_button() {
        let request = MsgBoxRequest::parse("headless?", 4 + 32 + 256).unwrap();
        assert_eq!(fallback(&request), MsgBoxButton::No);
    }

    #[test]
    fn input_fallback_answers_default_response() {
        let request = InputBoxRequest::new("headless?").with_default("42");
        assert_eq!(input_fallback(&request), "42");
    }

    #[test]
    fn no_such_window_is_error_5_describing_the_title() {
        let err = no_such_window("Ghost Window");
        assert_eq!(err.number, err_number::INVALID_PROCEDURE_CALL);
        assert!(
            err.description.contains("Ghost Window"),
            "{}",
            err.description
        );
    }

    #[test]
    fn app_activate_does_not_panic() {
        // Exercises whatever path this platform provides (real window
        // facility, logging fallback) without asserting on OS state.
        let backend = NativeBackend::new();
        let _ = backend.app_activate(&AppActivateRequest::new(
            "definitely-not-a-real-window-title-42",
        ));
    }

    #[test]
    fn send_keys_does_not_panic() {
        // Exercises whatever path this platform provides (real input
        // injector, logging fallback) without asserting on OS state.
        let backend = NativeBackend::new();
        backend
            .send_keys(
                &SendKeysRequest::parse("definitely-not-typed-anywhere-42{TAB}^c%{F4}", true)
                    .unwrap(),
            )
            .unwrap();
    }

    #[test]
    #[cfg(unix)]
    fn shell_spawns_a_program_and_reports_its_task_id() {
        // `true` exists on every Unix CI runner and exits immediately.
        let task_id = launch(&ShellRequest::new("true")).unwrap();
        assert!(task_id > 0.0);
    }

    #[test]
    #[cfg(unix)]
    fn shell_missing_program_is_file_not_found() {
        let err = NativeBackend::new()
            .shell(&ShellRequest::new("definitely-not-a-program-42"))
            .unwrap_err();
        assert_eq!(err.number, err_number::FILE_NOT_FOUND);
        assert!(err.description.contains("definitely-not-a-program-42"));
    }

    #[test]
    #[cfg(unix)]
    fn command_line_splitting_honors_double_quotes() {
        let (program, args) = posix::split_command_line(
            r#""C:\Program Files\App.exe" /flag "my file.txt"   trailing"#,
        );
        assert_eq!(program, r"C:\Program Files\App.exe");
        assert_eq!(args, vec!["/flag", "my file.txt", "trailing"]);
    }

    #[test]
    #[cfg(unix)]
    fn empty_command_lines_split_to_an_empty_program() {
        let (program, args) = posix::split_command_line("   ");
        assert_eq!(program, "");
        assert!(args.is_empty());
    }

    #[test]
    fn browser_message_prepends_the_title() {
        assert_eq!(browser_message(None, "hi"), "hi");
        assert_eq!(browser_message(Some("App"), "hi"), "App\n\nhi");
    }

    #[test]
    fn browser_secondary_message_labels_both_choices() {
        let message = browser_secondary_message(Some("App"), "Overwrite?", "No", "Cancel");
        assert!(message.contains("App\n\nOverwrite?"));
        assert!(message.contains("(OK = No, Cancel = Cancel)"));
    }
}