ahk 0.3.2

The ahk language: a lexer, an AST, a parser and an interpreter for AutoHotkey-style scripts
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
//! The hotkeys of the script.
//!
//! The script registers the hotkeys it wants, and the runtime runs the
//! function of the one that was pressed. The desktop owns the watching of
//! the keyboard: the runtime asks it, between the statements of the
//! script, which hotkey was pressed, and the desktop answers with the
//! name of the hotkey it was given.
//!
//! The spelling of a hotkey is v2's: `^!+` for the modifiers, the name of
//! the key and the `Up` at the end. The cases at the end of this file pin
//! it, and the messages of the failures are the ones of v2.0.19, measured
//! on the binary on 2026-10-28.
use alloc::format;
use alloc::rc::Rc;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;
use core::cell::RefCell;

use crate::ast::Node;
use crate::desktop::WindowAnswer;
use crate::keys;
use crate::runtime::{Route, Runtime, RuntimeError, RuntimeFailure, Value};

/// The name of the environment variable that says which device to watch.
///
/// The device of the keyboard is found by itself when the variable is not
/// set: the box has one physical keyboard, and the devices of the machine
/// say which one it is. The variable is there for the measurement: a
/// script that types with `Send` fires its own hotkey when the watcher
/// reads the device that the box writes.
pub const DEVICE_VARIABLE: &str = "AHK_HOTKEY_DEVICE";

/// What an entry of the registry is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
    /// A hotkey: a key the script watches for.
    Hotkey,
    /// A hotstring: a text the script watches for.
    Hotstring,
    /// The state that the hotkeys of the script share.
    ///
    /// The entry is not a hotkey: it is there so that a script that sets a
    /// condition before it has a hotkey keeps the condition.
    State,
}

/// A hotkey of the script.
#[derive(Debug, Clone)]
pub struct Hotkey {
    /// The name of the hotkey, as the script spelled it.
    pub name: String,
    /// The function the hotkey runs.
    pub function: String,
    /// Whether the hotkey is on.
    pub enabled: bool,
    /// What the entry is.
    pub kind: Kind,
    /// The line the hotkey was registered on.
    pub line: u32,
    /// The object of the class, which the callback receives.
    pub object: Option<Value>,
    /// The state the hotkeys of the script share.
    pub shared: Rc<RefCell<Shared>>,
    /// The condition of the hotkey, set by `HotIf`.
    pub condition: Option<Condition>,
    /// Whether the callback of the hotkey takes the name of it.
    ///
    /// The callback of v2 always receives the name of the hotkey, and a
    /// callback that cannot take it is refused. The tree serves the two:
    /// a callback that takes nothing runs without the name.
    pub takes_name: bool,
    /// The action of a hotkey of the v1.
    ///
    /// Measured on the binary of AutoHotkey v1.1.37.02 on 2026-11-03: the
    /// v1 writes a hotkey in a line of its own, and the action of it is the
    /// label that comes after the line, or the command that the line
    /// carries. The action is the body of the hotkey, and it runs with the
    /// scope of the script.
    pub body: Option<Vec<Node>>,
}

/// The hotkey that is registered: what the script asked for.
pub struct Shape {
    /// Whether it is a hotkey or a hotstring.
    pub kind: Kind,
    /// The name of it, as the script spelled it.
    pub name: String,
    /// The function it runs.
    pub function: String,
    /// Whether the callback takes the name of it.
    pub takes_name: bool,
    /// The options of it.
    pub options: String,
    /// The object of the class, which the callback receives.
    pub object: Option<Value>,
}

/// The state the hotkeys of one script share.
///
/// The runtime has one registry of hotkeys and no room for anything else,
/// so the state that is not of one hotkey -- the hotkey that ran last, the
/// condition of the next one -- lives in the registry, and every entry
/// holds the same state.
#[derive(Debug, Default)]
pub struct Shared {
    /// The hotkey that ran last, and when it ran.
    pub prior: Option<(String, u64)>,
    /// The hotkey that is running, and when it started.
    pub current: Option<(String, u64)>,
    /// The condition of the next hotkey, set by `HotIf`.
    pub condition: Option<Condition>,
}

/// The condition of a hotkey.
///
/// `HotIf` sets the condition of the next hotkey that is registered, and
/// the window variants of it ask about a window. The question of a window
/// is asked when the hotkey is pressed, and not when the condition is
/// set: that is the way v2 does it, and the way a script that watches a
/// window expects it.
#[derive(Debug, Clone)]
pub enum Condition {
    /// The text of a condition, the way AHK writes it.
    ///
    /// The tree keeps the condition of a hotkey in one of the five forms it
    /// understands, and this is the text of it: the name of the function, or
    /// the window with the `WinActive` and the `WinExist` of v2.
    /// A function of the script: it is called when the hotkey is pressed.
    Function(String),
    /// The window with this title has to be the active one.
    WindowActive(String),
    /// The window with this title has to be there.
    WindowExists(String),
    /// The window with this title has not to be the active one.
    WindowNotActive(String),
    /// The window with this title has not to be there.
    WindowNotExist(String),
}
pub(crate) fn the_text_of_a_condition(condition: &Condition) -> String {
    match condition {
        Condition::Function(name) => name.clone(),
        Condition::WindowActive(title) => format!("WinActive(\"{}\")", title),
        Condition::WindowExists(title) => format!("WinExist(\"{}\")", title),
        Condition::WindowNotActive(title) => format!("!WinActive(\"{}\")", title),
        Condition::WindowNotExist(title) => format!("!WinExist(\"{}\")", title),
    }
}

/// The spelling of a hotkey: what the script wrote.
#[derive(Debug, Clone)]
pub struct Spec {
    /// The modifiers that have to be down, by the name the runtime uses.
    pub modifiers: Vec<String>,
    /// The name of the key.
    pub key: String,
    /// The code of the key, the way the events of the machine carry it.
    pub code: u16,
    /// Whether the hotkey is the key coming up.
    pub up: bool,
    /// Whether the hotkey fires in the middle of a word.
    pub tilde: bool,
    /// Whether the hotkey fires for any combination of the modifiers.
    pub custom: bool,
}

