ahk 0.5.0

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
//! The commands of the v1 that the tree now carries.
//!
//! The v1 writes the answer of a command into the variable of the caller,
//! and the v2 answers with the value. The command of the v1 is therefore
//! the command of the v2 with the values of the caller and the answer
//! written into the first parameter.
//!
//! The failures of the v1 are not the failures of the v2. Measured on the
//! binary of v1.1.37.02 on 2026-11-14, the command that does not find
//! what it asks for is not a failure of the script: the variable of the
//! caller is empty, the `ErrorLevel` says whether the command did the
//! thing, and the script goes on.
//!
//! The `ErrorLevel` of each command is the one the binary gives, and it is
//! not the same for all of them:
//!
//! | the command | the `ErrorLevel` when the thing is not there |
//! | --- | --- |
//! | the `WinGetTitle`, the `WinGetClass`, the `WinGetPos` | zero |
//! | the `WinGetText`, the `ControlGetText`, the `ControlGetFocus` | one |
//! | the `RegRead`, the `ControlGet` | one |
//!
//! The names of the v1 that the v2 does not have are here too: the
//! `RegRead` of the v1 is a command that writes into a variable and the
//! `RegRead` of the v2 is a function that answers with the value, and the
//! `SysGet` of the v1 is a command with a sub-command where the `SysGet`
//! of the v2 is a command with a number.

use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;

use crate::builtins::{self, BuiltinHandler};
use crate::runtime::{Runtime, RuntimeError, Value};

pub(crate) use super::write_the_answer;

/// The answer of a command of the v1 that goes into the variable of the
/// caller, and the failure of it is a note and not a failure of the script.
///
/// The `ErrorLevel` is one when the command did not do the thing, and the
/// variable of the caller is empty.
fn the_answer_that_goes_on(
    rt: &mut Runtime<'_>,
    name: &str,
    values: &[Value],
    line: u32,
    answer: Result<Value, RuntimeError>,
    error_level: bool,
) -> Result<Value, RuntimeError> {
    match answer {
        Ok(value) => {
            write_the_answer(rt, name, values, 0, value.clone(), line)?;
            if error_level {
                rt.set_the_error_level(Value::Int(0));
            }
            Ok(value)
        }
        Err(failure) => {
            write_the_answer(rt, name, values, 0, Value::Text(String::new()), line)?;
            if error_level {
                rt.set_the_error_level(Value::Int(1));
            }
            rt.note(format!(
                "the command {name} did not do the thing: {}",
                failure.message
            ));
            Ok(Value::Text(String::new()))
        }
    }
}

/// The function of the v1 that calls the function of the v2 with the
/// values of the caller.
///
/// The failure of the v2 is the failure of the v1: a function of the v1
/// that cannot answer throws.
fn the_function_of_the_v2(
    rt: &mut Runtime<'_>,
    handler: BuiltinHandler,
    values: &[Value],
    line: u32,
) -> Result<Value, RuntimeError> {
    handler(rt, values, line, 0)
}

// -- the registry ----------------------------------------------------------------

/// `RegRead, OutputVar, KeyName, ValueName`: the value of the registry.
///
/// The `ErrorLevel` is one when the value is not there: measured on the
/// binary of v1.1.37.02 on 2026-11-14.
pub(crate) fn reg_read(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::reg_read(rt, values.get(1..).unwrap_or(&[]), line, 0);
    the_answer_that_goes_on(rt, "RegRead", values, line, answer, true)
}

/// `RegWrite, ValueType, KeyName, ValueName, Value`: write into the
/// registry.
///
/// The order of the parameters of the v1 is the value, the type, the key
/// and the name, and the order of the v2 is the type, the key, the name
/// and the value.
pub(crate) fn reg_write(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The v1: `RegWrite, ValueType, KeyName, ValueName, Value`.
    // The v2: `RegWrite(Value, ValueType, KeyName, ValueName)`.
    let mut reordered: Vec<Value> = Vec::with_capacity(values.len());
    reordered.push(values.get(4).cloned().unwrap_or(Value::Int(0)));
    reordered.push(values.first().cloned().unwrap_or(Value::Int(0)));
    reordered.push(values.get(1).cloned().unwrap_or(Value::Int(0)));
    reordered.push(values.get(2).cloned().unwrap_or(Value::Int(0)));
    let answer = builtins::reg_write(rt, &reordered, line, 0);
    match answer {
        Ok(value) => {
            rt.set_the_error_level(Value::Int(0));
            Ok(value)
        }
        Err(failure) => {
            rt.set_the_error_level(Value::Int(1));
            rt.note(format!(
                "the command RegWrite did not do the thing: {}",
                failure.message
            ));
            Ok(Value::Text(String::new()))
        }
    }
}

