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
//! The families of the v1 that the v2 does not have.
//!
//! The v1 has some commands and functions that the v2 does not carry:
//! the `Gui` of the v1 is a command and not a class, the `Menu` of the v1
//! is a command and not a class, and the `ComObjCreate` and the
//! `ComObjArray` of the v1 are functions that the v2 does not have.
//!
//! Every one of them is answered here in the shape of the v1: the command
//! takes the parameters that the v1 takes, in the order that the v1 takes
//! them, and it writes the answer of the v1 into the variable of the
//! caller.
//!
//! The answers come from the same desktop that the v2 uses, so that the
//! two dialects agree about the machine.

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

use crate::runtime::{Runtime, RuntimeError, Value};

/// The answer of a command of the v1 that writes nothing.
///
/// The `Gui`, the `GuiControl`, the `Menu`, the `Progress`, the `Control`
/// and the `Drive` of the v1 write nothing: they have no variable of the
/// caller to write into, and the failure of them is a note and not a stop.
fn the_answer_of_an_act(
    rt: &mut Runtime<'_>,
    name: &str,
    answer: Result<Value, RuntimeError>,
) -> Result<Value, RuntimeError> {
    match answer {
        Ok(value) => Ok(value),
        Err(failure) => {
            rt.note(format!(
                "the command {name} did not do the thing: {}",
                failure.message
            ));
            Ok(Value::Text(String::new()))
        }
    }
}