/// The spelling of a hotkey.
///
/// Measured on the binary of v2.0.19 on 2026-10-28: `^` is the control,
/// `!` the alt, `+` the shift and `#` the windows key, `<` and `>` say
/// which side of the key, `~` and `*` are the two prefixes, and the ` Up`
/// at the end is the key coming up. A name that is not a key is refused
/// with "Invalid key name.", and a spelling that is not one key with
/// "Invalid hotkey.".
pub fn parse(spec: &str) -> Result<Spec, String> {
    let mut modifiers: Vec<String> = Vec::new();
    let mut tilde = false;
    let mut custom = false;
    let mut rest = spec;
    // The prefixes and the modifiers are at the front.
    let mut marks: Vec<char> = Vec::new();
    while let Some(first) = rest.chars().next() {
        match first {
            '~' if modifiers.is_empty() && !tilde => {
                tilde = true;
                rest = &rest[1..];
            }
            '*' if modifiers.is_empty() && !custom => {
                custom = true;
                rest = &rest[1..];
            }
            // The $ of the spelling asks for the keyboard hook, and the
            // hook of the tree watches every key: the mark is taken and it
            // changes nothing.
            '$' if modifiers.is_empty() => {
                rest = &rest[1..];
            }
            '<' | '>' => {
                marks.push(first);
                rest = &rest[1..];
            }
            '^' | '!' | '+' | '#' => {
                marks.push(first);
                rest = &rest[1..];
            }
            _ => break,
        }
    }
    for (index, mark) in marks.iter().enumerate() {
        if !matches!(mark, '^' | '!' | '+' | '#') {
            continue;
        }
        let left = index > 0 && marks[index - 1] == '<';
        let right = index + 1 < marks.len() && marks[index + 1] == '>';
        for name in sides(*mark, left, right) {
            modifiers.push(name);
        }
    }
    // The ` Up` at the end is the key coming up. v2 has no ` Down`: the
    // spelling is refused with "Invalid hotkey.".
    let mut up = false;
    if rest.len() > 3 && rest[rest.len() - 3..].eq_ignore_ascii_case(" up") {
        up = true;
        rest = &rest[..rest.len() - 3];
    }
    // A lone modifier is the key itself: `^` is the control key.
    if rest.is_empty() {
        let Some(modifier) = modifiers.pop() else {
            return Err("Invalid key name.".to_string());
        };
        if modifiers.is_empty() {
            let code =
                keys::resolve_name(&modifier).map_err(|_| "Invalid key name.".to_string())?;
            return Ok(Spec {
                modifiers,
                key: modifier,
                code,
                up,
                tilde,
                custom,
            });
        }
        return Err("Invalid key name.".to_string());
    }
    if rest.contains(' ') {
        return Err("Invalid hotkey.".to_string());
    }
    let code = keys::resolve_name(rest).map_err(|_| "Invalid key name.".to_string())?;
    Ok(Spec {
        modifiers,
        key: rest.to_string(),
        code,
        up,
        tilde,
        custom,
    })
}

/// The names of the modifier, by the side of the key it is on.
///
/// The runtime names the four modifiers `ctrl`, `alt`, `shift` and `win`,
/// and the right ones have an `r` in front of them.
fn sides(marker: char, left: bool, right: bool) -> Vec<String> {
    let (name, right_name) = match marker {
        '^' => ("ctrl", "rctrl"),
        '!' => ("alt", "ralt"),
        '+' => ("shift", "rshift"),
        _ => ("win", "rwin"),
    };
    match (left, right) {
        (true, true) => vec![name.to_string(), right_name.to_string()],
        (true, false) => vec![name.to_string()],
        (false, true) => vec![right_name.to_string()],
        (false, false) => vec![name.to_string()],
    }
}

/// The text of a hotstring, when the name is one.
///
/// A hotstring of v2 is written between two of the same character, and
/// the character is not part of the text: `:btw:` is the text `btw`. The
/// text of a plain name is nothing, and the name is a hotkey.
pub fn hotstring_text(name: &str) -> Option<String> {
    let mut chars = name.chars();
    let first = chars.next()?;
    let last = name.chars().last()?;
    if first != last || first.is_alphanumeric() || name.chars().count() < 3 {
        return None;
    }
    let inner: String = name
        .chars()
        .skip(1)
        .take(name.chars().count() - 2)
        .collect();
    Some(inner)
}

/// The hotkey that was pressed, and the function that runs for it.
///
/// The desktop says which hotkey was pressed, and the runtime runs the
/// function of the script that the hotkey was registered with. The
/// callback of v2 receives the name of the hotkey, and the tree gives it
/// the same.
pub(crate) fn run_fired(rt: &mut Runtime<'_>) -> Result<(), RuntimeFailure> {
    // A script with no hotkey has nothing to run, and the desktop is not
    // asked at all: a desktop that cannot watch the keyboard is not a
    // failure of a script that wants no hotkey.
    if !rt.hotkeys().iter().any(|entry| entry.kind != Kind::State) {
        return Ok(());
    }
    let fired = match rt.desktop().fired_hotkey() {
        Ok(Some(name)) => name,
        Ok(None) => return Ok(()),
        Err(reason) => return Err(fail(&reason, 0)),
    };
    let Some(entry) = rt
        .hotkeys()
        .iter()
        .find(|entry| entry.matches(&fired))
        .cloned()
    else {
        return Ok(());
    };
    if !entry.enabled {
        return Ok(());
    }
    if !condition_holds(rt, &entry)? {
        return Ok(());
    }
    // The hotkey that ran last is the one that ran before this one, and
    // the time of it is when it started.
    {
        let mut shared = entry.shared.borrow_mut();
        shared.prior = shared.current.clone();
        shared.current = Some((entry.name.clone(), rt.now_ms()));
    }
    // The action of a hotkey of the v1 is the body that comes with it, and
    // it runs with the scope of the script and not with the scope of a
    // function of it.
    if let Some(body) = &entry.body {
        rt.run_the_body_of_a_hotkey(body)?;
        return Ok(());
    }
    if entry.takes_name {
        rt.call_named(
            &entry.function,
            &[Value::Text(fired)],
            entry.line,
            Route::Written,
        )?;
    } else {
        rt.call_function_by_name(&entry.function, entry.line)?;
    }
    Ok(())
}

/// The hotkey of the v1: the line that defines it, and its action.
///
/// Measured on the binary of AutoHotkey v1.1.37.02 on 2026-11-03: the hotkey
/// of the v1 is registered when the section of the script that runs reaches
/// it, and the action of it is the body that comes with it. The spelling of
/// the v1 is not the spelling of v2, and the desktop is the one that says
/// whether it can watch the key.
pub(crate) fn register_the_hotkey_of_the_v1(
    rt: &mut Runtime<'_>,
    name: &str,
    body: Vec<Node>,
    line: u32,
) -> Result<(), RuntimeFailure> {
    // The desktop watches the keyboard. A desktop that cannot watch says
    // so, and the script is told why: a hotkey that is registered and
    // never fires is a hotkey that does not work.
    rt.desktop()
        .register_hotkey(name)
        .map_err(|reason| fail(&reason, line))?;
    let shared = shared_of(rt);
    rt.hotkeys().push(Hotkey {
        name: name.to_string(),
        function: String::new(),
        enabled: true,
        kind: Kind::Hotkey,
        line,
        object: None,
        shared,
        condition: None,
        takes_name: false,
        body: Some(body),
    });
    Ok(())
}