/// `RegDelete, KeyName, ValueName`: remove a value of the registry, or a
/// key of it.
///
/// The `ErrorLevel` is one when the thing is not there: measured on the
/// binary of v1.1.37.02 on 2026-11-14.
pub(crate) fn reg_delete(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::reg_delete(rt, values, line, 0);
    match answer {
        Ok(value) => {
            rt.set_the_error_level(Value::Int(0));
            Ok(value)
        }
        Err(failure) => {
            rt.set_the_error_level(Value::Int(1));
            rt.note(format!(
                "the command RegDelete did not do the thing: {}",
                failure.message
            ));
            Ok(Value::Text(String::new()))
        }
    }
}

// -- the screen ------------------------------------------------------------------

/// `SysGet, OutputVar, N`: a number of the screen.
///
/// The `SysGet` of the v1 has a sub-command, and the `SysGet` of the v2
/// has a number: the sub-command of the v1 is the question about the
/// monitors of the screen, and the v2 has a name for each one of them.
pub(crate) fn sys_get(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The v1: `SysGet, OutputVar, SubCommand, Value`.
    // The sub-command is the second parameter, and the number is the
    // third.
    let sub_command = values
        .get(1)
        .map(|value| value.to_text())
        .unwrap_or_default();
    let number = values.get(2).map(|value| value.to_text()).unwrap_or_default();
    let answer = the_answer_of_the_sub_command(rt, values, &sub_command, &number, line);
    the_answer_that_goes_on(rt, "SysGet", values, line, answer, false)
}

/// Write a value into a variable of the script, by its name.
///
/// The name of the variable of the caller is a name of the script, and the
/// scope of it is the one of the script that is running.
fn write_the_variable(rt: &mut Runtime<'_>, name: &str, value: Value) {
    rt.write_reference(
        &Value::Reference(crate::runtime::Reference {
            name: name.to_string(),
            scope: crate::runtime::Scope::Global,
            alias: true,
        }),
        value,
    );
}

/// The name of the variable of the caller that holds one of the four places
/// of a monitor: the name of the caller and the "Left", the "Top", the
/// "Right" or the "Bottom".
fn the_name_of_the_monitor_variable(values: &[Value], index: usize) -> String {
    let base = values
        .first()
        .map(|value| value.to_text())
        .unwrap_or_default();
    let suffix = match index {
        0 => "Left",
        1 => "Top",
        2 => "Right",
        _ => "Bottom",
    };
    format!("{base}{suffix}")
}

/// The answer of the sub-command of the `SysGet` of the v1.
fn the_answer_of_the_sub_command(
    rt: &mut Runtime<'_>,
    values: &[Value],
    sub_command: &str,
    number: &str,
    line: u32,
) -> Result<Value, RuntimeError> {
    match sub_command.to_ascii_lowercase().as_str() {
        "" => {
            // The v1 without a sub-command is the metric of the screen.
            let metric = number.trim().parse::<i64>().unwrap_or(0);
            builtins::sys_get(rt, &[Value::Int(metric)], line, 0)
        }
        // The number of a metric of the screen is a sub-command of the v1:
        // the `SysGet, out, 0` is the width of the screen. Measured on the
        // binary of v1.1.37.02 on 2026-11-14: the answer was "3840", and
        // the number of the metric is in the place of the sub-command.
        _ if sub_command.trim().parse::<i64>().is_ok() => {
            let metric = sub_command.trim().parse::<i64>().unwrap_or(0);
            builtins::sys_get(rt, &[Value::Int(metric)], line, 0)
        }
        "monitorcount" => builtins::monitor_get_count(rt, &[], line, 0),
        // The number of the primary monitor of the v1 is one-based: it is
        // always one on a machine with one monitor -- measured on the
        // binary of v1.1.37.02 on 2026-11-14. The number that the v2
        // answers counts from one too, so it is the number itself.
        "monitorprimary" => builtins::monitor_get_primary(rt, &[], line, 0),
        "monitor" | "monitorworkarea" => {
            // The v1 writes the four places into the four variables whose
            // names begin with the name of the caller: the "Mon2" of the
            // "SysGet, Mon2, Monitor, 2" is the "Mon2Left", the "Mon2Top",
            // the "Mon2Right" and the "Mon2Bottom".
            let index = number.trim().parse::<usize>().unwrap_or(1);
            let monitors = rt
                .desktop()
                .monitors()
                .map_err(|reason| builtins::desktop_failure(reason, line))?;
            let Some(monitor) = monitors.get(index.saturating_sub(1)) else {
                // The monitor that is not there leaves the four variables
                // of the caller blank.
                return Ok(Value::Text(String::new()));
            };
            let places = [
                Value::Int(monitor.left),
                Value::Int(monitor.top),
                Value::Int(monitor.right),
                Value::Int(monitor.bottom),
            ];
            for (index, place) in places.iter().enumerate() {
                let name = the_name_of_the_monitor_variable(values, index);
                write_the_variable(rt, &name, place.clone());
            }
            Ok(Value::Text(String::new()))
        }
        "monitorname" => builtins::monitor_get_name(rt, &[Value::Text(number.to_string())], line, 0),
        _ => Err(RuntimeError {
            message: format!("the sub-command {sub_command} of the SysGet is not known."),
            line,
        }),
    }
}

