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
//! The window family of the v1, against the desktop of the machine.
//!
//! 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 its window is not a failure of the
//!   script: the variable of the caller is empty, the `ErrorLevel` is one
//!   when the command says so, and the script goes on;
//! - the `WinGetTitle` and the `WinGetClass` of a window that is not there
//!   leave the `ErrorLevel` at zero, and the `WinGetText` leaves it at one;
//! - the `WinGetPos` of a window that is not there leaves the four
//!   variables of the caller empty, and the `ErrorLevel` at zero.
//!
//! The names of the v1 that the v2 does not have are here: the `WinGet`
//! and the `WinSet` are families of sub-commands, and the `WinGetActive`
//! pair answers about the window that has the focus.

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

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

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()))
        }
    }
}

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

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

/// `WinGetPos, OutX, OutY, OutWidth, OutHeight, WinTitle, ...`: the place of
/// a window.
///
/// The four variables of the caller are empty when the window is not
/// there, and the `ErrorLevel` stays at zero: measured on the binary of
/// v1.1.37.02 on 2026-11-14.
pub(crate) fn win_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::win_get_pos(rt, values, line, 0);
    match answer {
        Ok(value) => Ok(value),
        Err(failure) => {
            // The four variables of the caller are empty, and not the
            // numbers they had before.
            for index in 0..4 {
                if values.get(index).is_some() {
                    write_the_answer(rt, "WinGetPos", values, index, Value::Text(String::new()), line)?;
                }
            }
            rt.note(format!(
                "the command WinGetPos did not do the thing: {}",
                failure.message
            ));
            Ok(Value::Text(String::new()))
        }
    }
}

/// `WinGetActiveTitle, OutputVar`: the title of the window that has the
/// focus.
///
/// Measured on the binary of v1.1.37.02 on 2026-11-14: the answer is the
/// title of the window that has the focus, and the `ErrorLevel` stays at
/// zero.
pub(crate) fn win_get_active_title(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = rt
        .desktop()
        .active_window_title()
        .map(|title| title.unwrap_or_default())
        .map(Value::Text)
        .map_err(|reason| builtins::desktop_failure(reason, line));
    the_answer_that_goes_on(rt, "WinGetActiveTitle", values, line, answer, false)
}

/// `WinGetActiveStats, OutTitle, OutWidth, OutHeight, OutX, OutY`: the
/// window that has the focus.
///
/// Measured on the binary of v1.1.37.02 on 2026-11-14: the title is the
/// title of the window that has the focus, the width and the height are
/// the size of it, and the two last numbers are where its upper-left
/// corner is.
pub(crate) fn win_get_active_stats(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let title = rt
        .desktop()
        .active_window_title()
        .map_err(|reason| builtins::desktop_failure(reason, line))?;
    let Some(title) = title else {
        // The window that has the focus is not there: the five variables
        // of the caller stay as they were.
        return Ok(Value::Text(String::new()));
    };
    let geometry = rt
        .desktop()
        .window_geometry(&title, crate::settings::title_match_mode())
        .map_err(|reason| builtins::desktop_failure(reason, line))?;
    let Some(geometry) = geometry else {
        return Ok(Value::Text(String::new()));
    };
    // The order of the v1 is the title, the width, the height, the x and
    // the y -- and the `WinGetPos` of the v2 is the x, the y, the width
    // and the height.
    let places = [
        Value::Text(title),
        Value::Int(geometry.width),
        Value::Int(geometry.height),
        Value::Int(geometry.x),
        Value::Int(geometry.y),
    ];
    for (index, place) in places.iter().enumerate() {
        if values.get(index).is_some() {
            write_the_answer(rt, "WinGetActiveStats", values, index, place.clone(), line)?;
        }
    }
    Ok(Value::Text(String::new()))
}