/// The hotkey of the v2 that the script writes in a line of its own.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: `F1::MsgBox "hi"` is a
/// hotkey whose action is the statement of the line, and `F1::{ ... }` one
/// whose action is the block. A desktop that cannot watch the keyboard does
/// not make the script fail: the v2 has no failure of the load for it, and a
/// script of this tree is still a script -- the note says why the hotkey is
/// not there, and the rest of it runs.
pub(crate) fn register_the_hotkey_of_the_v2(
    rt: &mut Runtime<'_>,
    name: &str,
    body: Vec<Node>,
    line: u32,
    condition: Option<Condition>,
) -> Result<(), RuntimeFailure> {
    if let Err(reason) = rt.desktop().register_hotkey(name) {
        rt.note(format!(
            "the hotkey {name} is not watched on this desktop: {reason}"
        ));
        return Ok(());
    }
    let shared = shared_of(rt);
    rt.hotkeys().push(Hotkey {
        name: name.to_string(),
        function: String::new(),
        enabled: true,
        kind: Kind::Hotkey,
        line,
        object: None,
        shared,
        condition,
        takes_name: false,
        body: Some(body),
    });
    Ok(())
}

/// Whether the entry answers the name the desktop gave.
///
/// A hotkey answers to its own name, and a hotstring to the text that was
/// typed: the text of a hotstring is matched without its case, and the
/// name of the hotkey is not.
impl Hotkey {
    /// Whether the entry is the one the desktop named.
    fn matches(&self, fired: &str) -> bool {
        match self.kind {
            Kind::Hotstring => match hotstring_text(&self.name) {
                Some(text) => text.eq_ignore_ascii_case(fired),
                None => false,
            },
            _ => self.name == fired,
        }
    }
}

/// Whether the condition of the hotkey lets it run.
///
/// A question the machine cannot answer fails with the reason: a hotkey
/// that waits for a window the desktop cannot see does not run, and the
/// script is told why.
fn condition_holds(rt: &mut Runtime<'_>, entry: &Hotkey) -> Result<bool, RuntimeFailure> {
    let Some(condition) = entry.condition.clone() else {
        return Ok(true);
    };
    // The mode of the matching of the titles is a setting of the script,
    // and it is handed to the desktop with the question.
    let mode = crate::settings::title_match_mode();
    match condition {
        Condition::Function(name) => {
            let value = rt.call_named(&name, &[], entry.line, Route::Written)?;
            Ok(value.truthy())
        }
        Condition::WindowActive(title) => match rt.desktop().window_active(&title, mode) {
            Ok(WindowAnswer::Active) => Ok(true),
            // A window that is not there is not the active one.
            Ok(WindowAnswer::NotActive) | Ok(WindowAnswer::Absent) => Ok(false),
            Ok(WindowAnswer::Unknown(reason)) => Err(fail(&reason, entry.line)),
            Err(reason) => Err(fail(&reason, entry.line)),
        },
        Condition::WindowExists(title) => match rt.desktop().window_exists(&title, mode) {
            Ok(WindowAnswer::Active) | Ok(WindowAnswer::NotActive) => Ok(true),
            // A window that is not there is not there.
            Ok(WindowAnswer::Absent) => Ok(false),
            Ok(WindowAnswer::Unknown(reason)) => Err(fail(&reason, entry.line)),
            Err(reason) => Err(fail(&reason, entry.line)),
        },
        Condition::WindowNotActive(title) => match rt.desktop().window_active(&title, mode) {
            Ok(WindowAnswer::Active) => Ok(false),
            // A window that is not there is not the active one, and so it
            // is not active.
            Ok(WindowAnswer::NotActive) | Ok(WindowAnswer::Absent) => Ok(true),
            Ok(WindowAnswer::Unknown(reason)) => Err(fail(&reason, entry.line)),
            Err(reason) => Err(fail(&reason, entry.line)),
        },
        Condition::WindowNotExist(title) => match rt.desktop().window_exists(&title, mode) {
            Ok(WindowAnswer::Active) | Ok(WindowAnswer::NotActive) => Ok(false),
            // A window that is not there is not there.
            Ok(WindowAnswer::Absent) => Ok(true),
            Ok(WindowAnswer::Unknown(reason)) => Err(fail(&reason, entry.line)),
            Err(reason) => Err(fail(&reason, entry.line)),
        },
    }
}

/// Register a hotkey of the script.
///
/// The name is the spelling of the script, the function is the name of
/// the function of the script that the hotkey runs, and the object is the
/// one of the class, which the callback receives.
pub(crate) fn register(
    rt: &mut Runtime<'_>,
    shape: Shape,
    line: u32,
) -> Result<(), RuntimeFailure> {
    let Shape {
        kind,
        name,
        function,
        takes_name,
        options,
        object,
    } = shape;
    // The spelling has to be one that v2 accepts.
    match kind {
        Kind::Hotkey => {
            parse(&name).map_err(|reason| fail(&reason, line))?;
        }
        Kind::Hotstring => {
            if hotstring_text(&name).is_none() {
                return Err(fail("Parameter #1 of Hotstring is invalid.", line));
            }
        }
        Kind::State => {}
    }
    check_options(&options, line)?;
    // The options may turn the hotkey off, and a hotkey that is off is
    // not one the desktop watches.
    let mut enabled = true;
    for option in options.split_whitespace() {
        match option.to_lowercase().as_str() {
            "off" => enabled = false,
            "toggle" => enabled = !enabled,
            _ => {}
        }
    }
    // The desktop watches the keyboard. A desktop that cannot watch says
    // so, and the script is told why: a hotkey that is registered and
    // never fires is a hotkey that does not work.
    if enabled {
        rt.desktop()
            .register_hotkey(&name)
            .map_err(|reason| fail(&reason, line))?;
    }
    // The condition of `HotIf` belongs to the next hotkey, and not to the
    // one after it.
    let shared = shared_of(rt);
    let condition = shared.borrow_mut().condition.take();
    rt.hotkeys().push(Hotkey {
        name: name.clone(),
        function: function.clone(),
        enabled,
        kind,
        line,
        object,
        shared,
        condition,
        takes_name,
        body: None,
    });
    Ok(())
}