// -- the controls ----------------------------------------------------------------

/// `ControlGetText, OutputVar, Control, WinTitle, ...`: the text of a
/// control of a window.
///
/// The `ErrorLevel` is one when the control is not there: measured on the
/// binary of v1.1.37.02 on 2026-11-14.
pub(crate) fn control_get_text(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::control_get_text(rt, values.get(1..).unwrap_or(&[]), line, 0);
    the_answer_that_goes_on(rt, "ControlGetText", values, line, answer, true)
}

/// `ControlGetFocus, OutputVar, WinTitle, ...`: the control that has the
/// focus.
///
/// The `ErrorLevel` is one when there is no such control: measured on the
/// binary of v1.1.37.02 on 2026-11-14.
pub(crate) fn control_get_focus(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::control_get_focus(rt, values.get(1..).unwrap_or(&[]), line, 0);
    the_answer_that_goes_on(rt, "ControlGetFocus", values, line, answer, true)
}

/// `ControlGetPos, OutX, OutY, OutWidth, OutHeight, Control, ...`: the place
/// of a control of a window.
///
/// The `ErrorLevel` stays at zero when the control is not there, and the
/// four variables of the caller are empty: measured on the binary of
/// v1.1.37.02 on 2026-11-14.
pub(crate) fn control_get_pos(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The v2 writes into the four references of the caller, and the v1
    // gives it the four names of the variables of the caller as the four
    // references: the shape of the two is the same.
    let answer = builtins::control_get_pos(rt, values, line, 0);
    match answer {
        Ok(value) => Ok(value),
        Err(failure) => {
            for index in 0..4 {
                if values.get(index).is_some() {
                    write_the_answer(
                        rt,
                        "ControlGetPos",
                        values,
                        index,
                        Value::Text(String::new()),
                        line,
                    )?;
                }
            }
            rt.note(format!(
                "the command ControlGetPos did not do the thing: {}",
                failure.message
            ));
            Ok(Value::Text(String::new()))
        }
    }
}

/// `ControlClick, Control, WinTitle, ...`: click a control of a window.
pub(crate) fn control_click(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::control_act(rt, values, line, 0);
    the_answer_of_an_act(rt, "ControlClick", answer)
}

/// `ControlFocus, Control, WinTitle, ...`: give the focus to a control of
/// a window.
pub(crate) fn control_focus(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::control_act(rt, values, line, 1);
    the_answer_of_an_act(rt, "ControlFocus", answer)
}

/// `ControlMove, Control, X, Y, Width, Height, ...`: move a control of a
/// window.
pub(crate) fn control_move(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::control_move(rt, values, line, 0);
    the_answer_of_an_act(rt, "ControlMove", answer)
}

/// `ControlSend, Control, Keys, WinTitle, ...`: type into a control of a
/// window.
pub(crate) fn control_send(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::control_send(rt, values, line, 0);
    the_answer_of_an_act(rt, "ControlSend", answer)
}

/// `ControlSetText, Control, NewText, WinTitle, ...`: write the text of a
/// control of a window.
pub(crate) fn control_set_text(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::control_set_text(rt, values, line, 0);
    the_answer_of_an_act(rt, "ControlSetText", answer)
}

/// The answer of an act on a control of a window.
///
/// The `ErrorLevel` is one when the act did not happen.
fn the_answer_of_an_act(
    rt: &mut Runtime<'_>,
    name: &str,
    answer: Result<Value, RuntimeError>,
) -> Result<Value, RuntimeError> {
    match answer {
        Ok(value) => {
            rt.set_the_error_level(Value::Int(0));
            Ok(value)
        }
        Err(failure) => {
            rt.set_the_error_level(Value::Int(1));
            rt.note(format!(
                "the command {name} did not do the thing: {}",
                failure.message
            ));
            Ok(Value::Text(String::new()))
        }
    }
}

/// `ControlGet, OutputVar, SubCommand, ...`: a question about a control of
/// a window.
///
/// The `ErrorLevel` is one when the control is not there: measured on the
/// binary of v1.1.37.02 on 2026-11-14.
pub(crate) fn control_get(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let sub_command = values
        .get(1)
        .map(|value| value.to_text())
        .unwrap_or_default();
    // The control is the third parameter of the v1, and the window is
    // the fourth.
    let control = values.get(2).map(|value| value.to_text()).unwrap_or_default();
    let title = values.get(3).map(|value| value.to_text()).unwrap_or_default();
    let answer = the_answer_of_the_control(rt, &sub_command, &control, &title, line);
    the_answer_that_goes_on(rt, "ControlGet", values, line, answer, true)
}