/// `WinExist(WinTitle, ...)`: the identifier of the window that is there.
///
/// The v1 answers the identifier of the window as a hexadecimal number
/// with the "0x" in front of it, and it answers the empty text -- the
/// "0x0" -- when there is no window. Measured on the binary of
/// v1.1.37.02 on 2026-11-14: the `WinExist` of a window that is not
/// there answers "0x0", and the answer is the text of the identifier and
/// not a number.
///
/// The title that is left out is the last window that a script found, and
/// a window that is found becomes the last found window: measured on the
/// binary of v1.1.37.02 on 2026-11-14, the `WinGet, out, IDLast` that
/// follows a `WinExist` answers the window that it found.
pub(crate) fn win_exist(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let title = values.first().map(|value| value.to_text()).unwrap_or_default();
    // The title that is left out is the last window that a script found.
    if title.is_empty() {
        return Ok(match rt.the_last_window_of_the_v1() {
            Some(id) => Value::Text(the_identifier_of_the_v1(id)),
            None => Value::Text("0x0".to_string()),
        });
    }
    let mode = crate::settings::title_match_mode();
    let windows = rt
        .desktop()
        .matching_windows(&title, mode)
        .map_err(|reason| builtins::desktop_failure(reason, line))?;
    match windows.first() {
        Some(window) => {
            // The window that is found is the last found window.
            rt.remember_the_last_window_of_the_v1(&window.id);
            Ok(Value::Text(the_identifier_of_the_v1(&window.id)))
        }
        // The window that is not there leaves the last found window
        // where it was: measured on the binary of v1.1.37.02 on
        // 2026-11-14.
        None => Ok(Value::Text("0x0".to_string())),
    }
}

/// `WinGet, OutputVar, SubCommand, WinTitle, ...`: a question about the
/// windows of the machine.
///
/// The sub-command names the question, and the v2 has a name for each one
/// of them: the `ID` is the `WinGetID`, the `Count` is the `WinGetCount`,
/// the `List` is the `WinGetList`, and so on.
pub(crate) fn win_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 target of the window of the v1 begins in the third place: the
    // title, the text of the window and the two exclusions. Measured on
    // the binary of v1.1.37.02 on 2026-11-14: the `WinGetTitle` of a
    // window by the text of one text element of it finds the window, and
    // the `WinGetTitle` with the exclusion of its title finds no window
    // at all.
    let wanted = crate::desktop::TheWindowWanted::of(values, 2);
    // The `List` of the v1 is a pseudo-array: the variable of the caller
    // has the number of the windows, and the variables whose name begins
    // with it have the identifiers of them. It is the one sub-command
    // that writes more than one variable.
    if sub_command.eq_ignore_ascii_case("list") {
        return the_list_of_the_windows(rt, values, &wanted, line);
    }
    let answer = the_answer_of_the_sub_command(rt, &sub_command, &wanted, line);
    the_answer_that_goes_on(rt, "WinGet", values, line, answer, false)
}

/// `WinGet, OutputVar, List, WinTitle, ...`: the identifiers of the
/// windows that match.
///
/// The v1 writes the number of the windows in the variable of the caller
/// and the identifier of each one of them in the variables whose name
/// begins with the name of that variable: measured on the binary of
/// v1.1.37.02 on 2026-11-14, the `WinGet, out, List` of two windows
/// leaves `out` at 2, `out1` at the identifier of the first one and
/// `out2` at the identifier of the second one.
fn the_list_of_the_windows(
    rt: &mut Runtime<'_>,
    values: &[Value],
    wanted: &crate::desktop::TheWindowWanted,
    line: u32,
) -> Result<Value, RuntimeError> {
    let windows = the_windows_that_answer(rt, wanted, line)?;
    // The number of the windows goes into the variable of the caller.
    let count = windows.len() as i64;
    write_the_answer(rt, "WinGet", values, 0, Value::Int(count), line)?;
    // The identifier of each one of them goes into the variable whose
    // name begins with the name of the variable of the caller.
    let Some(name) = the_name_of_the_output(rt, values) else {
        return Ok(Value::Int(count));
    };
    for (index, window) in windows.iter().enumerate() {
        let identifier = the_identifier_of_the_v1(&window.id.to_string());
        rt.assign_the_variable_of_the_pseudo_array(
            &format!("{name}{}", index + 1),
            Value::Text(identifier),
        );
    }
    Ok(Value::Int(count))
}

/// As janelas que respondem ao alvo, na listagem do desktop.
///
/// A listagem e a do desktop, e o filtro e o do runtime: e o mesmo
/// para os dois dialetos.
fn the_windows_that_answer(
    rt: &mut Runtime<'_>,
    wanted: &crate::desktop::TheWindowWanted,
    line: u32,
) -> Result<Vec<crate::desktop::WindowInfo>, RuntimeError> {
    let windows = rt
        .desktop()
        .windows()
        .map_err(|reason| builtins::desktop_failure(reason, line))?;
    Ok(builtins::the_windows_of_the_listing(rt, &windows, wanted))
}