/// The state the hotkeys of the script share.
///
/// The registry keeps it in an entry of its own, so that a script that
/// sets a condition before it has a hotkey keeps the condition.
/// The condition that the script set with `HotIf`, when it set one.
///
/// The condition of the next hotkey lives in the state the hotkeys share,
/// and not in a hotkey: a script that sets a condition before it has a
/// hotkey keeps the condition.
pub(crate) fn the_condition_of_the_script(rt: &mut Runtime<'_>) -> Option<Condition> {
    shared_of(rt).borrow().condition.clone()
}
fn shared_of(rt: &mut Runtime<'_>) -> Rc<RefCell<Shared>> {
    if let Some(entry) = rt.hotkeys().iter().find(|entry| entry.kind == Kind::State) {
        return entry.shared.clone();
    }
    let shared = Rc::new(RefCell::new(Shared::default()));
    rt.hotkeys().push(Hotkey {
        name: String::new(),
        function: String::new(),
        enabled: false,
        kind: Kind::State,
        line: 0,
        object: None,
        shared: shared.clone(),
        condition: None,
        takes_name: false,
        body: None,
    });
    shared
}

/// The state the hotkeys of the script share, when there is one.
fn shared_state(rt: &mut Runtime<'_>) -> Option<Rc<RefCell<Shared>>> {
    rt.hotkeys()
        .iter()
        .find(|entry| entry.kind == Kind::State)
        .map(|entry| entry.shared.clone())
}

/// The options of a hotkey.
///
/// Measured on the binary of v2.0.19 on 2026-10-28: the letters are B, I,
/// P, S and T, a letter may carry a number, and the words On, Off and
/// Toggle turn the hotkey on and off. Anything else is "Parameter #3 of
/// Hotkey is invalid.".
pub(crate) fn check_options(options: &str, line: u32) -> Result<(), RuntimeFailure> {
    for option in options.split_whitespace() {
        let lowered = option.to_lowercase();
        if lowered == "on" || lowered == "off" || lowered == "toggle" {
            continue;
        }
        let mut rest = lowered.as_str();
        while !rest.is_empty() {
            let letter = rest.chars().next().unwrap_or(' ');
            rest = &rest[letter.len_utf8()..];
            let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
            rest = &rest[digits.len()..];
            let known = match letter {
                'b' | 'i' | 'p' | 's' => true,
                // The threads of a hotkey are a number, and not a letter.
                't' => !digits.is_empty(),
                _ => false,
            };
            if !known {
                return Err(fail("Parameter #3 of Hotkey is invalid.", line));
            }
        }
    }
    Ok(())
}

/// The function a hotkey runs.
///
/// The action of a hotkey is a function of the script, and v2 refuses
/// anything else: a text that is not one of the three words is
/// "Parameter #2 of Hotkey is invalid.", and a function that cannot take
/// the name of the hotkey is "Invalid callback function.".
///
/// Measured on the binary of v2.0.19 on 2026-10-28: `Hotkey "a", "b"`
/// is refused, and so is `Hotkey "a", "MyFunc"` when the script has such
/// a function.
pub(crate) fn action_of(value: &Value, line: u32) -> Result<(String, bool), RuntimeFailure> {
    let Value::Object(object) = value else {
        return Err(fail("Parameter #2 of Hotkey is invalid.", line));
    };
    let object = object.borrow();
    if object.class != "func" {
        return Err(fail("Parameter #2 of Hotkey is invalid.", line));
    }
    let builtin = object
        .value_of("builtin")
        .and_then(|value| value.to_number())
        .unwrap_or(0.0);
    if builtin != 0.0 {
        return Err(fail("Invalid callback function.", line));
    }
    let max = object
        .value_of("maxparams")
        .and_then(|value| value.to_number())
        .unwrap_or(0.0);
    // The callback of a hotkey receives the name of it, and it may not
    // take anything else.
    if max > 1.0 {
        return Err(fail("Invalid callback function.", line));
    }
    let name = object
        .value_of("name")
        .map(|value| value.to_text())
        .unwrap_or_default();
    Ok((name, max >= 1.0))
}

/// The action of a hotstring.
///
/// The action of a hotstring may also be a text: v2 takes the name of a
/// label of the script, and the tree has no labels -- the text is the name
/// of a function of the script, and a hotstring of a function that the
/// script does not have is a hotstring of nothing.
///
/// Measured on the binary of v2.0.19 on 2026-10-28: `Hotstring ":btw:",
/// "b"` is taken, and `Hotstring ":btw:", 123` is taken as well.
pub(crate) fn hotstring_action_of(
    value: &Value,
    line: u32,
) -> Result<(String, bool), RuntimeFailure> {
    match value {
        Value::Text(text) => Ok((text.clone(), false)),
        Value::Int(number) => Ok((number.to_string(), false)),
        other => action_of(other, line),
    }
}

/// The `Hotkey` command.
///
/// The command registers a hotkey: the key it watches for and the
/// function it runs. The class of the same name does the same thing and
/// gives the object of the hotkey back, and the runtime asks the class
/// types before it asks this table.
pub fn hotkey(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let name = text_argument(values.first(), "Parameter #1 of Hotkey is invalid.", line)?;
    // A hotkey without an action is a hotkey of nothing, and v2 says so.
    let Some(action) = values.get(1).cloned() else {
        return Err(RuntimeError {
            message: "Nonexistent hotkey.".to_string(),
            line,
        });
    };
    let options = match values.get(2) {
        Some(value) => value.to_text(),
        None => String::new(),
    };
    // The words On, Off and Toggle are not a function: they turn a
    // hotkey that is already there on and off.
    if let Value::Text(word) = &action {
        match word.to_lowercase().as_str() {
            "on" | "off" | "toggle" => {
                return toggle(rt, &name, word, line);
            }
            _ => {}
        }
    }
    let (function, takes_name) =
        action_of(&action, line).map_err(|failure| as_error(failure, line))?;
    let shape = Shape {
        kind: Kind::Hotkey,
        name,
        function,
        takes_name,
        options,
        object: None,
    };
    register(rt, shape, line).map_err(|failure| as_error(failure, line))?;
    Ok(Value::Text(String::new()))
}

/// Turn a hotkey that is already there on or off.
fn toggle(rt: &mut Runtime<'_>, name: &str, word: &str, line: u32) -> Result<Value, RuntimeError> {
    let lowered = word.to_lowercase();
    let Some(entry) = rt
        .hotkeys()
        .iter()
        .find(|entry| entry.name == name)
        .cloned()
    else {
        return Err(RuntimeError {
            message: "Nonexistent hotkey.".to_string(),
            line,
        });
    };
    let on = match lowered.as_str() {
        "on" => true,
        "off" => false,
        _ => !entry.enabled,
    };
    set_enabled(rt, &entry, on).map_err(|failure| as_error(failure, line))?;
    Ok(Value::Text(String::new()))
}