/// The answer of the flag of a control: one for the flag that is set, zero
/// for the one that is not, and the failure of the v2 for the control that
/// is not there.
fn the_answer_of_the_flag(
    flag: crate::desktop::ControlFlag,
    line: u32,
) -> Result<Value, RuntimeError> {
    match flag {
        crate::desktop::ControlFlag::Yes => Ok(Value::Int(1)),
        crate::desktop::ControlFlag::No => Ok(Value::Int(0)),
        crate::desktop::ControlFlag::NoSuchWindow => Err(RuntimeError {
            message: builtins::TARGET_WINDOW.to_string(),
            line,
        }),
        crate::desktop::ControlFlag::NoSuchControl => Err(RuntimeError {
            message: builtins::TARGET_CONTROL.to_string(),
            line,
        }),
    }
}

/// The answer of the sub-command of the `ControlGet` of the v1.
fn the_answer_of_the_control(
    rt: &mut Runtime<'_>,
    sub_command: &str,
    control: &str,
    title: &str,
    line: u32,
) -> Result<Value, RuntimeError> {
    match sub_command.to_ascii_lowercase().as_str() {
        "enabled" => {
            let flag = rt
                .desktop()
                .control_enabled(control, title)
                .map_err(|reason| builtins::desktop_failure(reason, line))?;
            the_answer_of_the_flag(flag, line)
        }
        "visible" => {
            let flag = rt
                .desktop()
                .control_visible(control, title)
                .map_err(|reason| builtins::desktop_failure(reason, line))?;
            the_answer_of_the_flag(flag, line)
        }
        "style" => rt
            .desktop()
            .control_style(control, title, false)
            .map(Value::Int)
            .map_err(|reason| builtins::desktop_failure(reason, line)),
        "exstyle" => rt
            .desktop()
            .control_style(control, title, true)
            .map(Value::Int)
            .map_err(|reason| builtins::desktop_failure(reason, line)),
        "hwnd" => rt
            .desktop()
            .gui_number_named(control)
            .map(Value::Int)
            .map_err(|reason| builtins::desktop_failure(reason, line)),
        "list" => {
            let joined = rt
                .desktop()
                .gui_controls()
                .map_err(|reason| builtins::desktop_failure(reason, line))?;
            Ok(Value::Text(joined))
        }
        _ => Err(RuntimeError {
            message: format!("the sub-command {sub_command} of the ControlGet is not known."),
            line,
        }),
    }
}

// -- the groups ------------------------------------------------------------------

/// `GroupAdd, GroupName, WinTitle, ...`: put a window in a group.
pub(crate) fn group_add(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::group_add(rt, values, line, 0);
    the_answer_of_an_act(rt, "GroupAdd", answer)
}

/// `GroupActivate, GroupName, Mode`: activate the windows of a group.
pub(crate) fn group_activate(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::group_activate(rt, values, line, 0);
    the_answer_of_an_act(rt, "GroupActivate", answer)
}

/// `GroupClose, GroupName, Mode`: close the windows of a group.
pub(crate) fn group_close(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::group_close(rt, values, line, 0);
    the_answer_of_an_act(rt, "GroupClose", answer)
}

/// `GroupDeactivate, GroupName, Mode`: take the focus from the windows of
/// a group.
pub(crate) fn group_deactivate(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::group_close(rt, values, line, 0);
    the_answer_of_an_act(rt, "GroupDeactivate", answer)
}

// -- the files -------------------------------------------------------------------

/// `FileCreateShortcut, Target, LinkFile, ...`: make a shortcut.
pub(crate) fn file_create_shortcut(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::file_create_shortcut(rt, values, line, 0);
    the_answer_of_an_act(rt, "FileCreateShortcut", answer)
}

/// `FileGetShortcut, LinkFile, OutTarget, ...`: the pieces of a shortcut.
///
/// The `ErrorLevel` is one when the shortcut is not there: measured on
/// the binary of v1.1.37.02 on 2026-11-14.
pub(crate) fn file_get_shortcut(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::file_get_shortcut(rt, values, line, 0);
    match answer {
        Ok(value) => {
            rt.set_the_error_level(Value::Int(0));
            Ok(value)
        }
        Err(failure) => {
            rt.set_the_error_level(Value::Int(1));
            rt.note(format!(
                "the command FileGetShortcut did not do the thing: {}",
                failure.message
            ));
            Ok(Value::Text(String::new()))
        }
    }
}

/// `FileGetVersion, OutputVar, Filename`: the version of a program.
pub(crate) fn file_get_version(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::file_get_version(rt, values.get(1..).unwrap_or(&[]), line, 0);
    the_answer_that_goes_on(rt, "FileGetVersion", values, line, answer, false)
}

/// `FileRecycle, FilePattern`: send a file to the trash.
pub(crate) fn file_recycle(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::file_recycle(rt, values, line, 0);
    the_answer_of_an_act(rt, "FileRecycle", answer)
}