/// The name of the variable of the caller, if the caller gave one.
///
/// The name is the one of the reference of the first parameter, and it is
/// the beginning of the names of the variables of a pseudo-array.
fn the_name_of_the_output(rt: &mut Runtime<'_>, values: &[Value]) -> Option<String> {
    let Some(Value::Reference(reference)) = values.first() else {
        return None;
    };
    let name = reference.name.clone();
    if name.is_empty() {
        None
    } else {
        let _ = rt;
        Some(name)
    }
}

/// The identifier of a window, as the v1 writes it.
///
/// The v1 writes the identifier of a window as a hexadecimal number with
/// the "0x" in front of it: measured on the binary of v1.1.37.02 on
/// 2026-11-14, the `WinGet, out, ID` of a window of the machine answered
/// "0x6530f1e".
fn the_identifier_of_the_v1(id: &str) -> String {
    match id.parse::<u64>() {
        Ok(number) => format!("0x{number:x}"),
        // The identifier of a window of a compositor is a token, and there
        // is no hexadecimal number in it.
        Err(_) => id.to_string(),
    }
}

/// The answer of the sub-command of the `WinGet`.
///
/// The name of the sub-command is the name of the question, and the v2
/// has a built-in for each one of them.
///
/// The title that is left out is the last window that a script found: the
/// v1 keeps one, and it is empty at the start of a script. Measured on the
/// binary of v1.1.37.02 on 2026-11-14: the `WinGet, out, ID` of a script
/// that has found no window answers the empty text.
///
/// The title that is given is matched against the windows of the machine,
/// and the `IDLast` of it is the last of them: measured on the binary of
/// v1.1.37.02 on 2026-11-14, the `WinGet, out, IDLast` of a title with
/// many matches answers the identifier of the bottommost one, and the
/// `ID` of the same title answers the one of the topmost.
fn the_answer_of_the_sub_command(
    rt: &mut Runtime<'_>,
    sub_command: &str,
    wanted: &crate::desktop::TheWindowWanted,
    line: u32,
) -> Result<Value, RuntimeError> {
    let mode = crate::settings::title_match_mode();
    let title = &wanted.title;
    // The title that is left out is the last window that a script found.
    // The `Count` and the `List` are the two sub-commands that do not use
    // it: they ask about every window of the machine.
    let uses_the_last_window = !title.is_empty();
    match sub_command.to_ascii_lowercase().as_str() {
        "id" => {
            if uses_the_last_window {
                let windows = the_windows_that_answer(rt, wanted, line)?;
                return match windows.first() {
                    Some(window) => Ok(Value::Text(the_identifier_of_the_v1(&window.id.to_string()))),
                    None => Err(RuntimeError {
                        message: builtins::TARGET_WINDOW.to_string(),
                        line,
                    }),
                };
            }
            match rt.the_last_window_of_the_v1() {
                Some(id) => Ok(Value::Text(the_identifier_of_the_v1(id))),
                None => Err(RuntimeError {
                    message: builtins::TARGET_WINDOW.to_string(),
                    line,
                }),
            }
        }
        "idlast" => {
            if uses_the_last_window {
                let windows = the_windows_that_answer(rt, wanted, line)?;
                return match windows.last() {
                    Some(window) => Ok(Value::Text(the_identifier_of_the_v1(&window.id.to_string()))),
                    None => Err(RuntimeError {
                        message: builtins::TARGET_WINDOW.to_string(),
                        line,
                    }),
                };
            }
            match rt.the_last_window_of_the_v1() {
                Some(id) => Ok(Value::Text(the_identifier_of_the_v1(id))),
                None => Err(RuntimeError {
                    message: builtins::TARGET_WINDOW.to_string(),
                    line,
                }),
            }
        }
        "count" => {
            let windows = the_windows_that_answer(rt, wanted, line)?;
            Ok(Value::Int(windows.len() as i64))
        }
        "minmax" => {
            let state = rt
                .desktop()
                .window_min_max(title, mode)
                .map_err(|reason| builtins::desktop_failure(reason, line))?;
            match state {
                Some(state) => Ok(Value::Int(state)),
                None => Err(RuntimeError {
                    message: builtins::TARGET_WINDOW.to_string(),
                    line,
                }),
            }
        }
        "pid" => {
            let pid = rt
                .desktop()
                .window_pid(title)
                .map_err(|reason| builtins::desktop_failure(reason, line))?;
            match pid {
                Some(pid) => Ok(Value::Int(pid)),
                None => Err(RuntimeError {
                    message: builtins::TARGET_WINDOW.to_string(),
                    line,
                }),
            }
        }
        "processname" | "processpath" => {
            let pid = rt
                .desktop()
                .window_pid(title)
                .map_err(|reason| builtins::desktop_failure(reason, line))?;
            let Some(pid) = pid else {
                return Err(RuntimeError {
                    message: builtins::TARGET_WINDOW.to_string(),
                    line,
                });
            };
            let name = if sub_command.eq_ignore_ascii_case("processname") {
                rt.desktop().process_name(Some(&pid.to_string()))
            } else {
                rt.desktop().process_path(Some(&pid.to_string()))
            };
            match name
                .map_err(|reason| builtins::desktop_failure(reason, line))?
            {
                Some(name) => Ok(Value::Text(name)),
                None => Err(RuntimeError {
                    message: builtins::TARGET_WINDOW.to_string(),
                    line,
                }),
            }
        }
        "transparent" => rt
            .desktop()
            .window_trans_color(title)
            .map(Value::Text)
            .map_err(|reason| builtins::desktop_failure(reason, line)),
        "transcolor" => rt
            .desktop()
            .window_trans_color(title)
            .map(Value::Text)
            .map_err(|reason| builtins::desktop_failure(reason, line)),
        "style" => rt
            .desktop()
            .window_style(title, false)
            .map(Value::Int)
            .map_err(|reason| builtins::desktop_failure(reason, line)),
        "exstyle" => rt
            .desktop()
            .window_style(title, true)
            .map(Value::Int)
            .map_err(|reason| builtins::desktop_failure(reason, line)),
        // The controls of a window are the ones of the window of the
        // script: the desktop of the box publishes the controls of the
        // window of the script and no other.
        "controllist" | "controllisthwnd" => {
            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 WinGet is not known."),
            line,
        }),
    }
}