/// Turn a hotkey on or off, and tell the desktop about it.
///
/// A hotkey that is already in the state it is asked for is not told to
/// the desktop again: v2 starts a hotkey that is running, and it does
/// nothing.
pub(crate) fn set_enabled(
    rt: &mut Runtime<'_>,
    entry: &Hotkey,
    on: bool,
) -> Result<(), RuntimeFailure> {
    if entry.enabled == on {
        return Ok(());
    }
    if on {
        rt.desktop()
            .register_hotkey(&entry.name)
            .map_err(|reason| fail(&reason, entry.line))?;
    } else {
        rt.desktop()
            .unregister_hotkey(&entry.name)
            .map_err(|reason| fail(&reason, entry.line))?;
    }
    for hotkey in rt.hotkeys().iter_mut() {
        if hotkey.kind == entry.kind && hotkey.name == entry.name {
            hotkey.enabled = on;
        }
    }
    Ok(())
}

/// The `Hotstring` command.
///
/// A hotstring is a text that fires a function when it is typed. The text
/// of v2 is written between two of the same character, and the character
/// is not part of it.
pub fn hotstring(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let text = match values.first() {
        Some(Value::Text(text)) => text.clone(),
        Some(_) => {
            return Err(RuntimeError {
                message:
                    "Parameter #1 of Hotstring requires a String, but received something else."
                        .to_string(),
                line,
            });
        }
        None => {
            return Err(RuntimeError {
                message: "Parameter #1 of Hotstring is invalid.".to_string(),
                line,
            });
        }
    };
    // v2 says which parameter is wrong first, and the name of the
    // hotstring comes before the action: measured on the binary of
    // v2.0.19 on 2026-10-28, `Hotstring "btw", "b"` is "Parameter #1 of
    // Hotstring is invalid.".
    if hotstring_text(&text).is_none() {
        return Err(RuntimeError {
            message: "Parameter #1 of Hotstring is invalid.".to_string(),
            line,
        });
    }
    let options = match values.get(2) {
        Some(value) => value.to_text(),
        None => String::new(),
    };
    // A hotstring without an action runs nothing, and v2 takes it.
    let (function, takes_name) = match values.get(1) {
        Some(action) => {
            hotstring_action_of(action, line).map_err(|failure| as_error(failure, line))?
        }
        None => (String::new(), false),
    };
    let shape = Shape {
        kind: Kind::Hotstring,
        name: text,
        function,
        takes_name,
        options,
        object: None,
    };
    register(rt, shape, line).map_err(|failure| as_error(failure, line))?;
    Ok(Value::Text(String::new()))
}

/// The `HotIf` command.
///
/// The condition of a hotkey is a function of the script, and it is
/// called when the hotkey is pressed. The command without an argument
/// takes the condition away.
pub fn hotif(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let shared = shared_of(rt);
    match values.first() {
        None => {
            shared.borrow_mut().condition = None;
        }
        Some(value) => {
            let Value::Object(object) = value else {
                return Err(RuntimeError {
                    message: "Parameter #1 must match an existing #HotIf expression.".to_string(),
                    line,
                });
            };
            let object = object.borrow();
            if object.class != "func" {
                return Err(RuntimeError {
                    message: "Parameter #1 must match an existing #HotIf expression.".to_string(),
                    line,
                });
            }
            let name = object
                .value_of("name")
                .map(|value| value.to_text())
                .unwrap_or_default();
            shared.borrow_mut().condition = Some(Condition::Function(name));
        }
    }
    Ok(Value::Text(String::new()))
}

/// The `HotIfWin...` commands.
///
/// The variant says which window the condition is about: 0 is the active
/// one, 1 is a window that is there, 2 is the active one that must not
/// be there, and 3 is a window that must not be there.
pub fn hotif_window(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    variant: u8,
) -> Result<Value, RuntimeError> {
    let title = text_argument(
        values.first(),
        "Parameter #1 must match an existing #HotIf expression.",
        line,
    )?;
    let condition = match variant {
        0 => Condition::WindowActive(title),
        1 => Condition::WindowExists(title),
        2 => Condition::WindowNotActive(title),
        _ => Condition::WindowNotExist(title),
    };
    let shared = shared_of(rt);
    shared.borrow_mut().condition = Some(condition);
    Ok(Value::Text(String::new()))
}

/// The `GetKeyState` command.
///
/// The command says whether a key is down right now, and it takes the mode
/// of the state as its second parameter: "T" is the state of the toggle and
/// "P" the one of the key being down.
///
/// Measured on the binary of v2.0.19 on 2026-11-11: `GetKeyState("A")` and
/// `GetKeyState("A", "T")` and `GetKeyState("A", "P")` all answer 0, and a
/// mode that is neither "T" nor "P" throws "Parameter #2 of GetKeyState is
/// invalid." -- so the second parameter is carried, and only these two
/// words are right in it.
///
/// The three locks of a keyboard are the one case where the mode says
/// something new: `GetKeyState("CapsLock", "T")` answers the state of the
/// lamp -- one when the program turned it on with `SetCapsLockState("On")`
/// -- and `GetKeyState("CapsLock")` answers zero, because a lock key is
/// never down.
pub fn get_key_state(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    if values.len() > 2 {
        return Err(RuntimeError {
            message: "Parameter #2 of GetKeyState is invalid.".to_string(),
            line,
        });
    }
    let mode = values
        .get(1)
        .map(|value| value.to_text())
        .unwrap_or_default();
    let mode = mode.trim();
    if !mode.is_empty() && !mode.eq_ignore_ascii_case("T") && !mode.eq_ignore_ascii_case("P") {
        return Err(RuntimeError {
            message: "Parameter #2 of GetKeyState is invalid.".to_string(),
            line,
        });
    }
    let name = text_argument(
        values.first(),
        "Parameter #1 of GetKeyState is invalid.",
        line,
    )?;
    if keys::resolve_name(&name).is_err() {
        return Err(RuntimeError {
            message: "Parameter #1 of GetKeyState is invalid.".to_string(),
            line,
        });
    }
    // A lock: the lamp carries the state, and the key is never down.
    if let Some(lock) = the_lock_of(&name) {
        if mode.eq_ignore_ascii_case("T") {
            return match rt.desktop().lock_light(lock) {
                Ok(Some(on)) => Ok(Value::Int(on as i64)),
                // A desktop that does not know the lock leaves the state open.
                Ok(None) => Ok(Value::Int(0)),
                Err(reason) => Err(RuntimeError {
                    message: reason,
                    line,
                }),
            };
        }
        return Ok(Value::Int(0));
    }
    match rt.desktop().key_is_down(&name) {
        Ok(down) => Ok(Value::Int(down as i64)),
        Err(reason) => Err(RuntimeError {
            message: reason,
            line,
        }),
    }
}