/// `FileRecycleEmpty, DriveLetter`: empty the trash.
pub(crate) fn file_recycle_empty(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::file_recycle_empty(rt, values, line, 0);
    the_answer_of_an_act(rt, "FileRecycleEmpty", answer)
}

// -- the sound -------------------------------------------------------------------

/// `SoundGet, OutputVar, ComponentType, ...`: a number of the sound.
pub(crate) fn sound_get(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The v1: `SoundGet, OutputVar, ComponentType, ControlType, DeviceNumber`.
    // The component is the second parameter, the control is the third and
    // the device is the fourth.
    let component = values
        .get(1)
        .map(|value| value.to_text())
        .unwrap_or_default();
    let control = values
        .get(2)
        .map(|value| value.to_text())
        .unwrap_or_default();
    let device = values.get(3).map(|value| value.to_text()).unwrap_or_default();
    let answer = rt
        .desktop()
        .sound_control(&component, &control, &device)
        .map(|answer| match answer {
            crate::desktop::SoundControl::Volume(volume) => Value::Float(volume),
            crate::desktop::SoundControl::Switch(on) => {
                Value::Text(if on { "On".into() } else { "Off".into() })
            }
        })
        .map_err(|failure| RuntimeError {
            message: failure.the_words_of_the_v1().to_string(),
            line,
        });
    // The `ErrorLevel` of the v1 is the phrase of the failure, and not
    // a number: measured on the binary of v1.1.37.02 on 2026-11-14.
    match answer {
        Ok(value) => {
            write_the_answer(rt, "SoundGet", values, 0, value.clone(), line)?;
            rt.set_the_error_level(Value::Int(0));
            Ok(value)
        }
        Err(failure) => {
            write_the_answer(rt, "SoundGet", values, 0, Value::Text(String::new()), line)?;
            rt.set_the_error_level(Value::Text(failure.message.clone()));
            rt.note(format!(
                "the command SoundGet did not do the thing: {}",
                failure.message
            ));
            Ok(Value::Text(String::new()))
        }
    }
}

/// `SoundSet, NewSetting, ComponentType, ...`: a number of the sound.
pub(crate) fn sound_set(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The v1: `SoundSet, NewSetting, ComponentType, ControlType, DeviceNumber`.
    // The setting is the first parameter, the component is the second, the
    // control is the third and the device is the fourth.
    let setting = values.first().map(|value| value.to_text()).unwrap_or_default();
    let component = values
        .get(1)
        .map(|value| value.to_text())
        .unwrap_or_default();
    let control = values
        .get(2)
        .map(|value| value.to_text())
        .unwrap_or_default();
    let device = values.get(3).map(|value| value.to_text()).unwrap_or_default();
    // The setting is a number of percent, and the mute of the v1 is the
    // word "On" or the number that is not zero.
    //
    // Measured on the binary of v1.1.37.02 on 2026-11-14: o v1 le o
    // ajuste com o `ATOF`, e por isso a palavra "On" e o zero -- o
    // `SoundSet, On, Master, Mute` deixa o mute desligado, e o
    // `SoundSet, 1, Master, Mute` liga o mute. E o `+` e o `-` na
    // frente do ajuste fazem o ajuste relatifo: o `+` liga o mute que
    // estava desligado, e o mute ligado vira desligado.
    let number = crate::v1::the_number_at_the_start_of_a_text(&setting)
        .and_then(|value| value.to_number())
        .unwrap_or(0.0);
    let answer = rt
        .desktop()
        .sound_control_is_set(&component, &control, number, &device)
        .map_err(|failure| RuntimeError {
            message: failure.the_words_of_the_v1().to_string(),
            line,
        });
    match answer {
        Ok(()) => {
            rt.set_the_error_level(Value::Int(0));
            Ok(Value::Text(String::new()))
        }
        Err(failure) => {
            rt.set_the_error_level(Value::Text(failure.message.clone()));
            rt.note(format!(
                "the command SoundSet did not do the thing: {}",
                failure.message
            ));
            Ok(Value::Text(String::new()))
        }
    }
}

/// `SoundGetWaveVolume, OutputVar, DeviceNumber`: the volume of the wave
/// of a device.
pub(crate) fn sound_get_wave_volume(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The v1: `SoundGetWaveVolume, OutputVar, DeviceNumber`.
    //
    // On Windows Vista and later the v1 says that the command is the
    // same as the `SoundGet, OutputVar, Wave, Volume`: measured on the
    // binary of v1.1.37.02 on 2026-11-14, the answer of the wave of a
    // machine that has no wave is the empty text and the `ErrorLevel` is
    // "Component Doesn't Support This Control Type".
    let device = values.get(1).map(|value| value.to_text()).unwrap_or_default();
    let answer = rt
        .desktop()
        .sound_control("wave", "volume", &device)
        .map(|answer| match answer {
            crate::desktop::SoundControl::Volume(volume) => Value::Float(volume),
            crate::desktop::SoundControl::Switch(on) => {
                Value::Text(if on { "On".into() } else { "Off".into() })
            }
        })
        .map_err(|failure| RuntimeError {
            message: failure.the_words_of_the_v1().to_string(),
            line,
        });
    match answer {
        Ok(value) => {
            write_the_answer(
                rt,
                "SoundGetWaveVolume",
                values,
                0,
                value.clone(),
                line,
            )?;
            rt.set_the_error_level(Value::Int(0));
            Ok(value)
        }
        Err(failure) => {
            write_the_answer(
                rt,
                "SoundGetWaveVolume",
                values,
                0,
                Value::Text(String::new()),
                line,
            )?;
            rt.set_the_error_level(Value::Text(failure.message.clone()));
            rt.note(format!(
                "the command SoundGetWaveVolume did not do the thing: {}",
                failure.message
            ));
            Ok(Value::Text(String::new()))
        }
    }
}