/// `WinWait, WinTitle, WinText, Timeout, ExcludeTitle, ExcludeText`: wait
/// for a window.
///
/// The order of the parameters of the v1 is the title, the text of the
/// window, the timeout and the two exclusions, and the order of the v2 is
/// the title, the text of the window, the timeout and the two exclusions
/// as well -- the two dialects put the timeout in the third place.
/// Measured on the binary of v1.1.37.02 on 2026-11-14: the third
/// parameter is the timeout, and the two exclusions are read and not
/// refused.
///
/// The `ErrorLevel` is one when the wait ran out and zero when it found
/// a window, and a window that is found becomes the last found window:
/// measured on the binary of v1.1.37.02 on 2026-11-14.
pub(crate) fn win_wait(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::win_wait(rt, &the_values_of_a_wait(values), line, 0);
    the_wait_that_goes_on(rt, answer)
}

/// `WinWaitActive, WinTitle, ...`: wait for a window to have the focus.
pub(crate) fn win_wait_active(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::win_wait_active(rt, &the_values_of_a_wait(values), line, 0);
    the_wait_that_goes_on(rt, answer)
}

/// `WinWaitClose, WinTitle, ...`: wait for a window to be gone.
///
/// The wait for the close does not change the last found window: the
/// window it waits for is gone.
pub(crate) fn win_wait_close(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let answer = builtins::win_wait_close(rt, &the_values_of_a_wait(values), line, 0);
    the_wait_that_goes_on(rt, answer)
}