/// The answer of a command of the v1 that goes into the variable of the
/// caller.
///
/// The `ErrorLevel` is the one that the v1 gives: the failure of a command
/// of the v1 is a note and not a stop, 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) => {
            crate::v1::commands::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) => {
            crate::v1::commands::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 COM of the machine ---------------------------------------------------------

/// `ComObjCreate(CLSID, IID)`: an object of the COM of the machine.
///
/// The v2 has no such function: it has the `ComObjGet` and the
/// `ComObjQuery`, and the object of a class of the machine is what this
/// asks for. Measured on the binary of v1.1.37.02 on 2026-11-14: the
/// `ComObjCreate` of a class that is not there throws.
pub(crate) fn com_obj_create(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let class = values
        .first()
        .map(|value| value.to_text())
        .unwrap_or_default();
    let interface = values.get(1).map(|value| value.to_text());
    let interface = interface.filter(|text| !text.is_empty());
    let object = rt
        .desktop()
        .com_object_of_the_class(&class, interface.as_deref())
        .map_err(|reason| RuntimeError {
            message: reason,
            line,
        })?;
    crate::classes::comvalue::construct_the_object(&[Value::Int(object.pointer as i64)], rt, line)
        .map_err(|failure| RuntimeError {
            message: crate::builtins::the_message_of(failure),
            line,
        })
}

/// `ComObjArray(VarType, Count1, ..., Count8)`: a `SafeArray` for the COM.
///
/// The v2 has no such function either. The desktop of the machine makes
/// the array of the COM, and the answer is the wrapper of it.
pub(crate) fn com_obj_array(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let kind = values
        .first()
        .map(|value| value.to_text())
        .unwrap_or_default()
        .trim()
        .parse::<i64>()
        .unwrap_or(0);
    let count = values
        .get(1)
        .map(|value| value.to_text())
        .unwrap_or_default()
        .trim()
        .parse::<f64>()
        .unwrap_or(0.0);
    let object = rt
        .desktop()
        .com_value_is_made(kind, crate::desktop::ComValue::Number(count))
        .map_err(|reason| RuntimeError {
            message: reason,
            line,
        })?;
    crate::classes::comvalue::construct_the_object(&[Value::Int(object.pointer as i64)], rt, line)
        .map_err(|failure| RuntimeError {
            message: crate::builtins::the_message_of(failure),
            line,
        })
}

/// `ComObjError(Enable)`: whether the errors of the COM are raised.
///
/// The v1 has the setting, and the v2 does not: the v2 always raises the
/// errors of the COM.
pub(crate) fn com_obj_error(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    _line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The setting of the runtime is the one that the v1 answers, and the
    // value that is given is the one that goes into it.
    let before = crate::settings::com_obj_error();
    if let Some(setting) = values.first() {
        let on = match setting {
            Value::Int(number) => *number != 0,
            Value::Float(number) => *number != 0.0,
            other => !other.to_text().is_empty(),
        };
        crate::settings::set_com_obj_error(on);
    }
    Ok(Value::Int(if before { 1 } else { 0 }))
}

// -- the control of a window --------------------------------------------------------

/// `Control, SubCommand, Value, Control, WinTitle, ...`: a change in a
/// control of a window.
///
/// The v2 has a built-in for each one of the changes: the `ControlSetText`
/// and the `ControlSetEnabled` and the `ControlHide` and the
/// `ControlShow`. The v1 puts them all under one command, and the
/// sub-command says which one is meant.
pub(crate) fn control(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The v1: `Control, SubCommand, Value, Control, WinTitle, ...`.
    let sub_command = value_of(values, 0);
    let value = value_of(values, 1);
    let control = value_of(values, 2);
    let title = value_of(values, 3);
    // The v2 wants the control first and the window after it.
    let mut rest: Vec<Value> = vec![Value::Text(control.clone()), Value::Text(title.clone())];
    rest.extend(values.iter().skip(4).cloned());
    let answer = match sub_command.to_ascii_lowercase().as_str() {
        "enable" => crate::builtins::control_set_enabled(rt, &rest, line, 0),
        "disable" => crate::builtins::control_set_enabled(rt, &rest, line, 0),
        "hide" => crate::builtins::control_visibility(rt, &rest, line, 0),
        "show" => crate::builtins::control_show(rt, &rest, line, 0),
        "focus" => crate::builtins::control_act(rt, &rest, line, 1),
        "move" => crate::builtins::control_move(rt, &rest, line, 0),
        "click" => crate::builtins::control_act(rt, &rest, line, 0),
        "send" => crate::builtins::control_send(rt, &rest, line, 0),
        "sendtext" => crate::builtins::control_send_text(rt, &rest, line, 0),
        "style" => crate::builtins::control_style(rt, &rest, line, 0),
        "exstyle" => crate::builtins::control_style(rt, &rest, line, 1),
        "showdropdown" => crate::builtins::control_show_drop_down(rt, &rest, line, 0),
        "hidedropdown" => crate::builtins::control_hide_drop_down(rt, &rest, line, 0),
        "check" => crate::builtins::control_set_checked(rt, &rest, line, 0),
        "uncheck" => crate::builtins::control_set_checked(rt, &rest, line, 0),
        _ => Err(RuntimeError {
            message: format!("the sub-command {sub_command} of the Control is not known."),
            line,
        }),
    };
    // The v1 puts the value of the change in the second parameter, and the
    // v2 wants it after the control and the window.
    let answer = match sub_command.to_ascii_lowercase().as_str() {
        "enable" | "disable" | "check" | "uncheck" => {
            let mut with_value = rest.clone();
            with_value.insert(0, Value::Text(value.clone()));
            match sub_command.to_ascii_lowercase().as_str() {
                "enable" => crate::builtins::control_set_enabled(rt, &with_value, line, 0),
                "disable" => crate::builtins::control_set_enabled(rt, &with_value, line, 0),
                "check" => crate::builtins::control_set_checked(rt, &with_value, line, 0),
                _ => crate::builtins::control_set_checked(rt, &with_value, line, 0),
            }
        }
        _ => answer,
    };
    the_answer_of_an_act(rt, "Control", answer)
}

// -- the drive of the machine -------------------------------------------------------

/// `Drive, SubCommand, Value1, Value2`: the drive of the machine.
///
/// The v2 has a built-in for each one of the changes: the `DriveSetLabel`
/// and the `DriveLock` and the `DriveUnlock` and the `DriveEject` and the
/// `DriveRetract`.
pub(crate) fn drive(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The v1: `Drive, SubCommand, Value1, Value2`.
    let sub_command = value_of(values, 0);
    let value = value_of(values, 1);
    let answer = match sub_command.to_ascii_lowercase().as_str() {
        "label" => crate::builtins::drive_set_label(rt, &[Value::Text(value)], line, 0),
        "lock" => crate::builtins::drive_lock(rt, &[Value::Text(value)], line, 0),
        "unlock" => crate::builtins::drive_unlock(rt, &[Value::Text(value)], line, 0),
        "eject" => crate::builtins::drive_eject(rt, &[Value::Text(value)], line, 0),
        "retract" => crate::builtins::drive_retract(rt, &[Value::Text(value)], line, 0),
        _ => Err(RuntimeError {
            message: format!("the sub-command {sub_command} of the Drive is not known."),
            line,
        }),
    };
    the_answer_of_an_act(rt, "Drive", answer)
}

// -- the window of the script -------------------------------------------------------

/// `Gui, SubCommand, Value1, Value2, Value3`: the window of the script.
///
/// The v1 has the GUI as a command and the v2 has it as a class.
///
/// The window of the v1 is one at a time: the `Gui, Add` puts a control in
/// the window that is there, and makes the window when there is none. The
/// desktop of the tree has one window of the script as well, and it
/// refuses a second one.
///
/// The sub-commands that the tree does not carry -- the "Submit", the
/// "Cancel", the "Font", the "Color", the "Margin", the "Flash", the
/// "Default" and the "Tab" -- are refused with the reason, and the reason
/// is a note and not a stop: the script goes on.
///
/// Measured on the binary of v1.1.37.02 on 2026-11-14: the sub-commands
/// that the v1 knows are the "New", the "Add", the "Show", the "Submit",
/// the "Cancel", the "Hide", the "Destroy", the "Font", the "Color", the
/// "Margin", the "Menu", the "Minimize", the "Maximize", the "Restore",
/// the "Flash", the "Default" and the "Tab"; the "List", the "ListVars"
/// and the "Back" are refused with "Parameter #1 invalid.".
pub(crate) fn gui(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The v1: `Gui, SubCommand, Value1, Value2, Value3`.
    let sub_command = value_of(values, 0);
    let trimmed = sub_command.trim();
    let answer = if trimmed.starts_with('+') || trimmed.starts_with('-') {
        // The v1: `Gui, +Resize` and `Gui, -Resize`: the option of the
        // window of the script.
        let on = trimmed.starts_with('+');
        let name = trimmed[1..].trim().to_ascii_lowercase();
        rt.desktop()
            .gui_option(&name, on)
            .map(|_| Value::Text(String::new()))
            .map_err(|reason| crate::builtins::desktop_failure(reason, line))
    } else {
        match trimmed.to_ascii_lowercase().as_str() {
            "new" => {
                // The v1: the new window takes the place of the one that is
                // there.
                if rt.desktop().gui_is_open() {
                    rt.desktop()
                        .gui_destroy(0)
                        .map_err(|reason| crate::builtins::desktop_failure(reason, line))?;
                }
                let title = value_of(values, 1);
                rt.desktop()
                    .gui_open(&title)
                    .map(|_| Value::Text(String::new()))
                    .map_err(|reason| crate::builtins::desktop_failure(reason, line))
            }
            "add" => {
                // The v1: `Gui, Add, Type, Options, Text`. The type of
                // the control is the second parameter, the options are
                // the third and the text is the fourth. Measured in the
                // CHM of v1.1.37.02: "Gui , Add, ControlType , Options,
                // Text", and the example of the CHM is the `Gui, Add,
                // Edit, vName`, which has no text at all.
                let kind = the_kind_of_the_machine(&value_of(values, 1));
                let text = value_of(values, 3);
                let handle = the_window_of_the_script(rt, line)?;
                rt.desktop()
                    .gui_add(handle, &kind, &text)
                    .map(|(number, _)| Value::Text(number.to_string()))
                    .map_err(|reason| crate::builtins::desktop_failure(reason, line))
            }
            "show" => {
                // The v1: the window is made when there is none.
                let handle = the_window_of_the_script(rt, line)?;
                rt.desktop()
                    .gui_show(handle)
                    .map(|_| Value::Text(String::new()))
                    .map_err(|reason| crate::builtins::desktop_failure(reason, line))
            }
            "hide" => rt
                .desktop()
                .gui_hide()
                .map(|_| Value::Text(String::new()))
                .map_err(|reason| crate::builtins::desktop_failure(reason, line)),
            "destroy" => rt
                .desktop()
                .gui_destroy(0)
                .map(|_| Value::Text(String::new()))
                .map_err(|reason| crate::builtins::desktop_failure(reason, line)),
            "menu" => {
                // The v1: `Gui, Menu, MenuName` -- the bar of the window is
                // the menu of the script that the name names.
                let name = value_of(values, 1);
                let items = crate::v1::menus::the_items_of_the_menu(rt, &name);
                rt.desktop()
                    .gui_menu_bar(&items)
                    .map(|_| Value::Text(String::new()))
                    .map_err(|reason| crate::builtins::desktop_failure(reason, line))
            }
            "minimize" => the_state_of_the_window(rt, "minimize", line),
            "maximize" => the_state_of_the_window(rt, "maximize", line),
            "restore" => the_state_of_the_window(rt, "restore", line),
            "submit" | "cancel" | "font" | "color" | "margin" | "flash" | "default" | "tab" => {
                Err(RuntimeError {
                    message: the_reason_of_a_gui_that_the_tree_does_not_carry(
                        &trimmed.to_ascii_lowercase(),
                    ),
                    line,
                })
            }
            _ => Err(RuntimeError {
                message: format!("the sub-command {sub_command} of the Gui is not known."),
                line,
            }),
        }
    };
    the_answer_of_an_act(rt, "Gui", answer)
}

/// The window of the script, made when there is none.
///
/// The v1 has one window of the script at a time: the `Gui, Add` puts a
/// control in the window that is there, and makes it when there is none.
/// The desktop of the tree refuses a second window, so the question comes
/// first.
fn the_window_of_the_script(rt: &mut Runtime<'_>, line: u32) -> Result<u64, RuntimeError> {
    if rt.desktop().gui_is_open() {
        return Ok(0);
    }
    rt.desktop()
        .gui_open("")
        .map_err(|reason| crate::builtins::desktop_failure(reason, line))
}

/// The kind of a control of the v1, in the name the machine knows.
///
/// The v1 spells the kinds its own way: the "DropDownList" is the "ddl" of
/// the machine, the "Trackbar" is the "slider", and the "Tab3" is the
/// "tab". The others are the same name in the two.
fn the_kind_of_the_machine(kind: &str) -> String {
    let kind = kind.trim().to_ascii_lowercase();
    match kind.as_str() {
        "dropdownlist" => "ddl".to_string(),
        "trackbar" => "slider".to_string(),
        "tab3" => "tab".to_string(),
        _ => kind,
    }
}

/// The state of the window of the script: the "minimize", the "maximize"
/// and the "restore".
fn the_state_of_the_window(
    rt: &mut Runtime<'_>,
    state: &str,
    line: u32,
) -> Result<Value, RuntimeError> {
    rt.desktop()
        .gui_option(state, true)
        .map(|_| Value::Text(String::new()))
        .map_err(|reason| crate::builtins::desktop_failure(reason, line))
}

/// The reason of a sub-command of the `Gui` that the tree does not carry.
///
/// The tree has no font, no colour and no margin for the window of the
/// script, and it does not speak the messages of the window: the
/// "Submit" and the "Cancel" are two of those messages.
fn the_reason_of_a_gui_that_the_tree_does_not_carry(sub_command: &str) -> String {
    match sub_command {
        "font" => "the tree does not carry the font of the window of the script: the machine of the tree has no font for it.".to_string(),
        "color" => "the tree does not carry the colour of the window of the script: the machine of the tree has no colour for it.".to_string(),
        "margin" => "the tree does not carry the margin of the window of the script: the machine of the tree lays the controls out its own way.".to_string(),
        "submit" | "cancel" => "the tree does not carry the submit of the window of the script: the machine of the tree does not speak the messages of the window.".to_string(),
        _ => format!("the tree does not carry the {sub_command} of the window of the script."),
    }
}

/// `GuiControl, SubCommand, ControlID, Value`: a change in a control of the
/// window of the script.
///
/// The v2 has the class of the control, and the tree has the number of it
/// by its `ClassNN`.
///
/// Measured on the binary of v1.1.37.02 on 2026-11-14: the sub-commands
/// that the v1 knows are the "Text", the "Move", the "MoveDraw", the
/// "Focus", the "Disable", the "Enable", the "Hide", the "Show", the
/// "Choose", the "ChooseString" and the "Font"; the "Redraw", the
/// "Delete" and the "Value" are refused with "Parameter #1 invalid.".
pub(crate) fn gui_control(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The v1: `GuiControl, SubCommand, ControlID, Value`.
    let sub_command = value_of(values, 0);
    let control = value_of(values, 1);
    let value = value_of(values, 2);
    // The failure of a control that is not there is a note and not a
    // stop of the script: measured on the binary of v1.1.37.02 on
    // 2026-11-14, the `GuiControlGet` of a window that does not exist
    // writes the empty text into the variable of the caller and leaves
    // the `ErrorLevel` at one, and the script goes on.
    let answer = (|| -> Result<Value, RuntimeError> {
    match sub_command.trim().to_ascii_lowercase().as_str() {
        "enable" => the_state_of_a_control(rt, &control, "enabled", true, line),
        "disable" => the_state_of_a_control(rt, &control, "enabled", false, line),
        "hide" => rt
            .desktop()
            .gui_visibility(&control, false)
            .map(|_| Value::Text(String::new()))
            .map_err(|reason| crate::builtins::desktop_failure(reason, line)),
        "show" => rt
            .desktop()
            .gui_visibility(&control, true)
            .map(|_| Value::Text(String::new()))
            .map_err(|reason| crate::builtins::desktop_failure(reason, line)),
        "focus" => {
            let number = the_number_of_a_control(rt, &control, line)?;
            rt.desktop()
                .gui_focus(number as u64)
                .map(|_| Value::Text(String::new()))
                .map_err(|reason| crate::builtins::desktop_failure(reason, line))
        }
        "text" => {
            // The v1: `GuiControl, Text, ControlID, NewText`. The text of
            // the control is written when there is one, and read when there
            // is not.
            let number = the_number_of_a_control(rt, &control, line)?;
            if value.is_empty() {
                rt.desktop()
                    .gui_value(number as u64, None)
                    .map(Value::Text)
                    .map_err(|reason| crate::builtins::desktop_failure(reason, line))
            } else {
                rt.desktop()
                    .gui_value(number as u64, Some(&value))
                    .map(Value::Text)
                    .map_err(|reason| crate::builtins::desktop_failure(reason, line))
            }
        }
        "choose" => {
            // The v1: `GuiControl, Choose, ControlID, ItemNumber`.
            let number = the_number_of_a_control(rt, &control, line)?;
            rt.desktop()
                .gui_combo_select(number as u64, &value, false)
                .map(|index| Value::Text(index.to_string()))
                .map_err(|reason| crate::builtins::desktop_failure(reason, line))
        }
        "choosestring" => {
            // The v1: `GuiControl, ChooseString, ControlID, ItemText`.
            let number = the_number_of_a_control(rt, &control, line)?;
            rt.desktop()
                .gui_combo_select(number as u64, &value, true)
                .map(|index| Value::Text(index.to_string()))
                .map_err(|reason| crate::builtins::desktop_failure(reason, line))
        }
        "move" | "movedraw" | "font" => Err(RuntimeError {
            message: the_reason_of_a_gui_control_that_the_tree_does_not_carry(sub_command.trim()),
            line,
        }),
        _ => Err(RuntimeError {
            message: format!("the sub-command {sub_command} of the GuiControl is not known."),
            line,
        }),
    }
    })();
    the_answer_of_an_act(rt, "GuiControl", answer)
}

/// The reason of a sub-command of the `GuiControl` that the tree does not
/// carry.
///
/// The tree lays the controls out its own way, and it has no font for them.
fn the_reason_of_a_gui_control_that_the_tree_does_not_carry(sub_command: &str) -> String {
    match sub_command.to_ascii_lowercase().as_str() {
        "font" => "the tree does not carry the font of a control of the window of the script: the machine of the tree has no font for it.".to_string(),
        _ => "the tree does not move a control of the window of the script: the machine of the tree lays the controls out its own way.".to_string(),
    }
}

/// The number that names a control of the window of the script.
fn the_number_of_a_control(
    rt: &mut Runtime<'_>,
    control: &str,
    line: u32,
) -> Result<i64, RuntimeError> {
    rt.desktop()
        .gui_number_named(control)
        .map_err(|reason| crate::builtins::desktop_failure(reason, line))
}

/// The state of a control of the window of the script: the "enabled" of it.
fn the_state_of_a_control(
    rt: &mut Runtime<'_>,
    control: &str,
    what: &str,
    on: bool,
    line: u32,
) -> Result<Value, RuntimeError> {
    let number = the_number_of_a_control(rt, control, line)?;
    rt.desktop()
        .gui_flag(number as u64, what, Some(on))
        .map(|_| Value::Text(String::new()))
        .map_err(|reason| crate::builtins::desktop_failure(reason, line))
}

/// `GuiControlGet, OutputVar, SubCommand, ControlID, Value`: what a control
/// of the window of the script has.
///
/// The v1 writes the answer into the variable of the caller, and the
/// sub-command says what the answer is: the text of the control when the
/// sub-command is not there, the place of it with the "Pos", the name of
/// it with the "Name" and the handle of it with the "Hwnd".
///
/// Measured on the binary of v1.1.37.02 on 2026-11-14: the sub-commands
/// that the v1 knows are the "Pos", the "Focus", the "FocusV", the
/// "Enabled", the "Visible", the "Hwnd" and the "Name"; the "Type", the
/// "Value", the "Text", the "Style", the "ExStyle", the "Choice" and the
/// "Checked" are refused with "Parameter #2 invalid.".
pub(crate) fn gui_control_get(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The v1: `GuiControlGet, OutputVar, SubCommand, ControlID, Value`.
    let sub_command = value_of(values, 1);
    let control = value_of(values, 2);
    // The failure of a control that is not there is a note and not a
    // stop of the script: the text of the caller stays empty and the
    // script goes on.
    let answer = (|| -> Result<Value, RuntimeError> {
    match sub_command.trim().to_ascii_lowercase().as_str() {
        "" | "text" => {
            // The v1: the text of the control is the answer when the
            // sub-command is not there.
            let number = the_number_of_a_control(rt, &control, line)?;
            rt.desktop()
                .gui_value(number as u64, None)
                .map(Value::Text)
                .map_err(|reason| crate::builtins::desktop_failure(reason, line))
        }
        "pos" => {
            // The v1: the place of the control and the size of it are four
            // numbers. The tree writes them in one text.
            let number = the_number_of_a_control(rt, &control, line)?;
            let (x, y, width, height) = rt
                .desktop()
                .gui_control_pos(number as u64)
                .map_err(|reason| crate::builtins::desktop_failure(reason, line))?;
            Ok(Value::Text(format!("{x} {y} {width} {height}")))
        }
        "focus" => rt
            .desktop()
            .gui_focused()
            .map(Value::Text)
            .map_err(|reason| crate::builtins::desktop_failure(reason, line)),
        "focusv" => Err(RuntimeError {
            message: "the tree does not carry the variable of the control that has the focus: the controls of the window of the script have no variable.".to_string(),
            line,
        }),
        "enabled" => {
            let number = the_number_of_a_control(rt, &control, line)?;
            rt.desktop()
                .gui_flag(number as u64, "enabled", None)
                .map(Value::Int)
                .map_err(|reason| crate::builtins::desktop_failure(reason, line))
        }
        "visible" => {
            let number = the_number_of_a_control(rt, &control, line)?;
            rt.desktop()
                .gui_flag(number as u64, "visible", None)
                .map(Value::Int)
                .map_err(|reason| crate::builtins::desktop_failure(reason, line))
        }
        "hwnd" => {
            let number = the_number_of_a_control(rt, &control, line)?;
            rt.desktop()
                .gui_handle(number as u64)
                .map(Value::Int)
                .map_err(|reason| crate::builtins::desktop_failure(reason, line))
        }
        "name" => {
            let number = the_number_of_a_control(rt, &control, line)?;
            rt.desktop()
                .gui_classnn(number as u64)
                .map(Value::Text)
                .map_err(|reason| crate::builtins::desktop_failure(reason, line))
        }
        _ => Err(RuntimeError {
            message: format!(
                "the sub-command {sub_command} of the GuiControlGet is not known."
            ),
            line,
        }),
    }
    })();
    // The `ErrorLevel` of the `GuiControlGet` is one when the control is
    // not there: measured on the binary of v1.1.37.02 on 2026-11-14, the
    // `GuiControlGet` of a window that does not exist writes the empty
    // text and leaves the `ErrorLevel` at one, and the script goes on.
    the_answer_that_goes_on(rt, "GuiControlGet", values, line, answer, true)
}

// -- the keyboard of the machine ----------------------------------------------------

/// `InputHook(Options, EndKeys, MatchList)`: the hook of the keyboard.
///
/// The v2 has the `InputHook` as a class, and the v1 has it as a function.
/// The options of the v1 are the letters of the v2: the "B" and the "C"
/// and the "E" and the "H" and the "I" and the "L" and the "M" and the "N"
/// and the "O" and the "P" and the "R" and the "S" and the "T" and the "V".
pub(crate) fn input_hook(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let options = values
        .first()
        .map(|value| value.to_text())
        .unwrap_or_default();
    let end_keys = values.get(1).map(|value| value.to_text()).unwrap_or_default();
    let match_list = values.get(2).map(|value| value.to_text()).unwrap_or_default();
    // The options of the v1 become the options of the v2, and the letters
    // that the v2 does not have are refused with the reason.
    let mut arguments: Vec<Value> = Vec::new();
    if !options.trim().is_empty() {
        arguments.push(Value::Text(the_options_of_the_v2(&options, line)?));
    }
    if !end_keys.trim().is_empty() {
        arguments.push(Value::Text(end_keys));
    }
    if !match_list.trim().is_empty() {
        arguments.push(Value::Text(match_list));
    }
    match crate::classes::construct("InputHook", &arguments, rt, line) {
        Some(answer) => answer.map_err(|failure| RuntimeError {
            message: crate::builtins::the_message_of(failure),
            line,
        }),
        None => Err(RuntimeError {
            message: "the class of the InputHook is not known.".to_string(),
            line,
        }),
    }
}

/// The options of the v1 as the options of the v2.
///
/// The letters of the v1 are the letters of the v2, and the ones that the
/// v2 does not have are refused with the reason.
fn the_options_of_the_v2(options: &str, line: u32) -> Result<String, RuntimeError> {
    let mut carried = String::new();
    for letter in options.split_whitespace() {
        for one in letter.chars() {
            let upper = one.to_ascii_uppercase();
            match upper {
                'B' | 'C' | 'E' | 'H' | 'I' | 'L' | 'M' | 'N' | 'O' | 'P' | 'R' | 'S' | 'T' | 'V'
                | 'W' => carried.push(upper),
                _ => {
                    return Err(RuntimeError {
                        message: format!("the option {one} of the InputHook is not known."),
                        line,
                    })
                }
            }
        }
    }
    Ok(carried)
}

// -- the menu of the machine --------------------------------------------------------

/// `Menu, MenuName, SubCommand, Value1, Value2, Value3, Value4`: the menu of
/// the machine.
///
/// The v1 has the menu as a command and the v2 has it as a class.
///
/// The sub-commands that the tree does not carry -- the "Standard", the
/// "NoStandard", the "Icon", the "NoIcon", the "Tip", the "Show", the
/// "Color", the "Click", the "MainWindow", the "NoMainWindow" and the
/// "UseErrorLevel" -- are refused with the reason: they are about the menu
/// bar of a window of the machine, and the menus of the tree are menus of
/// the script.
///
/// Measured on the binary of v1.1.37.02 on 2026-11-14: the sub-commands
/// that the v1 knows are the "Add", the "Insert", the "Delete", the
/// "DeleteAll", the "Rename", the "Check", the "Uncheck", the
/// "ToggleCheck", the "Enable", the "Disable", the "ToggleEnable", the
/// "Default", the "NoDefault", the "Standard", the "NoStandard", the
/// "Icon", the "NoIcon", the "Tip", the "Show", the "Color", the "Click",
/// the "MainWindow", the "NoMainWindow" and the "UseErrorLevel".
pub(crate) fn menu(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The v1: `Menu, MenuName, SubCommand, Value1, ...`.
    let name = value_of(values, 0);
    let sub_command = value_of(values, 1);
    let value = value_of(values, 2);
    let answer = match sub_command.trim().to_ascii_lowercase().as_str() {
        "add" => {
            // The v1: `Menu, MyMenu, Add, ItemName, Callback, Options`.
            let callback = value_of(values, 3);
            crate::v1::menus::add_item(rt, &name, &value, &callback, line)
        }
        "insert" => {
            // The v1: `Menu, MyMenu, Insert, ItemName, Callback, Options`.
            // The item goes above the last one of the menu.
            let callback = value_of(values, 3);
            crate::v1::menus::insert_item(rt, &name, &value, &callback, line)
        }
        "delete" => crate::v1::menus::delete_item(rt, &name, &value, line),
        "deleteall" => crate::v1::menus::delete_all(rt, &name, line),
        "disable" => crate::v1::menus::set_enabled(rt, &name, &value, false, line),
        "enable" => crate::v1::menus::set_enabled(rt, &name, &value, true, line),
        "toggleenable" => crate::v1::menus::toggle_enabled(rt, &name, &value, line),
        "check" => crate::v1::menus::set_checked(rt, &name, &value, true, line),
        "uncheck" => crate::v1::menus::set_checked(rt, &name, &value, false, line),
        "togglecheck" => crate::v1::menus::toggle_checked(rt, &name, &value, line),
        "default" => crate::v1::menus::set_default(rt, &name, &value, line),
        "nodefault" => crate::v1::menus::no_default(rt, &name, line),
        "rename" => {
            // The v1: `Menu, MyMenu, Rename, NewName, OldName`. The new
            // name comes before the old one.
            let new_name = value_of(values, 2);
            let old_name = value_of(values, 3);
            crate::v1::menus::rename_item(rt, &name, &old_name, &new_name, line)
        }
        "standard" | "nostandard" | "icon" | "noicon" | "tip" | "show" | "color" | "click"
        | "mainwindow" | "nomainwindow" | "useerrorlevel" => Err(RuntimeError {
            message: the_reason_of_a_menu_that_the_tree_does_not_carry(sub_command.trim()),
            line,
        }),
        _ => Err(RuntimeError {
            message: format!("the sub-command {sub_command} of the Menu is not known."),
            line,
        }),
    };
    the_answer_of_an_act(rt, "Menu", answer)
}

/// The reason of a sub-command of the `Menu` that the tree does not carry.
///
/// The menus of the tree are menus of the script: they have items, and the
/// items have a name, a mark and a state. The bar of a window of the
/// machine is another thing, and the tree does not carry it.
fn the_reason_of_a_menu_that_the_tree_does_not_carry(sub_command: &str) -> String {
    match sub_command.to_ascii_lowercase().as_str() {
        "standard" | "nostandard" => "the tree does not carry the standard items of a menu: the menus of the tree have the items that the script puts in them.".to_string(),
        _ => "the tree does not carry the menu bar of a window of the machine: the menus of the tree are menus of the script.".to_string(),
    }
}

/// `MenuGetHandle(MenuName)`: the handle of a menu of the machine.
///
/// The v2 has the `MenuFromHandle`, and it is the other way round: the v1
/// asks the handle of a menu by its name.
pub(crate) fn menu_get_handle(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let name = values
        .first()
        .map(|value| value.to_text())
        .unwrap_or_default();
    crate::v1::menus::the_handle_of(rt, &name, line)
}

/// `MenuGetName(Handle)`: the name of a menu of the machine.
pub(crate) fn menu_get_name(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let handle = values
        .first()
        .map(|value| value.to_text())
        .unwrap_or_default();
    crate::v1::menus::the_name_of(rt, &handle, line)
}

// -- the window of the progress -----------------------------------------------------

/// `Progress, ProgressParam1, SubText, MainText, WinTitle, FontName`: the
/// window of the progress.
///
/// The v2 has the progress as a control of a window of the script, and the
/// v1 has it as a window of its own. The tree has one window of the
/// script, and the progress takes its place: a script that has a window of
/// the GUI and a progress at the same time has the refusal of the desktop
/// as the answer.
pub(crate) fn progress(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The v1: `Progress, ProgressParam1, SubText, MainText, ...`.
    let percent = value_of(values, 0);
    let answer = if percent.trim().eq_ignore_ascii_case("off") {
        rt.desktop()
            .gui_destroy(0)
            .map(|_| Value::Text(String::new()))
            .map_err(|reason| crate::builtins::desktop_failure(reason, line))
    } else {
        let number = percent.trim().parse::<i64>().unwrap_or(0);
        let handle = rt
            .desktop()
            .gui_open("Progress")
            .map_err(|reason| crate::builtins::desktop_failure(reason, line))?;
        let (control, _) = rt
            .desktop()
            .gui_add(handle, "Progress", &number.to_string())
            .map_err(|reason| crate::builtins::desktop_failure(reason, line))?;
        rt.desktop()
            .gui_value(control, None)
            .map(Value::Text)
            .map_err(|reason| crate::builtins::desktop_failure(reason, line))
    };
    the_answer_of_an_act(rt, "Progress", answer)
}

/// `SplashTextOn, Width, Height, Title, Text`: the window of a text.
///
/// The v1 has it as a window of its own, and the v2 has it as a window of
/// the script.
pub(crate) fn splash_text_on(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The v1: `SplashTextOn, Width, Height, Title, Text`.
    let width = values.get(1).map(|value| value.to_text()).unwrap_or_default();
    let height = 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 text = values.get(4).map(|value| value.to_text()).unwrap_or_default();
    let handle = rt
        .desktop()
        .gui_open(&title)
        .map_err(|reason| crate::builtins::desktop_failure(reason, line))?;
    let (control, _) = rt
        .desktop()
        .gui_add(handle, "Text", &text)
        .map_err(|reason| crate::builtins::desktop_failure(reason, line))?;
    let width = width.trim().parse::<i64>().unwrap_or(200);
    let height = height.trim().parse::<i64>().unwrap_or(0);
    rt.desktop()
        .gui_size(control, width, height)
        .map(|_| Value::Text(String::new()))
        .map_err(|reason| crate::builtins::desktop_failure(reason, line))
}

// -- the callback of the machine ----------------------------------------------------

/// `RegisterCallback(Function, Options, ParamCount, EventInfo)`: the address
/// of a function of the machine that calls a function of the script.
///
/// The address is a trampoline of the pool of the callbacks: the machine
/// calls it, and it runs the function of the script. The callback runs on
/// the thread of the script while a `DllCall` goes on; the number of the
/// parameters is the one the script gives, or the one the function
/// declares.
pub(crate) fn register_callback(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    #[cfg(feature = "std")]
    {
        let name = value_of(values, 0);
        if name.is_empty() {
            return Err(RuntimeError {
                message: "Parameter #1 of RegisterCallback must not be blank.".to_string(),
                line,
            });
        }
        let params = match values.get(2).and_then(|value| value.to_number()) {
            Some(number) if number >= 0.0 => number as usize,
            _ => rt.the_number_of_parameters_of(&name).unwrap_or(0),
        };
        let address = crate::callback::register(&name, params);
        if address == 0 {
            return Err(RuntimeError {
                message: "the pool of the callbacks is full.".to_string(),
                line,
            });
        }
        Ok(Value::Int(address as i64))
    }
    #[cfg(not(feature = "std"))]
    {
        let _ = (rt, values);
        Err(RuntimeError {
            message: "the callback of the machine needs the std of the tree.".to_string(),
            line,
        })
    }
}
/// The text of the parameter of this place, or the empty text.
fn value_of(values: &[Value], at: usize) -> String {
    values.get(at).map(|value| value.to_text()).unwrap_or_default()
}