/// `SoundSetWaveVolume, Percent, DeviceNumber`: the volume of the wave of
/// a device.
pub(crate) fn sound_set_wave_volume(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The v1: `SoundSetWaveVolume, Percent, DeviceNumber`.
    //
    // On Windows Vista and later the v1 says that the command is the
    // same as the `SoundSet, Percent, Wave, Volume`: measured on the
    // binary of v1.1.37.02 on 2026-11-14, the `ErrorLevel` of a machine
    // that has no wave is "Can't Open Specified Mixer".
    let percent = values.first().map(|value| value.to_text()).unwrap_or_default();
    let device = values.get(1).map(|value| value.to_text()).unwrap_or_default();
    let number = crate::v1::the_number_at_the_start_of_a_text(&percent)
        .and_then(|value| value.to_number())
        .unwrap_or(0.0);
    let answer = rt
        .desktop()
        .sound_control_is_set("wave", "volume", number, &device)
        .map_err(|failure| RuntimeError {
            message: failure.the_words_of_the_v1().to_string(),
            line,
        });
    match answer {
        Ok(()) => {
            rt.set_the_error_level(Value::Int(0));
            Ok(Value::Text(String::new()))
        }
        Err(failure) => {
            rt.set_the_error_level(Value::Text(failure.message.clone()));
            rt.note(format!(
                "the command SoundSetWaveVolume did not do the thing: {}",
                failure.message
            ));
            Ok(Value::Text(String::new()))
        }
    }
}

// -- the drives -----------------------------------------------------------------

/// `DriveGet, OutputVar, SubCommand, Value`: a number of a drive.
pub(crate) fn drive_get(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The v1: `DriveGet, OutputVar, SubCommand, Value`.
    let sub_command = values
        .get(1)
        .map(|value| value.to_text())
        .unwrap_or_default();
    let drive = values.get(2).map(|value| value.to_text()).unwrap_or_default();
    let answer = match sub_command.to_ascii_lowercase().as_str() {
        "label" => builtins::drive_get_label(rt, &[Value::Text(drive)], line, 0),
        "serial" => builtins::drive_get_serial(rt, &[Value::Text(drive)], line, 0),
        "type" => builtins::drive_get_type(rt, &[Value::Text(drive)], line, 0),
        "capacity" => builtins::drive_get_capacity(rt, &[Value::Text(drive)], line, 0),
        "filesystem" => builtins::drive_get_filesystem(rt, &[Value::Text(drive)], line, 0),
        "list" => {
            let list = rt
                .desktop()
                .drive_list()
                .map_err(|reason| builtins::desktop_failure(reason, line))?;
            Ok(Value::Text(list.join("\n")))
        }
        _ => Err(RuntimeError {
            message: format!("the sub-command {sub_command} of the DriveGet is not known."),
            line,
        }),
    };
    the_answer_that_goes_on(rt, "DriveGet", values, line, answer, false)
}

/// `DriveSpaceFree, OutputVar, Path`: the space of a drive that is free.
pub(crate) fn drive_space_free(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::drive_get_space_free(rt, values.get(1..).unwrap_or(&[]), line, 0);
    the_answer_that_goes_on(rt, "DriveSpaceFree", values, line, answer, false)
}

// -- the processes ---------------------------------------------------------------