/// The answer of a wait of the v1.
///
/// The `ErrorLevel` is one when the wait ran out and zero when it found a
/// window, and the window that it found is the last found window of the
/// v1: measured on the binary of v1.1.37.02 on 2026-11-14.
fn the_wait_that_goes_on(
    rt: &mut Runtime<'_>,
    answer: Result<Value, RuntimeError>,
) -> Result<Value, RuntimeError> {
    match answer {
        Ok(value) => {
            let found = value.to_text();
            // The wait that found nothing does not take the last found
            // window away: measured on the binary of v1.1.37.02 on
            // 2026-11-14, a wait that runs out leaves the window that an
            // earlier wait found where it was.
            if !found.is_empty() && found != "0" {
                rt.remember_the_last_window_of_the_v1(&found);
                rt.set_the_error_level(Value::Int(0));
            } else {
                rt.set_the_error_level(Value::Int(1));
            }
            Ok(value)
        }
        Err(failure) => {
            rt.set_the_error_level(Value::Int(1));
            rt.note(format!(
                "the command of the wait did not do the thing: {}",
                failure.message
            ));
            Ok(Value::Int(0))
        }
    }
}

/// The values of a command of the `WinWait` family of the v1, in the
/// order of the v2.
///
/// The v1 is the title, the text of the window, the timeout and the two
/// exclusions, and the v2 is the title, the text of the window, the
/// timeout and the two exclusions as well: the timeout is in the third
/// place of the two dialects. Measured on the binary of v1.1.37.02 on
/// 2026-11-14: the timeout of the v1 is the third parameter, and the two
/// exclusions are read and not refused.
///
/// The timeout that the script did not write is the timeout that does
/// not end, and the zero is the meio segundo: measured on the binary of
/// v1.1.37.02 on 2026-11-14, the `WinWait, titulo` without a timeout
/// waits forever, and the `WinWait, titulo, , 0` waits the meio
/// segundo. This is why the timeout that is missing is a value that is
/// not a number, and not the zero.
fn the_values_of_a_wait(values: &[Value]) -> Vec<Value> {
    let mut answer: Vec<Value> = values.iter().take(5).cloned().collect();
    while answer.len() < 3 {
        answer.push(Value::Text(String::new()));
    }
    answer
}

/// The command of the v1 that acts on a window, and whose failure is a
/// note and not a failure of the script.
///
/// The `ErrorLevel` is one when the command did not do the thing.
fn the_act_on_a_window(
    rt: &mut Runtime<'_>,
    name: &str,
    values: &[Value],
    line: u32,
    handler: BuiltinHandler,
) -> Result<Value, RuntimeError> {
    let answer = handler(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 {name} did not do the thing: {}",
                failure.message
            ));
            Ok(Value::Text(String::new()))
        }
    }
}

/// `WinActivate, WinTitle, ...`: give the focus to a window.
pub(crate) fn win_activate(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_act_on_a_window(rt, "WinActivate", values, line, builtins::win_activate)
}

/// `WinActivateBottom, WinTitle, ...`: give the focus to the bottom of the
/// windows that match.
pub(crate) fn win_activate_bottom(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_act_on_a_window(
        rt,
        "WinActivateBottom",
        values,
        line,
        builtins::win_activate_bottom,
    )
}

/// `WinHide, WinTitle, ...`: take a window off the screen.
pub(crate) fn win_hide(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_act_on_a_window(rt, "WinHide", values, line, builtins::win_hide)
}

/// `WinShow, WinTitle, ...`: put a window back on the screen.
pub(crate) fn win_show(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_act_on_a_window(rt, "WinShow", values, line, builtins::win_show)
}

/// `WinMinimize, WinTitle, ...`: minimize a window.
pub(crate) fn win_minimize(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_act_on_a_window(rt, "WinMinimize", values, line, builtins::win_minimize)
}

/// `WinMaximize, WinTitle, ...`: maximize a window.
pub(crate) fn win_maximize(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_act_on_a_window(rt, "WinMaximize", values, line, builtins::win_maximize)
}

/// `WinRestore, WinTitle, ...`: put a window back to its size.
pub(crate) fn win_restore(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_act_on_a_window(rt, "WinRestore", values, line, builtins::win_restore)
}

/// `WinMove, WinTitle, ..., X, Y, Width, Height`: move a window.
pub(crate) fn win_move(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_act_on_a_window(rt, "WinMove", values, line, builtins::win_move)
}

/// `WinSetTitle, NewTitle, WinTitle, ...`: give a window another title.
pub(crate) fn win_set_title(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_act_on_a_window(rt, "WinSetTitle", values, line, builtins::win_set_title)
}

/// `WinClose, WinTitle, ...`: close a window.
pub(crate) fn win_close(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_act_on_a_window(rt, "WinClose", values, line, builtins::win_close)
}