/// The `KeyHistory` command.
///
/// The command of v2 opens a window with the keys that were pressed. The
/// box has no window to open, and the script is told why.
pub fn key_history(
    _rt: &mut Runtime<'_>,
    _values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    Err(RuntimeError {
        message:
            "this desktop cannot show the history of the keys: it has no window to show it in."
                .to_string(),
        line,
    })
}

/// The `ListHotkeys` command.
///
/// The command of v2 opens a window with the hotkeys of the script. The
/// box has no window to open, and the script is told why.
pub fn list_hotkeys(
    _rt: &mut Runtime<'_>,
    _values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    Err(RuntimeError {
        message:
            "this desktop cannot show the list of the hotkeys: it has no window to show it in."
                .to_string(),
        line,
    })
}

/// The `InstallKeybdHook` and `InstallMouseHook` commands.
///
/// The hooks of v2 are installed when a hotkey needs them, and the
/// commands say that they are there. The box watches the keyboard from
/// the first hotkey, and the mouse is not watched at all.
pub fn install_hook(
    _rt: &mut Runtime<'_>,
    _values: &[Value],
    _line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    Ok(Value::Text(String::new()))
}

/// The value of a built-in variable of the hotkeys.
///
/// The names are the ones of v2, without the `A_` that the table of the
/// variables of the runtime carries. The three numbers are the ones of
/// v2.0.19, measured on the binary on 2026-10-28.
pub fn variable(name: &str, rt: &mut Runtime<'_>) -> Option<Result<Value, RuntimeError>> {
    let spelled = name.to_lowercase();
    let name = spelled.strip_prefix("a_").unwrap_or(spelled.as_str());
    let value = match name {
        "hotkeyinterval" => Value::Int(2000),
        // Measured on the binary of v2.0.19 on 2026-11-01: the timeout of
        // the change of a hotkey is fifty until a script writes another
        // one. The name is `A_HotkeyModifierTimeout`: the tree had measured
        // a name that does not exist, and it said that the variable had no
        // value.
        "hotkeymodifiertimeout" => Value::Int(50),
        "maxhotkeysperinterval" => Value::Int(70),
        "priorhotkey" => match shared_state(rt) {
            Some(shared) => match &shared.borrow().prior {
                Some((name, _)) => Value::Text(name.clone()),
                None => Value::Text(String::new()),
            },
            None => Value::Text(String::new()),
        },
        // The tree does not keep the key that was pressed last, and v2
        // answers with an empty text until there is one.
        "priorkey" => Value::Text(String::new()),
        "thishotkey" => match shared_state(rt) {
            Some(shared) => match &shared.borrow().current {
                Some((name, _)) => Value::Text(name.clone()),
                None => Value::Text(String::new()),
            },
            None => Value::Text(String::new()),
        },
        "timesincepriorhotkey" => match shared_state(rt) {
            Some(shared) => {
                let shared = shared.borrow();
                match &shared.prior {
                    Some((_, when)) => Value::Int(rt.now_ms() as i64 - *when as i64),
                    None => Value::Text(String::new()),
                }
            }
            None => Value::Text(String::new()),
        },
        "timesincethishotkey" => match shared_state(rt) {
            Some(shared) => {
                let shared = shared.borrow();
                match &shared.current {
                    Some((_, when)) => Value::Int(rt.now_ms() as i64 - *when as i64),
                    None => Value::Text(String::new()),
                }
            }
            None => Value::Text(String::new()),
        },
        _ => return None,
    };
    Some(Ok(value))
}

/// The text of an argument, or the failure of v2.
fn text_argument(value: Option<&Value>, message: &str, line: u32) -> Result<String, RuntimeError> {
    match value {
        Some(Value::Text(text)) => Ok(text.clone()),
        _ => Err(RuntimeError {
            message: message.to_string(),
            line,
        }),
    }
}

/// A failure of a hotkey, with the message of v2.
fn fail(message: &str, line: u32) -> RuntimeFailure {
    RuntimeFailure::Error(RuntimeError {
        message: message.to_string(),
        line,
    })
}

/// A failure of a built-in, as the table of the built-ins wants it.
fn as_error(failure: RuntimeFailure, line: u32) -> RuntimeError {
    match failure {
        RuntimeFailure::Error(error) => error,
        RuntimeFailure::Detailed(error, _) => error,
        _ => RuntimeError {
            message: "the hotkey could not be registered.".to_string(),
            line,
        },
    }
}