/// `Process, SubCommand, PIDOrName, Value`: a question about a process of
/// the machine.
pub(crate) fn process(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The v1: `Process, SubCommand, PIDOrName, Value`.
    let sub_command = values
        .first()
        .map(|value| value.to_text())
        .unwrap_or_default();
    let which = values.get(1).map(|value| value.to_text()).unwrap_or_default();
    let answer = match sub_command.to_ascii_lowercase().as_str() {
        "exist" => rt
            .desktop()
            .process_exist(Some(&which))
            .map(|pid| {
                if pid == 0 {
                    Value::Int(0)
                } else {
                    Value::Int(pid as i64)
                }
            })
            .map_err(|reason| builtins::desktop_failure(reason, line)),
        "close" => rt
            .desktop()
            .process_close(&which)
            .map(|pid| Value::Int(pid as i64))
            .map_err(|reason| builtins::desktop_failure(reason, line)),
        "priority" => {
            let level = values.get(2).map(|value| value.to_text()).unwrap_or_default();
            rt.desktop()
                .process_set_priority(&level, Some(&which))
                .map(|pid| match pid {
                    Some(pid) => Value::Int(pid as i64),
                    None => Value::Int(0),
                })
                .map_err(|reason| builtins::desktop_failure(reason, line))
        }
        "wait" => {
            let timeout = values.get(2).map(|value| value.to_text()).unwrap_or_default();
            let timeout = timeout.trim().parse::<f64>().ok();
            rt.desktop()
                .process_wait(&which, timeout)
                .map(|pid| Value::Int(pid as i64))
                .map_err(|reason| builtins::desktop_failure(reason, line))
        }
        "waitclose" => {
            let timeout = values.get(2).map(|value| value.to_text()).unwrap_or_default();
            let timeout = timeout.trim().parse::<f64>().ok();
            rt.desktop()
                .process_wait_close(&which, timeout)
                .map(|pid| Value::Int(pid as i64))
                .map_err(|reason| builtins::desktop_failure(reason, line))
        }
        _ => Err(RuntimeError {
            message: format!("the sub-command {sub_command} of the Process is not known."),
            line,
        }),
    };
    match answer {
        Ok(value) => {
            rt.set_the_error_level(Value::Int(0));
            Ok(value)
        }
        Err(failure) => {
            rt.set_the_error_level(Value::Int(1));
            rt.note(format!(
                "the command Process did not do the thing: {}",
                failure.message
            ));
            Ok(Value::Text(String::new()))
        }
    }
}

// -- the COM --------------------------------------------------------------------

/// `ComObjActive(CLSID)`: the COM object of a class.
pub(crate) fn com_obj_active(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_function_of_the_v2(rt, builtins::com_obj_active, values, line)
}

/// `ComObjConnect(ComObject, PrefixOrSink)`: the events of a COM object.
pub(crate) fn com_obj_connect(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_function_of_the_v2(rt, builtins::com_obj_connect, values, line)
}

/// `ComObjFlags(ComObject, NewFlags, Mask)`: the flags of a COM object.
pub(crate) fn com_obj_flags(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_function_of_the_v2(rt, builtins::com_obj_flags, values, line)
}

/// `ComObjGet(Name)`: the COM object of a name.
pub(crate) fn com_obj_get(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_function_of_the_v2(rt, builtins::com_obj_get, values, line)
}

/// `ComObjQuery(ComObject, SID, IID)`: the interface of a COM object.
pub(crate) fn com_obj_query(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_function_of_the_v2(rt, builtins::com_obj_query, values, line)
}

/// `ComObjType(ComObject, InfoType)`: what is known of a COM object.
pub(crate) fn com_obj_type(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_function_of_the_v2(rt, builtins::com_obj_type, values, line)
}

/// `ComObjValue(ComObject)`: the value of a COM object.
pub(crate) fn com_obj_value(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_function_of_the_v2(rt, builtins::com_obj_value, values, line)
}

// -- the text --------------------------------------------------------------------

/// `StrGet(Source, Length, Encoding)`: the text of a buffer.
pub(crate) fn str_get(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_function_of_the_v2(rt, builtins::str_get, values, line)
}

/// `StrPut(String, Target, Length, Encoding)`: the bytes of a text.
pub(crate) fn str_put(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_function_of_the_v2(rt, builtins::str_put, values, line)
}

// -- the script ------------------------------------------------------------------

/// `BlockInput, OnOff`: the input of the machine, blocked.
pub(crate) fn block_input(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::block_input(rt, values, line, 0);
    the_answer_of_an_act(rt, "BlockInput", answer)
}

/// `Edit`: open the script in an editor.
pub(crate) fn edit(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::edit(rt, values, line, 0);
    the_answer_of_an_act(rt, "Edit", answer)
}

/// `KeyHistory`: the keys that were pressed.
/// `KeyWait, key`: the v1 checks the name of the key before it waits.
///
/// Measured on the binary of v1.1.37.02: a name that is not a key is
/// "Parameter #1 invalid." with the name under it. The runtime that
/// cannot wait refuses only after the name is known to be a key.
pub(crate) fn key_wait(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    variant: u8,
) -> Result<Value, RuntimeError> {
    let name = values.first().map(|v| v.to_text()).unwrap_or_default();
    if crate::keys::resolve_name(&name).is_err() {
        return Err(RuntimeError {
            message: format!("Parameter #1 invalid.\n     Specifically: {name}"),
            line,
        });
    }
    builtins::key_wait(rt, values, line, variant)
}

pub(crate) fn key_history(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = crate::hotkeys::key_history(rt, values, line, 0);
    the_answer_of_an_act(rt, "KeyHistory", answer)
}