/// `WinKill, WinTitle, ...`: close a window without asking it.
pub(crate) fn win_kill(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_act_on_a_window(rt, "WinKill", values, line, builtins::win_kill)
}

/// `WinMinimizeAll`: minimize every window of the session.
pub(crate) fn win_minimize_all(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_act_on_a_window(
        rt,
        "WinMinimizeAll",
        values,
        line,
        builtins::win_minimize_all,
    )
}

/// `WinSet, SubCommand, ...`: a change to the state of a window.
///
/// The sub-command names the change, and the v2 has a name for each one
/// of them.
pub(crate) fn win_set(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let sub_command = values
        .first()
        .map(|value| value.to_text())
        .unwrap_or_default();
    let title = values.get(1).map(|value| value.to_text()).unwrap_or_default();
    let answer = the_change_of_the_sub_command(rt, &sub_command, &title, 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 WinSet did not do the thing: {}",
                failure.message
            ));
            Ok(Value::Text(String::new()))
        }
    }
}

/// The change that the sub-command of the `WinSet` names.
fn the_change_of_the_sub_command(
    rt: &mut Runtime<'_>,
    sub_command: &str,
    title: &str,
    line: u32,
) -> Result<Value, RuntimeError> {
    let mode = crate::settings::title_match_mode();
    match sub_command.to_ascii_lowercase().as_str() {
        "alwaysontop" => {
            let windows = rt
                .desktop()
                .matching_windows(title, mode)
                .map_err(|reason| builtins::desktop_failure(reason, line))?;
            let Some(window) = windows.first() else {
                return Err(RuntimeError {
                    message: builtins::TARGET_WINDOW.to_string(),
                    line,
                });
            };
            let info = rt
                .desktop()
                .windows()
                .map_err(|reason| builtins::desktop_failure(reason, line))?;
            let Some(info) = info.iter().find(|other| other.id.to_string() == window.id) else {
                return Err(RuntimeError {
                    message: builtins::TARGET_WINDOW.to_string(),
                    line,
                });
            };
            rt.desktop()
                .set_always_on_top(info, true)
                .map_err(|reason| builtins::desktop_failure(reason, line))?;
            Ok(Value::Text(String::new()))
        }
        "style" | "exstyle" => {
            let style = rt
                .desktop()
                .window_style(title, sub_command.eq_ignore_ascii_case("exstyle"))
                .map_err(|reason| builtins::desktop_failure(reason, line))?;
            rt.desktop()
                .window_set_style(title, style, sub_command.eq_ignore_ascii_case("exstyle"))
                .map_err(|reason| builtins::desktop_failure(reason, line))?;
            Ok(Value::Text(String::new()))
        }
        "transparent" => {
            let color = rt
                .desktop()
                .window_trans_color(title)
                .map_err(|reason| builtins::desktop_failure(reason, line))?;
            rt.desktop()
                .window_set_trans_color(title, &color)
                .map_err(|reason| builtins::desktop_failure(reason, line))?;
            Ok(Value::Text(String::new()))
        }
        "transcolor" => {
            let color = rt
                .desktop()
                .window_trans_color(title)
                .map_err(|reason| builtins::desktop_failure(reason, line))?;
            rt.desktop()
                .window_set_trans_color(title, &color)
                .map_err(|reason| builtins::desktop_failure(reason, line))?;
            Ok(Value::Text(String::new()))
        }
        _ => Err(RuntimeError {
            message: format!("the sub-command {sub_command} of the WinSet is not known."),
            line,
        }),
    }
}

/// `WinMenuSelectItem, WinTitle, ..., Item1, Item2, ...`: choose an item
/// of the menu of a window.
///
/// The menu of another program is not read by this runtime, and the menu
/// of the window of the script is: the refusal says so.
pub(crate) fn win_menu_select_item(
    rt: &mut Runtime<'_>,
    _values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The menu of the window of the script is drawn by the helper, and the
    // items of it are the ones of the helper.
    rt.desktop()
        .gui_menu_bar("{}")
        .map_err(|reason| builtins::desktop_failure(reason, line))?;
    Err(RuntimeError {
        message: "the menu of another program is not read by this runtime, and the menu of the window of the script is not read either.".to_string(),
        line,
    })
}