/// The three locks of a keyboard, and the name of each of them.
fn the_lock_of(name: &str) -> Option<&'static str> {
    match name.trim().to_lowercase().as_str() {
        "capslock" => Some("CapsLock"),
        "numlock" => Some("NumLock"),
        "scrolllock" => Some("ScrollLock"),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::desktop::{
        Clipboard, Desktop, Dialogs, Files, Hotkeys, Keyboard, Machine, Native, Network, Pictures,
        Pointer, Processes, Screen, Sound, Timers, TitleMatch, WindowAnswer, Windows,
    };
    use crate::runtime::Clock;
    use alloc::string::String;
    use alloc::vec::Vec;
    use core::time::Duration;

    /// A desktop that says which hotkey was pressed.
    ///
    /// The fake fires the first hotkey it was given, once: that is what
    /// a keyboard does when a key is pressed.
    struct Fake {
        fired: bool,
        registered: Vec<String>,
        down: Vec<String>,
    }

    impl Fake {
        fn new() -> Self {
            Fake {
                fired: false,
                registered: Vec::new(),
                down: Vec::new(),
            }
        }
    }

    impl Keyboard for Fake {
        fn type_text(&mut self, text: &str) -> Result<String, String> {
            Ok(text.to_string())
        }

        fn press_key(&mut self, name: &str, _modifiers: &[String]) -> Result<String, String> {
            Ok(name.to_string())
        }

        fn key_is_down(&mut self, name: &str) -> Result<bool, String> {
            Ok(self.down.iter().any(|key| key == name))
        }
    }

    impl Pointer for Fake {
        fn click(
            &mut self,
            _x: i64,
            _y: i64,
            _button: &str,
            _count: u32,
        ) -> Result<String, String> {
            Ok(String::new())
        }
    }

    impl Screen for Fake {
        fn capture(
            &mut self,
            _x: i64,
            _y: i64,
            _w: i64,
            _h: i64,
            _filename: &str,
        ) -> Result<String, String> {
            Ok(String::new())
        }

        fn pixel(&mut self, _x: i64, _y: i64) -> Result<String, String> {
            Ok("#000000".to_string())
        }
    }

    impl Processes for Fake {
        fn run(&mut self, _command: &str, _window: &str) -> Result<(i32, String, String), String> {
            Ok((0, String::new(), String::new()))
        }
    }

    impl Windows for Fake {
        fn window_active(
            &mut self,
            _title: &str,
            _mode: TitleMatch,
        ) -> Result<WindowAnswer, String> {
            // The fake has no window at all: every window is absent.
            Ok(WindowAnswer::Absent)
        }
        fn window_exists(
            &mut self,
            _title: &str,
            _mode: TitleMatch,
        ) -> Result<WindowAnswer, String> {
            Ok(WindowAnswer::Absent)
        }
    }
    impl Files for Fake {}
    impl Clipboard for Fake {}
    impl Timers for Fake {}

    impl Hotkeys for Fake {
        fn register_hotkey(&mut self, name: &str) -> Result<String, String> {
            self.registered.push(name.to_string());
            Ok(name.to_string())
        }

        fn unregister_hotkey(&mut self, name: &str) -> Result<String, String> {
            Ok(name.to_string())
        }

        fn hotkeys(&mut self) -> Result<Vec<String>, String> {
            Ok(self.registered.clone())
        }

        fn fired_hotkey(&mut self) -> Result<Option<String>, String> {
            if self.fired {
                return Ok(None);
            }
            self.fired = true;
            Ok(self.registered.first().cloned())
        }
    }

    impl Native for Fake {}
    impl Desktop for Fake {}
    impl Pictures for Fake {}
    impl Network for Fake {}
    impl Sound for Fake {}
    impl Machine for Fake {}
    impl Dialogs for Fake {}

    /// A clock that does not move.
    struct TheClock;

    impl Clock for TheClock {
        fn now_ms(&self) -> u64 {
            0
        }

        fn sleep_ms(&mut self, _millis: u64) {}
    }

    /// The spelling of `^!a` is the two modifiers and the key.
    #[test]
    fn the_modifiers_are_read_from_the_front() {
        let spec = parse("^!a").unwrap();
        assert_eq!(spec.modifiers, vec!["ctrl".to_string(), "alt".to_string()]);
        assert_eq!(spec.key, "a");
        assert_eq!(spec.code, 30);
        assert!(!spec.up);
    }

    /// The shift is a `+` and the windows key is a `#`.
    #[test]
    fn the_shift_and_the_windows_key_are_read() {
        assert_eq!(
            parse("^+a").unwrap().modifiers,
            vec!["ctrl".to_string(), "shift".to_string()]
        );
        assert_eq!(parse("#a").unwrap().modifiers, vec!["win".to_string()]);
    }

    /// The `<` and the `>` say which side of the key the modifier is on.
    #[test]
    fn the_sides_of_the_modifiers_are_read() {
        assert_eq!(parse("<^a").unwrap().modifiers, vec!["ctrl".to_string()]);
        assert_eq!(parse("^>a").unwrap().modifiers, vec!["rctrl".to_string()]);
        assert_eq!(
            parse("<^>a").unwrap().modifiers,
            vec!["ctrl".to_string(), "rctrl".to_string()]
        );
    }

    /// The `~` and the `*` are the two prefixes, and they come first.
    #[test]
    fn the_prefixes_are_read() {
        let spec = parse("~^a").unwrap();
        assert!(spec.tilde);
        assert!(!spec.custom);
        let spec = parse("*^a").unwrap();
        assert!(spec.custom);
        assert!(!spec.tilde);
    }

    /// The ` Up` at the end is the key coming up.
    #[test]
    fn the_up_suffix_is_read() {
        let spec = parse("a Up").unwrap();
        assert!(spec.up);
        assert_eq!(spec.key, "a");
        let spec = parse("^a Up").unwrap();
        assert!(spec.up);
        assert_eq!(spec.modifiers, vec!["ctrl".to_string()]);
    }

    /// v2 has no ` Down`: the spelling is refused.
    #[test]
    fn the_down_suffix_is_refused() {
        assert_eq!(parse("a Down").unwrap_err(), "Invalid hotkey.");
    }

    /// A name that is not a key is refused.
    #[test]
    fn a_name_that_is_not_a_key_is_refused() {
        assert_eq!(parse("Foo").unwrap_err(), "Invalid key name.");
        assert_eq!(parse("").unwrap_err(), "Invalid key name.");
    }

    /// Two keys are not one hotkey.
    #[test]
    fn two_keys_are_refused() {
        assert_eq!(parse("a b").unwrap_err(), "Invalid hotkey.");
    }

    /// A lone modifier is the key itself.
    #[test]
    fn a_lone_modifier_is_the_key() {
        let spec = parse("^").unwrap();
        assert_eq!(spec.key, "ctrl");
        assert_eq!(spec.code, 29);
    }

    /// The options of v2 are the letters B, I, P, S and T, and the three
    /// words that turn a hotkey on and off.
    #[test]
    fn the_options_are_read() {
        assert!(check_options("B", 1).is_ok());
        assert!(check_options("S", 1).is_ok());
        assert!(check_options("P", 1).is_ok());
        assert!(check_options("I", 1).is_ok());
        assert!(check_options("T2", 1).is_ok());
        assert!(check_options("On", 1).is_ok());
        assert!(check_options("Off", 1).is_ok());
        assert!(check_options("Toggle", 1).is_ok());
        assert!(check_options("SS", 1).is_ok());
    }

    /// An option that v2 does not know is refused with its message.
    #[test]
    fn an_option_that_v2_does_not_know_is_refused() {
        let failure = check_options("X", 1).unwrap_err();
        let RuntimeFailure::Error(error) = failure else {
            panic!("the failure is not an error");
        };
        assert_eq!(error.message, "Parameter #3 of Hotkey is invalid.");
    }

    /// The text of a hotstring is between two of the same character.
    #[test]
    fn the_text_of_a_hotstring_is_read() {
        assert_eq!(hotstring_text(":btw:"), Some("btw".to_string()));
        assert_eq!(hotstring_text("abc"), None);
        assert_eq!(hotstring_text("~a~"), Some("a".to_string()));
        assert_eq!(hotstring_text("(a)"), None);
    }

    /// The name of a hotstring is checked before its action.
    #[test]
    fn the_name_of_a_hotstring_is_checked_before_its_action() {
        // Measured on the binary of v2.0.19 on 2026-10-28.
        let script = "Hotstring(\"btw\", \"b\")\n";
        let statements = crate::parse(script).expect("the script parses");
        let mut desktop = Fake::new();
        let mut clock = TheClock;
        let report =
            Runtime::with_clock(&mut desktop, &mut clock, Duration::from_secs(10)).run(&statements);
        assert!(!report.ok, "the script was expected to fail");
        assert_eq!(
            report.error.unwrap(),
            "Parameter #1 of Hotstring is invalid."
        );
    }

    /// The action of a hotstring may be a text: it is the name of a
    /// function of the script.
    #[test]
    fn the_action_of_a_hotstring_may_be_a_text() {
        let script = "Callback(hk) {\n    MsgBox hk\n}\nHotstring(\":btw:\", \"Callback\")\n";
        let statements = crate::parse(script).expect("the script parses");
        let mut desktop = Fake::new();
        let mut clock = TheClock;
        let report =
            Runtime::with_clock(&mut desktop, &mut clock, Duration::from_secs(10)).run(&statements);
        assert!(report.ok, "the script failed: {:?}", report.error);
        assert_eq!(desktop.registered, vec![":btw:".to_string()]);
    }

    /// A hotkey that is registered is watched by the desktop, and the
    /// function of the script runs when the hotkey is pressed.
    ///
    /// The callback of v2 receives the name of the hotkey, and the tree
    /// gives it the same.
    #[test]
    fn the_hotkey_that_was_pressed_runs_its_function() {
        let script = "Callback(hk) {\n    MsgBox hk\n}\nHotkey(\"^a\", Callback)\n";
        let statements = crate::parse(script).expect("the script parses");
        let mut desktop = Fake::new();
        let mut clock = TheClock;
        let report =
            Runtime::with_clock(&mut desktop, &mut clock, Duration::from_secs(10)).run(&statements);
        assert!(report.ok, "the script failed: {:?}", report.error);
        assert_eq!(desktop.registered, vec!["^a".to_string()]);
        assert_eq!(report.output, vec!["^a".to_string()]);
    }

    /// A script with no hotkey never asks the desktop about one.
    #[test]
    fn a_script_with_no_hotkey_asks_nothing() {
        let script = "MsgBox \"hello\"\n";
        let statements = crate::parse(script).expect("the script parses");
        let mut desktop = Fake::new();
        let mut clock = TheClock;
        let report =
            Runtime::with_clock(&mut desktop, &mut clock, Duration::from_secs(10)).run(&statements);
        assert!(report.ok, "the script failed: {:?}", report.error);
        assert!(desktop.registered.is_empty());
    }

    /// A window that is not there is not there: the hotkey that asks for
    /// it does not run.
    #[test]
    fn a_hotkey_of_a_window_that_is_not_there_does_not_run() {
        let script =
            "Callback(hk) {\n    MsgBox hk\n}\nHotIfWinExist \"Steam\"\nHotkey(\"^a\", Callback)\n";
        let statements = crate::parse(script).expect("the script parses");
        let mut desktop = Fake::new();
        let mut clock = TheClock;
        let report =
            Runtime::with_clock(&mut desktop, &mut clock, Duration::from_secs(10)).run(&statements);
        assert!(report.ok, "the script failed: {:?}", report.error);
        assert_eq!(desktop.registered, vec!["^a".to_string()]);
        assert!(
            report.output.is_empty(),
            "the hotkey ran: {:?}",
            report.output
        );
    }

    /// A window that is not there is not the active one, and so it is not
    /// active: the hotkey that asks for the opposite runs.
    #[test]
    fn a_hotkey_of_a_window_that_is_not_active_runs() {
        let script = "Callback(hk) {\n    MsgBox hk\n}\nHotIfWinNotActive \"Steam\"\nHotkey(\"^a\", Callback)\n";
        let statements = crate::parse(script).expect("the script parses");
        let mut desktop = Fake::new();
        let mut clock = TheClock;
        let report =
            Runtime::with_clock(&mut desktop, &mut clock, Duration::from_secs(10)).run(&statements);
        assert!(report.ok, "the script failed: {:?}", report.error);
        assert_eq!(report.output, vec!["^a".to_string()]);
    }

    /// The numbers of v2 are the ones the binary has.
    #[test]
    fn the_numbers_of_the_hotkeys_are_the_ones_of_v2() {
        let mut desktop = Fake::new();
        let mut clock = TheClock;
        let mut rt = Runtime::with_clock(&mut desktop, &mut clock, Duration::from_secs(10));
        assert_eq!(
            variable("hotkeyinterval", &mut rt).unwrap().unwrap(),
            Value::Int(2000)
        );
        assert_eq!(
            variable("maxhotkeysperinterval", &mut rt).unwrap().unwrap(),
            Value::Int(70)
        );
        // Measured on the binary of v2.0.19 on 2026-11-01: the timeout of
        // the change of a hotkey is fifty until a script writes another one.
        assert_eq!(
            variable("hotkeymodifiertimeout", &mut rt).unwrap().unwrap(),
            Value::Int(50)
        );
    }

    /// The variables of the hotkeys carry the state of the last one that
    /// ran.
    #[test]
    fn the_variables_carry_the_state_of_the_hotkeys() {
        let mut desktop = Fake::new();
        let mut clock = TheClock;
        let mut rt = Runtime::with_clock(&mut desktop, &mut clock, Duration::from_secs(10));
        // A script that has not run a hotkey has no hotkey to name.
        assert_eq!(
            variable("thishotkey", &mut rt).unwrap().unwrap(),
            Value::Text(String::new())
        );
        assert_eq!(
            variable("priorhotkey", &mut rt).unwrap().unwrap(),
            Value::Text(String::new())
        );
        assert_eq!(
            variable("timesincepriorhotkey", &mut rt).unwrap().unwrap(),
            Value::Text(String::new())
        );
        let shared = shared_of(&mut rt);
        shared.borrow_mut().current = Some(("^a".to_string(), 0));
        shared.borrow_mut().prior = Some(("a".to_string(), 0));
        assert_eq!(
            variable("thishotkey", &mut rt).unwrap().unwrap(),
            Value::Text("^a".to_string())
        );
        assert_eq!(
            variable("priorhotkey", &mut rt).unwrap().unwrap(),
            Value::Text("a".to_string())
        );
        assert_eq!(
            variable("timesincethishotkey", &mut rt).unwrap().unwrap(),
            Value::Int(0)
        );
    }
}