/// `ListHotkeys`: the hotkeys of the script.
pub(crate) fn list_hotkeys(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = crate::hotkeys::list_hotkeys(rt, values, line, 0);
    the_answer_of_an_act(rt, "ListHotkeys", answer)
}

/// `ListLines, OnOff`: the lines of the script, listed.
pub(crate) fn list_lines(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::list_lines(rt, values, line, 0);
    the_answer_of_an_act(rt, "ListLines", answer)
}

/// `ListVars`: the variables of the script, listed.
pub(crate) fn list_vars(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::list_vars(rt, values, line, 0);
    the_answer_of_an_act(rt, "ListVars", answer)
}

/// `OnMessage(MsgNumber, Callback, MaxThreads)`: a handler for a message.
pub(crate) fn on_message(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::on_message(rt, values, line, 0);
    the_answer_of_an_act(rt, "OnMessage", answer)
}

/// `OutputDebug, Text`: a line in the log of the debugger.
pub(crate) fn output_debug(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::output_debug(rt, values, line, 0);
    the_answer_of_an_act(rt, "OutputDebug", answer)
}

/// `Pause, OnOffToggle`: the script, paused.
pub(crate) fn pause(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::pause(rt, values, line, 0);
    the_answer_of_an_act(rt, "Pause", answer)
}

/// `PostMessage, Msg, wParam, lParam, Control, WinTitle`: a message to a
/// window.
///
/// The v1 writes the control before the title, and the built-in reads
/// the title in the fourth place: the parameters are put in the order
/// of the built-in, and the control is left out -- the message goes to
/// the window, not to a control of it.
pub(crate) fn post_message(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let mut ordered: Vec<Value> = values.iter().take(3).cloned().collect();
    if let Some(title) = values.get(4) {
        ordered.push(title.clone());
    }
    let answer = builtins::post_message(rt, &ordered, line, 0);
    the_answer_of_an_act(rt, "PostMessage", answer)
}

/// `Reload`: the script, run again.
pub(crate) fn reload(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::reload(rt, values, line, 0);
    the_answer_of_an_act(rt, "Reload", answer)
}

/// `RunAs, User, Password, Domain`: the script, run as another user.
pub(crate) fn run_as(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::run_as(rt, values, line, 0);
    the_answer_of_an_act(rt, "RunAs", answer)
}

/// `Shutdown, Flag`: the machine, shut down.
pub(crate) fn shutdown(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::shutdown(rt, values, line, 0);
    the_answer_of_an_act(rt, "Shutdown", answer)
}

/// `Suspend, OnOffToggle`: the script, suspended.
pub(crate) fn suspend(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::suspend(rt, values, line, 0);
    the_answer_of_an_act(rt, "Suspend", answer)
}

/// `Thread, SubCommand, Value1, Value2`: the thread of the script.
pub(crate) fn thread(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The v1: `Thread, SubCommand, Value1, Value2`.
    // The v2: `Thread(Priority)`.
    let sub_command = values
        .first()
        .map(|value| value.to_text())
        .unwrap_or_default();
    let answer = match sub_command.to_ascii_lowercase().as_str() {
        // The three settings of the thread are the ones of the v2: the
        // priority, the interrupt (the milliseconds and the lines) and
        // the NoTimers. The sub-command and its values go as they are.
        "priority" | "interrupt" | "notimers" => {
            builtins::thread_command(rt, values, line, 0)
        }
        _ => Err(RuntimeError {
            message: "Parameter #1 invalid.".to_string(),
            line,
        }),
    };
    match answer {
        Ok(value) => {
            rt.set_the_error_level(Value::Int(0));
            Ok(value)
        }
        Err(failure) => {
            rt.set_the_error_level(Value::Int(1));
            rt.note(format!(
                "the command Thread did not do the thing: {}",
                failure.message
            ));
            Ok(Value::Text(String::new()))
        }
    }
}

/// `ToolTip, Text, X, Y, WhichToolTip`: the tip of the mouse.
pub(crate) fn tool_tip(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::tooltip(rt, values, line, 0);
    the_answer_of_an_act(rt, "ToolTip", answer)
}

/// `TrayTip, Title, Text, Timeout, Options`: the tip of the tray.
pub(crate) fn tray_tip(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = crate::dialogs::tray_tip(rt, values, line, 0);
    the_answer_of_an_act(rt, "TrayTip", answer)
}

/// `StatusBarGetText, OutputVar, Part#, ...`: the text of a status bar.
pub(crate) fn status_bar_get_text(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::status_bar_get_text(rt, values.get(1..).unwrap_or(&[]), line, 0);
    the_answer_that_goes_on(rt, "StatusBarGetText", values, line, answer, false)
}

/// `StatusBarWait, BarText, Timeout, Part#, ...`: wait for a status bar.
pub(crate) fn status_bar_wait(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::status_bar_wait(rt, values, line, 0);
    the_answer_of_an_act(rt, "StatusBarWait", answer)
}