walkit 0.10.4

Modern Winamp skin engine: .wal skins, MAKI scripts, a draw list for any renderer
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
// SPDX-License-Identifier: GPL-3.0-or-later

//! Touches: what a finger at a point of the stack means, presses, moves and releases, the
//! skin's menus, and the button actions and config values the objects drive.

use std::collections::HashMap;

use super::{SkinRuntime, HOST_WINDOWS};
use crate::draw::Rect;
use crate::gui::{Kind, ObjId};
use crate::host::SkinMenu;
use crate::maki::{Handle, Value};

/// Menus a script may pop in reply to one touch; more answer 0 without showing.
const MAX_MENUS_PER_GESTURE: i32 = 3;
/// The id of a wasabi title bar's group, and of the layer over the whole bar that takes its drags.
const TITLE_BAR: &str = "wasabi.titlebar";
const TITLE_BAR_TRAP: &str = "mousetrap";
/// The edges a resize grip's `resize` names.
const GRIP_EDGES: [&str; 4] = ["left", "right", "top", "bottom"];
/// The actions whose state `action_state` reads.
const STATE_ACTIONS: [&str; 3] = ["TOGGLE", "EQ_TOGGLE", "EQ_AUTO"];
/// The events of a press or a move; an object a script watches only for others takes no touch beside it.
const POINTER_EVENTS: [&str; 9] = [
    "onleftbuttondown",
    "onleftbuttonup",
    "onrightbuttondown",
    "onrightbuttonup",
    "onleftbuttondblclk",
    "onrightbuttondblclk",
    "onmousemove",
    "onleftclick",
    "onrightclick",
];
/// The events a tap fires on an object that is not a control: the left button going down and up.
const TAP_EVENTS: [&str; 2] = ["onleftbuttondown", "onleftbuttonup"];
/// The event of a finger moving while it presses.
const FOLLOW_EVENTS: [&str; 1] = ["onmousemove"];
/// The event of the left button going down.
const PRESS_EVENTS: [&str; 1] = ["onleftbuttondown"];

/// A drag on a resize grip: the window it resizes, the edges it moves, and where the finger
/// went down and the window's size then, in the window's pixels.
#[derive(Debug, Clone)]
struct Resize {
    window: ObjId,
    edges: String,
    x: i32,
    y: i32,
    size: (i32, i32),
    /// The steps the size takes, for a classic skin's grip.
    steps: Option<(i32, i32)>,
}

/// A press its object has not heard yet: the object, and the point of the stack the finger went down on.
#[derive(Debug, Clone, Copy)]
struct DeferredPress {
    target: ObjId,
    sx: i32,
    sy: i32,
}

/// The object with a skin menu a touch landed on: the touch's seq, and the point in the object's window.
#[derive(Debug, Clone, Copy)]
struct MenuAim {
    seq: i32,
    target: ObjId,
    x: i32,
    y: i32,
}

/// What the pointer machinery keeps between calls.
#[derive(Debug, Default)]
pub(crate) struct PointerState {
    captured_origin: Rect,
    /// The scale of the window the press went down in; 0 before any press.
    captured_scale: f32,
    /// Where the last touch went down, in the stack.
    down_at: Option<(i32, i32)>,
    deferred: Option<DeferredPress>,
    resizing: Option<Resize>,
    menu_aim: Option<MenuAim>,
    move_seq: Option<i32>,
    aimed: Option<ObjId>,
    pub(crate) gesture_depth: i32,
    menus_this_gesture: i32,
    menus_ended: bool,
    pub(crate) picked_this_gesture: bool,
    pub(crate) press_ended: bool,
    entered: bool,
    cancelling: bool,
    menu_refusals_logged: Vec<String>,
    /// What `has_skin_menu` answered for each object since the last layout pass.
    pub(crate) skin_menus: HashMap<ObjId, bool>,
    skin_menu_reads: i64,
    /// Whether the moves and the release of the press now held land exactly where they say: a
    /// host's magnifier steers them, so no touch slop keeps the press on its control.
    pub(crate) precise: bool,
    /// The keys held with the press now held, as the host said before it went down: Ctrl, and Shift.
    pub(crate) ctrl: bool,
    pub(crate) shift: bool,
}

impl SkinRuntime {
    /// The window under a point of the stack, or the nearest within the touch slop.
    pub(crate) fn window_at(&mut self, x: i32, y: i32) -> Option<ObjId> {
        if self.needs_layout {
            self.do_layout();
        }
        if let Some(a) = self.pointer.aimed {
            return Some(a);
        }
        let windows = self.z_windows();
        // apart, a window takes a touch only where it docks: Winamp Modern's main window is
        // shaped around its closed drawer, and a touch there reaches the window under it
        if self.free_windows() {
            if let Some(w) = windows
                .iter()
                .rev()
                .find(|l| self.docking_rect(**l).contains(x, y))
            {
                return Some(*w);
            }
        }
        let distance2 = |r: Rect| -> i64 {
            let dx = (r.left - x).max(0).max(x - (r.right() - 1)) as i64;
            let dy = (r.top - y).max(0).max(y - (r.bottom() - 1)) as i64;
            dx * dx + dy * dy
        };
        if let Some(w) = windows
            .iter()
            .rev()
            .find(|l| self.window_rect_of(**l).contains(x, y))
        {
            return Some(*w);
        }
        let slop = self.touch_slop as i64;
        windows
            .iter()
            .copied()
            .min_by_key(|l| distance2(self.window_rect_of(*l)))
            .filter(|l| distance2(self.window_rect_of(*l)) <= slop * slop)
    }

    /// Runs `block` with the point `x`, `y` of `window` as a point of the stack, the touch kept to that window.
    fn in_window<T>(
        &mut self,
        window: crate::host::WindowId,
        x: i32,
        y: i32,
        block: impl FnOnce(&mut Self, i32, i32) -> T,
    ) -> T {
        let l = self.layouts_by_id_lookup(window);
        if self.needs_layout {
            self.do_layout();
        }
        let origin = self.window_rect_of(l);
        let before = self.pointer.aimed;
        self.pointer.aimed = Some(l);
        let r = block(self, origin.left + x, origin.top + y);
        self.pointer.aimed = before;
        r
    }

    fn layouts_by_id_lookup(&self, id: crate::host::WindowId) -> ObjId {
        self.layouts_by_id[(id.0 as usize).wrapping_sub(1)]
    }

    /// `pointer_down` at a point of `window`, in that window's pixels.
    pub fn pointer_down_in(&mut self, window: crate::host::WindowId, x: i32, y: i32, seq: i32) {
        self.in_window(window, x, y, |rt, sx, sy| rt.pointer_down(sx, sy, seq));
    }

    /// `pointer_move` at a point of `window`, in that window's pixels.
    pub fn pointer_move_in(&mut self, window: crate::host::WindowId, x: i32, y: i32) {
        self.in_window(window, x, y, |rt, sx, sy| rt.pointer_move(sx, sy));
    }

    /// `pointer_up` at a point of `window`, in that window's pixels.
    pub fn pointer_up_in(&mut self, window: crate::host::WindowId, x: i32, y: i32) {
        self.in_window(window, x, y, |rt, sx, sy| rt.pointer_up(sx, sy));
    }

    /// `double_tap` at a point of `window`, in that window's pixels.
    pub fn double_tap_in(&mut self, window: crate::host::WindowId, x: i32, y: i32, seq: i32) {
        self.in_window(window, x, y, |rt, sx, sy| rt.double_tap(sx, sy, seq));
    }

    /// A point of the stack in the pressed window's layout pixels.
    fn captured_local(&self, sx: i32, sy: i32) -> (i32, i32) {
        let at = self.pointer.captured_origin;
        let s = if self.pointer.captured_scale > 0.0 {
            self.pointer.captured_scale
        } else {
            1.0
        };
        (
            ((sx - at.left) as f32 / s).floor() as i32,
            ((sy - at.top) as f32 / s).floor() as i32,
        )
    }

    /// The topmost object at a point of the stack.
    pub(crate) fn hit_test_stack(&mut self, x: i32, y: i32) -> Option<ObjId> {
        let l = self.window_at(x, y)?;
        let (x, y) = self.layout_point(l, x, y);
        self.hit_test(l, x, y)
    }

    /// Whether a touch on `o` does something: a control, or an object a script listens to.
    fn reacts(&self, o: ObjId) -> bool {
        self.is_control(o) || self.scripts.iter().any(|s| s.listens_to(Handle::Gui(o)))
    }

    fn is_control(&self, o: ObjId) -> bool {
        matches!(
            self.objects[o].kind,
            Kind::Button(_)
                | Kind::Slider(_)
                | Kind::ColorThemeList(_)
                | Kind::PlaylistView(_)
                | Kind::ClassicWindow(_)
        ) || self.is_grip(o)
    }

    /// Whether a classic stack stretches to fill the view, where its grips size nothing.
    pub(crate) fn classic_filled(&self) -> bool {
        self.stretch_last && self.view_size.is_some() && !self.free_windows()
    }

    /// Whether `o` is a window's resize grip: its `resize`, as a script last set it, names an edge, and it lies in a window.
    pub(crate) fn is_grip(&self, o: ObjId) -> bool {
        let Some(edges) = self.objects[o]
            .base
            .attr("resize")
            .map(|e| e.to_lowercase())
        else {
            return false;
        };
        self.layout_object(o).is_some() && GRIP_EDGES.iter().any(|e| edges.contains(e))
    }

    /// Sizes the window as the finger at `x`, `y` drags its grip, as Winamp sizes it. Apart,
    /// the edges the grip moves snap to the viewport and to the other windows, and a window
    /// whose left or top edge moves keeps its right or bottom edge where it was.
    fn drag_grip(&mut self, r: &Resize, x: i32, y: i32) {
        let l = r.window;
        let (mut w, mut h) = r.size;
        if r.edges.contains("right") {
            w += x - r.x;
        }
        if r.edges.contains("left") {
            w -= x - r.x;
        }
        if r.edges.contains("bottom") {
            h += y - r.y;
        }
        if r.edges.contains("top") {
            h -= y - r.y;
        }
        let apart = self.free_windows();
        let at = self.window_rect_of(l);
        let scale = self.layout_scale(l);
        let on_screen = |v: i32| (v as f32 * scale).round() as i32;
        let in_layout = |v: i32| (v as f32 / scale).round() as i32;
        if apart {
            let mut want = Rect::new(at.left, at.top, on_screen(w), on_screen(h));
            if r.edges.contains("left") {
                want.left = at.right() - want.width;
            }
            if r.edges.contains("top") {
                want.top = at.bottom() - want.height;
            }
            let got = self.autodock_edges(l, want, &r.edges);
            w = in_layout(got.width);
            h = in_layout(got.height);
        }
        let (vw, vh) = self.viewport();
        let (vw, vh) = (in_layout(vw), in_layout(vh));
        let d = self.objects[l].layout().expect("a layout");
        let mut size = (
            within(w, d.min_w, d.max_w, vw),
            within(h, d.min_h, d.max_h, vh),
        );
        if let Some((sw, sh)) = r.steps {
            let horizontal = r.edges.contains("left") || r.edges.contains("right");
            let vertical = r.edges.contains("top") || r.edges.contains("bottom");
            if horizontal {
                size.0 = stepped(size.0, sw, |v| within(v, d.min_w, d.max_w, vw));
            }
            if vertical {
                size.1 = stepped(size.1, sh, |v| within(v, d.min_h, d.max_h, vh));
            }
        }
        if Some(l) != self.main_layout() {
            self.objects[l].layout_mut().expect("a layout").user_size = Some(size);
        }
        if apart {
            let x = if r.edges.contains("left") {
                at.right() - on_screen(size.0)
            } else {
                at.left
            };
            let y = if r.edges.contains("top") {
                at.bottom() - on_screen(size.1)
            } else {
                at.top
            };
            let d = self.objects[l].layout_mut().expect("a layout");
            d.view_x = x;
            d.view_y = y;
        }
        if size != self.layout_size(l) {
            self.resize_layout_to(l, size.0, size.1);
        }
    }

    /// The grip drag ends: the window hears that the user resized it.
    fn end_grip(&mut self) {
        let Some(r) = self.pointer.resizing.take() else {
            return;
        };
        let l = r.window;
        let (w, h) = self.layout_size(l);
        let d = self.objects[l].layout().expect("a layout");
        let (vx, vy) = (d.view_x, d.view_y);
        self.dispatch(
            Handle::Gui(l),
            "onuserresize",
            &[Value::Int(vx), Value::Int(vy), Value::Int(w), Value::Int(h)],
        );
    }

    /// Whether a script hears a tap on `o`: one listens to it for the tap events, or to the group
    /// that exposes it as its xui child.
    fn hears_tap(&self, o: ObjId) -> bool {
        self.dispatch_chain(o).iter().any(|c| {
            self.scripts
                .iter()
                .any(|s| s.listens_to_any(Handle::Gui(*c), &TAP_EVENTS))
        })
    }

    /// Whether a script follows the finger across `o`, or across the group that exposes it.
    fn follows_finger(&mut self, o: ObjId) -> bool {
        let chain = self.dispatch_chain(o);
        let mut any = false;
        for c in &chain {
            for s in 0..self.scripts.len() {
                if self.scripts[s].listens_to_any(Handle::Gui(*c), &FOLLOW_EVENTS)
                    || self.scripts[s].reads_mouse(Handle::Gui(*c), &PRESS_EVENTS)
                {
                    any = true;
                }
            }
        }
        self.take_script_logs();
        any
    }

    /// Whether a mouse could click `o` in `window` at one of a few of its points.
    fn clickable(&mut self, o: ObjId, window: ObjId, x: i32, y: i32) -> bool {
        let r = self.objects[o].base.rect;
        let right = r.right() - 1;
        let bottom = r.bottom() - 1;
        let points = [
            (
                x.clamp(r.left, right.max(r.left)),
                y.clamp(r.top, bottom.max(r.top)),
            ),
            ((r.left + right) / 2, (r.top + bottom) / 2),
            (r.left, r.top),
            (right, r.top),
            (r.left, bottom),
            (right, bottom),
        ];
        points.iter().any(|(px, py)| {
            let mut at = self.hit_test(window, *px, *py);
            while let Some(h) = at {
                if h == o {
                    return true;
                }
                at = self.objects[h].base.parent;
            }
            false
        })
    }

    /// Squared distance from a point to `o`'s rectangle; 0 inside.
    pub(crate) fn distance2(&self, o: ObjId, x: i32, y: i32) -> i64 {
        let r = self.objects[o].base.rect;
        let dx = (r.left - x).max(0).max(x - (r.right() - 1)) as i64;
        let dy = (r.top - y).max(0).max(y - (r.bottom() - 1)) as i64;
        dx * dx + dy * dy
    }

    /// What a finger at a point means, in the order the checks below run.
    pub(crate) fn touch_target(&mut self, sx: i32, sy: i32) -> Option<ObjId> {
        let window = self.window_at(sx, sy)?;
        let (x, y) = self.layout_point(window, sx, sy);
        let hit = self.hit_test(window, x, y);
        if let Some(h) = hit {
            if let Some(grip) = self.classic_grip_near(h, x, y) {
                return Some(grip);
            }
            // a status bar is hit only on its command buttons, which sit over the frame's
            // resize corner in MMD3
            if self.is_control(h)
                || matches!(self.objects[h].kind, Kind::Menu(_) | Kind::LayoutStatus(_))
            {
                return Some(h);
            }
        }
        let slop2 = (self.touch_slop as i64) * (self.touch_slop as i64);
        let objects = self.all_objects.clone();
        let nearest = |rt: &mut SkinRuntime,
                       shown: bool,
                       pick: &dyn Fn(&SkinRuntime, ObjId) -> bool|
         -> Option<ObjId> {
            let mut best: Option<(ObjId, i64)> = None;
            for o in objects.iter().rev().copied() {
                if rt.layout_object(o) != Some(window) || !rt.touchable(o, shown) {
                    continue;
                }
                let d = rt.distance2(o, x, y);
                if d > slop2 || !pick(rt, o) {
                    continue;
                }
                if shown && !rt.clickable(o, window, x, y) {
                    continue;
                }
                if best.is_none_or(|(_, bd)| d < bd) {
                    best = Some((o, d));
                }
            }
            best.map(|(o, _)| o)
        };
        let control = nearest(self, true, &|rt, o| rt.is_control(o));
        if let Some(h) = hit {
            if self.hears_tap(h)
                && !control.is_some_and(|c| {
                    self.objects[c]
                        .base
                        .rect
                        .overlaps(&self.objects[h].base.rect)
                })
            {
                return Some(h);
            }
        }
        if let Some(c) = control {
            return Some(c);
        }
        if let Some(h) = hit.filter(|h| self.reacts(*h)) {
            return Some(h);
        }
        if let Some(o) = nearest(self, false, &|rt, o| {
            !rt.is_control(o)
                && rt
                    .scripts
                    .iter()
                    .any(|s| s.listens_to_any(Handle::Gui(o), &POINTER_EVENTS))
        }) {
            return Some(o);
        }
        hit
    }

    /// Pointer events take points of the stack; objects hear points of their window. `seq`
    /// names this touch for the menu and move targets and `right_click`.
    pub fn pointer_down(&mut self, sx: i32, sy: i32, seq: i32) {
        self.gesture(true, |rt| {
            rt.aim_menu(sx, sy, seq);
            rt.pointer.move_seq = None;
            rt.pointer.precise = false;
            // apart, a press raises its window; a press on the desktop between the windows
            // reaches no window (window_at falls back to the nearest one for the stack)
            if rt.free_windows() {
                if let Some(w) = rt.window_under(sx, sy) {
                    rt.raise_window(w);
                }
            }
            let touched = rt.pointer_down_at(sx, sy);
            // a press on no object moves the window; a press that opened a menu has been let go of, and
            // moves nothing; a press held back from an object with a skin menu moves the window as a
            // press on that object would
            let held = rt.captured.or(rt.pointer.deferred.map(|d| d.target));
            if touched.is_none() || held.is_some_and(|h| rt.moves_window(h)) {
                rt.pointer.move_seq = Some(seq);
                // set out apart, the window under the finger moves with it
                if rt.free_windows() {
                    if let Some(w) = rt.window_under(sx, sy) {
                        rt.free_drag_begin(w, sx, sy);
                    }
                }
            }
        });
    }

    /// Presses what a finger at a point of the stack means, and returns it; `None` for nothing.
    fn pointer_down_at(&mut self, sx: i32, sy: i32) -> Option<ObjId> {
        self.drop_deferred();
        if self.needs_layout {
            self.do_layout();
        }
        let target = self.touch_target(sx, sy)?;
        // the touched window takes the focus, as a press of either mouse button gives it
        if let Some(l) = self.layout_object(target) {
            self.take_focus(l);
        }
        if self.pointer.menu_aim.is_some_and(|a| a.target == target)
            && !matches!(self.objects[target].kind, Kind::Slider(_))
        {
            self.pointer.deferred = Some(DeferredPress { target, sx, sy });
            self.show_pressed(target, true);
            return Some(target);
        }
        self.press(target, sx, sy);
        Some(target)
    }

    /// Shows a held press's button pressed, or no longer; its scripts hear nothing of it.
    fn show_pressed(&mut self, target: ObjId, pressed: bool) {
        if let Kind::Button(b) = &mut self.objects[target].kind {
            b.pressed = pressed;
            self.repaint();
        }
    }

    /// The object hears the button go down at a point of the stack, and the finger come in.
    fn press(&mut self, target: ObjId, sx: i32, sy: i32) {
        let window = self.layout_object(target);
        self.pointer.captured_origin = window.map_or(Rect::EMPTY, |l| self.window_rect_of(l));
        self.pointer.captured_scale = window.map_or(1.0, |l| self.layout_scale(l));
        let (x, y) = self.captured_local(sx, sy);
        self.last_pointer = (x, y);
        self.captured = Some(target);
        if let Some(window) = self.layout_object(target) {
            // a classic stack stretched to fill the view keeps its size: its grip sizes nothing
            let filled =
                self.classic_filled() && self.objects[target].base.id.starts_with("classic.");
            if self.is_grip(target) && !filled {
                let edges = self.objects[target]
                    .base
                    .attr("resize")
                    .unwrap_or("")
                    .to_lowercase();
                let size = self.layout_size(window);
                let steps = self.objects[target]
                    .base
                    .id
                    .starts_with("classic.")
                    .then_some(crate::classic::touch::CLASSIC_SIZE_STEP);
                self.pointer.resizing = Some(Resize {
                    window,
                    edges,
                    x,
                    y,
                    size,
                    steps,
                });
            }
        }
        self.object_pointer_down(target, x, y);
        // a menu the press opened has let go of it already
        if self.captured == Some(target) {
            self.pointer.entered = true;
            self.dispatch(Handle::Gui(target), "onenterarea", &[]);
        }
    }

    /// The finger moves to a point of the stack.
    pub fn pointer_move(&mut self, sx: i32, sy: i32) {
        self.gesture(false, |rt| rt.pointer_move_at(sx, sy));
    }

    /// Sends the deferred press where the finger went down, unless its object has gone from the skin.
    fn send_deferred(&mut self) {
        let Some(d) = self.pointer.deferred else {
            return;
        };
        self.drop_deferred();
        if self.needs_layout {
            self.do_layout();
        }
        if self.all_objects.contains(&d.target) {
            self.press(d.target, d.sx, d.sy);
        }
    }

    /// Lets the deferred press go unsent: its object hears nothing of it.
    fn drop_deferred(&mut self) {
        let Some(d) = self.pointer.deferred.take() else {
            return;
        };
        self.show_pressed(d.target, false);
    }

    fn pointer_move_at(&mut self, sx: i32, sy: i32) {
        if self.free_dragging() {
            self.free_drag_to(sx, sy);
        }
        if let Some(d) = self.pointer.deferred {
            let dx = sx - d.sx;
            let dy = sy - d.sy;
            // still a tap or a long press
            if !self.pointer.precise && dx * dx + dy * dy <= self.touch_slop * self.touch_slop {
                return;
            }
            self.send_deferred();
        }
        let (x, y) = self.captured_local(sx, sy);
        self.last_pointer = (x, y);
        if let Some(r) = self.pointer.resizing.clone() {
            self.drag_grip(&r, x, y);
        }
        if let Some(c) = self.captured {
            if let Some(next) = self.eq_band_reached(c, sx, sy) {
                // the band lets go and the one the finger reached takes the drag, as pressed there
                self.object_pointer_up(c, x, y, true);
                self.leave_area(c);
                self.captured = Some(next);
                self.object_pointer_down(next, x, y);
                if self.captured == Some(next) {
                    self.pointer.entered = true;
                    self.dispatch(Handle::Gui(next), "onenterarea", &[]);
                }
                return;
            }
            self.object_pointer_move(c, x, y);
        }
    }

    /// The finger lifts at a point of the stack.
    pub fn pointer_up(&mut self, sx: i32, sy: i32) {
        self.gesture(false, |rt| rt.pointer_up_at(sx, sy));
    }

    fn pointer_up_at(&mut self, sx: i32, sy: i32) {
        // the browser may fold the last move into the release
        if self.free_dragging() {
            self.free_drag_to(sx, sy);
        }
        self.free_drag_end();
        self.send_deferred();
        let (x, y) = self.captured_local(sx, sy);
        self.last_pointer = (x, y);
        if let Some(r) = self.pointer.resizing.clone() {
            self.drag_grip(&r, x, y);
        }
        self.end_grip();
        let Some(target) = self.captured.take() else {
            return;
        };
        // a press a host's magnifier steered onto another control is let go as a click on
        // that control: the one it began on lets go outside, and the one under it is pressed
        // and let go
        if self.pointer.precise {
            if let Some(under) = self.hit_test_stack(sx, sy).filter(|u| {
                *u != target
                    && self.reacts(*u)
                    && !matches!(self.objects[*u].kind, Kind::ClassicWindow(_))
            }) {
                self.object_pointer_up(target, x, y, false);
                self.leave_area(target);
                self.pointer.precise = false;
                self.press(under, sx, sy);
                return self.pointer_up_at(sx, sy);
            }
        }
        // a finger that drifts a little still counts as on the control
        let r = self.objects[target].base.rect;
        let slop = if self.pointer.precise {
            0
        } else {
            self.touch_slop
        };
        let inside = x >= r.left - slop
            && x < r.right() + slop
            && y >= r.top - slop
            && y < r.bottom() + slop;
        self.object_pointer_up(target, x, y, inside);
        self.leave_area(target);
    }

    /// A second tap of a double tap, at a point of the stack.
    pub fn double_tap(&mut self, sx: i32, sy: i32, seq: i32) {
        self.gesture(true, |rt| {
            rt.aim_menu(sx, sy, seq);
            rt.pointer.move_seq = None;
            rt.double_tap_at(sx, sy);
        });
    }

    fn double_tap_at(&mut self, sx: i32, sy: i32) {
        self.drop_deferred();
        let Some(target) = self.hit_test_stack(sx, sy) else {
            return;
        };
        let (x, y) = match self.layout_object(target) {
            Some(l) => self.layout_point(l, sx, sy),
            None => (sx, sy),
        };
        self.object_double_tap(target, x, y);
    }

    /// The seq of the last press when it landed on an object with a skin menu, else `None`.
    pub fn menu_target(&self) -> Option<i32> {
        self.pointer.menu_aim.map(|a| a.seq)
    }

    /// The seq of the last press when it landed on no object, or the object it pressed moves the
    /// window; none while the windows are apart, where the engine moves them itself.
    pub fn move_target(&self) -> Option<i32> {
        if self.free.on {
            return None;
        }
        self.pointer.move_seq
    }

    /// Whether a drag that starts on `o` moves the window.
    pub(crate) fn moves_window(&mut self, o: ObjId) -> bool {
        if matches!(self.objects[o].kind, Kind::ClassicWindow(_)) {
            return self.classic_moves_window(o);
        }
        if matches!(
            self.objects[o].kind,
            Kind::Slider(_) | Kind::ColorThemeList(_) | Kind::PlaylistView(_)
        ) {
            return false;
        }
        if self.is_grip(o) {
            return false;
        }
        if matches!(self.objects[o].kind, Kind::Button(_) | Kind::Menu(_)) {
            return !self.follows_finger(o);
        }
        self.is_move_area(o) || !self.follows_finger(o)
    }

    /// Whether Winamp moves the window by a drag on `o`: what `o` writes in `move`, else what the
    /// nearest group around it writes; a wasabi title bar's mousetrap moves it unless it says otherwise.
    fn is_move_area(&self, o: ObjId) -> bool {
        if let Some(m) = self.objects[o].base.move_window {
            return m;
        }
        let b = &self.objects[o].base;
        if b.id == TITLE_BAR_TRAP
            && b.parent
                .is_some_and(|p| self.objects[p].base.id == TITLE_BAR)
        {
            return true;
        }
        let mut p = b.parent;
        while let Some(g) = p {
            if let Some(m) = self.objects[g].base.move_window {
                return m;
            }
            p = self.objects[g].base.parent;
        }
        false
    }

    /// Remembers the object with a skin menu under a touch at a point of the stack, or none.
    fn aim_menu(&mut self, sx: i32, sy: i32, seq: i32) {
        if self.needs_layout {
            self.do_layout();
        }
        self.pointer.menu_aim = self.menu_aim_at(sx, sy, seq);
        self.pointer.down_at = Some((sx, sy));
    }

    /// Where the touch going on went down, in the stack; `None` outside a touch.
    pub(crate) fn press_point(&self) -> Option<(i32, i32)> {
        self.pointer
            .down_at
            .filter(|_| self.pointer.gesture_depth > 0)
    }

    fn menu_aim_at(&mut self, sx: i32, sy: i32, seq: i32) -> Option<MenuAim> {
        let window = self.window_at(sx, sy)?;
        let (x, y) = self.layout_point(window, sx, sy);
        if let Some(target) = self.classic_row_menu_at(window, x, y) {
            return Some(MenuAim { seq, target, x, y });
        }
        let target = self.menu_object_at(window, x, y)?;
        Some(MenuAim { seq, target, x, y })
    }

    /// The object a right click at a point of `window` means, among objects with a skin menu only.
    fn menu_object_at(&mut self, window: ObjId, x: i32, y: i32) -> Option<ObjId> {
        let slop2 = (self.touch_slop as i64) * (self.touch_slop as i64);
        let mut best: Option<(ObjId, i64)> = None;
        for o in self.all_objects.clone().into_iter().rev() {
            if self.layout_object(o) != Some(window)
                || self.objects[o].base.ghost
                || !self.touchable(o, true)
            {
                continue;
            }
            let d = self.distance2(o, x, y);
            if d > slop2 {
                continue;
            }
            let has = if let Some(h) = self.pointer.skin_menus.get(&o) {
                *h
            } else {
                let h = self.has_skin_menu(o);
                self.pointer.skin_menus.insert(o, h);
                h
            };
            if has && best.is_none_or(|(_, bd)| d < bd) {
                best = Some((o, d));
            }
        }
        best.map(|(o, _)| o)
    }

    /// Whether a right click on `o` can open a menu of the skin's, read from the scripts'
    /// bytecode without running them.
    pub(crate) fn has_skin_menu(&mut self, o: ObjId) -> bool {
        self.pointer.skin_menu_reads += 1;
        let chain = self.dispatch_chain(o);
        let is_button = matches!(self.objects[o].kind, Kind::Button(_));
        let events = crate::maki::script::right_click_events(is_button);
        let mut reaches = false;
        for c in &chain {
            for s in 0..self.scripts.len() {
                if self.scripts[s].reaches_menu(Handle::Gui(*c), &events) {
                    reaches = true;
                }
            }
        }
        self.take_script_logs();
        if reaches {
            return true;
        }
        let mut called: Vec<String> = Vec::new();
        for c in &chain {
            for s in 0..self.scripts.len() {
                for e in self.scripts[s].events_called(Handle::Gui(*c), &events) {
                    if !called.contains(&e) {
                        called.push(e);
                    }
                }
            }
        }
        let called: Vec<&str> = called.iter().map(|s| s.as_str()).collect();
        let mut any = false;
        if !called.is_empty() {
            for c in &chain {
                for s in 0..self.scripts.len() {
                    if self.scripts[s].reaches_menu(Handle::Gui(*c), &called) {
                        any = true;
                    }
                }
            }
        }
        self.take_script_logs();
        any
    }

    /// Writes the lines the scripts' bytecode walks asked to log.
    fn take_script_logs(&mut self) {
        for s in 0..self.scripts.len() {
            if let Some(line) = self.scripts[s].pending_log.take() {
                self.host.log(&line);
            }
        }
    }

    /// The objects an event on `o` fires on: `o`, then each group that exposes the one before as its xui child.
    fn dispatch_chain(&self, o: ObjId) -> Vec<ObjId> {
        let mut chain = vec![o];
        let mut at = o;
        while let Some(p) = self.objects[at].base.parent {
            let exposes = self.objects[p]
                .group
                .as_ref()
                .is_some_and(|g| g.embed_xui.as_deref() == Some(self.objects[at].base.id.as_str()));
            if !exposes || chain.contains(&p) {
                break;
            }
            chain.push(p);
            at = p;
        }
        chain
    }

    /// A right click on the object the touch `seq` landed on, at the point it landed, as a separate touch.
    pub fn right_click(&mut self, seq: i32) {
        self.gesture(true, |rt| {
            if let Some(aim) = rt.pointer.menu_aim.filter(|a| a.seq == seq) {
                rt.right_click_at(aim);
            }
        });
    }

    fn right_click_at(&mut self, aim: MenuAim) {
        // the touch was a long press: a deferred press goes nowhere
        self.drop_deferred();
        if self.needs_layout {
            self.do_layout();
        }
        if !self.all_objects.contains(&aim.target) {
            return;
        }
        // a press still held lets go first, as a right click takes the mouse
        if self.captured.is_some() {
            self.end_press();
        }
        self.last_pointer = (aim.x, aim.y);
        self.object_right_click(aim.target, aim.x, aim.y);
        if matches!(self.objects[aim.target].kind, Kind::Button(_)) {
            self.dispatch(Handle::Gui(aim.target), "onrightclick", &[]);
        }
    }

    /// Runs `block` as a touch the listener made, from which a script may pop a menu. `fresh`
    /// starts a new touch, whose menu count starts over.
    pub fn gesture<T>(&mut self, fresh: bool, block: impl FnOnce(&mut Self) -> T) -> T {
        self.gesture_begin(fresh);
        let r = block(self);
        self.gesture_end();
        r
    }

    /// Starts a touch the listener made, as [`SkinRuntime::gesture`] does around its block, for
    /// a host across a boundary that cannot pass the block; [`SkinRuntime::gesture_end`] ends it.
    pub fn gesture_begin(&mut self, fresh: bool) {
        if fresh {
            self.pointer.menus_this_gesture = 0;
            self.pointer.menus_ended = false;
            self.pointer.picked_this_gesture = false;
            self.pointer.press_ended = false;
        }
        self.pointer.gesture_depth += 1;
    }

    /// Ends the touch [`SkinRuntime::gesture_begin`] started; one that was not started ends nothing.
    pub fn gesture_end(&mut self) {
        self.pointer.gesture_depth = self.pointer.gesture_depth.saturating_sub(1);
    }

    /// The listener's pick from a menu a script popped, by command id, or 0.
    pub fn menu_choice(&mut self, menu: &SkinMenu) -> i32 {
        let refusal = if self.pointer.gesture_depth == 0 {
            Some("outside a touch".to_string())
        } else if self.pointer.menus_ended {
            Some("after one closed without the listener".to_string())
        } else if self.pointer.cancelling {
            Some("while a press ends without a release".to_string())
        } else if self.pointer.menus_this_gesture >= MAX_MENUS_PER_GESTURE {
            Some(format!("more than {MAX_MENUS_PER_GESTURE} in one touch"))
        } else {
            None
        };
        if let Some(refusal) = refusal {
            if !self.pointer.menu_refusals_logged.contains(&refusal) {
                self.pointer.menu_refusals_logged.push(refusal.clone());
                self.host.log(&format!("popup menu {refusal}: not shown"));
            }
            return 0;
        }
        self.pointer.menus_this_gesture += 1;
        self.end_press();
        let picked = self.host.choose_from_menu(menu);
        if picked.is_none() {
            self.pointer.menus_ended = true;
        }
        if picked.unwrap_or(0) != 0 {
            self.pointer.picked_this_gesture = true;
        }
        picked.unwrap_or(0)
    }

    /// Makes the moves and the release of the press now held land exactly where they say, as a
    /// mouse's do: no touch slop keeps the press on its control or a finger on a button. For a
    /// host's magnifier, which steers the press with a finger geared down; the next
    /// `pointer_down` turns it off.
    pub fn set_pointer_precise(&mut self, precise: bool) {
        self.pointer.precise = precise;
    }

    /// The keys held with the next press, from a keyboard beside a mouse or a finger: Ctrl and
    /// Shift. A classic playlist's row takes them as Winamp's does, Ctrl adding a row to the
    /// selection or taking it out, Shift selecting the rows from the last one picked. They hold
    /// until the host says again.
    pub fn set_pointer_modifiers(&mut self, ctrl: bool, shift: bool) {
        self.pointer.ctrl = ctrl;
        self.pointer.shift = shift;
    }

    /// The controls of the window the press now held is on, in stack pixels, for a host's
    /// magnifier to show and to steer the press between; empty without a press. A classic
    /// window lists each control by the box it answers in, and, while one of its playlist
    /// buttons is held, the pictures of its menu, which ask for the magnifier.
    pub fn press_controls(&mut self) -> Vec<crate::host::TouchControl> {
        if let Some(press) = self.classic_press {
            return self.classic_controls(press);
        }
        let Some(held) = self.captured else {
            return Vec::new();
        };
        let Some(window) = self.layout_object(held) else {
            return Vec::new();
        };
        let at = self.window_rect_of(window);
        self.all_objects
            .clone()
            .into_iter()
            .filter(|o| {
                self.layout_object(*o) == Some(window)
                    && self.is_control(*o)
                    && self.touchable(*o, false)
            })
            .map(|o| {
                let r = self.objects[o].base.rect;
                crate::host::TouchControl {
                    rect: Rect::new(at.left + r.left, at.top + r.top, r.width, r.height),
                    magnify: false,
                }
            })
            .collect()
    }

    /// Ends the press under the finger without a release.
    pub fn pointer_cancel(&mut self) {
        self.gesture(false, |rt| rt.end_press());
    }

    /// Lets go of the pressed object without a release, and tells it the finger left.
    fn end_press(&mut self) {
        self.pointer.press_ended = true;
        self.drop_deferred();
        self.end_grip();
        let Some(held) = self.captured.take() else {
            return;
        };
        self.pointer.cancelling = true;
        self.object_pointer_cancel(held);
        self.pointer.cancelling = false;
        self.leave_area(held);
    }

    /// `onLeaveArea` for `o`, once per press that sent it `onEnterArea`.
    fn leave_area(&mut self, o: ObjId) {
        if !self.pointer.entered {
            return;
        }
        self.pointer.entered = false;
        self.dispatch(Handle::Gui(o), "onleavearea", &[]);
    }

    // ---- actions -----------------------------------------------------------------------------

    /// A button action, as Winamp does it.
    pub(crate) fn action(
        &mut self,
        source: ObjId,
        action: &str,
        param: Option<&str>,
        target: Option<&str>,
    ) {
        let a = action.to_uppercase();
        let point = self.press_point();
        let from = self
            .action_from
            .take()
            .or_else(|| self.stack_rect_of(source))
            .map(|rect| crate::host::ActionFrom { rect, point });
        let source_id = self.objects[source].base.id.clone();
        self.host.log(&format!(
            "action {a} {} from {source_id}",
            param.unwrap_or("")
        ));
        match a.as_str() {
            "PLAY" => self.player.play(),
            "PAUSE" => self.player.pause(),
            "STOP" => self.player.stop(),
            "PREV" => self.player.previous(),
            "NEXT" => self.player.next(),
            "EJECT" => self.player.eject(),
            "VOLUME_UP" => {
                let v = (self.player.volume() + 10).min(255);
                self.player.set_volume(v);
            }
            "VOLUME_DOWN" => {
                let v = (self.player.volume() - 10).max(0);
                self.player.set_volume(v);
            }
            "TOGGLE" => {
                let Some(param) = param else { return };
                let id = param.to_lowercase();
                let id = id.strip_prefix("guid:").unwrap_or(&id).to_string();
                let kind = Self::window_kind(&id);
                let answers = self.host_actions
                    && (HOST_WINDOWS.contains(&kind.as_str()) || self.toggle_target(&id).is_none());
                if answers {
                    self.host.host_action(&a, Some(&kind), from);
                    // the app shows it: the skin's frame for it (an empty library) stays shut
                    if HOST_WINDOWS.contains(&kind.as_str()) {
                        self.invalidate();
                        return;
                    }
                }
                self.toggle_window(&id, param);
                self.invalidate();
            }
            "SWITCH" => {
                if let (Some(p), Some(c)) = (
                    param,
                    self.layout_object(source)
                        .and_then(|l| self.objects[l].layout().and_then(|d| d.container)),
                ) {
                    self.switch_to(c, p);
                }
            }
            "CB_PREVPAGE" | "CB_PREV" | "CB_NEXTPAGE" | "CB_NEXT" => {
                if let Some(b) = self.bucket_for(source, target) {
                    self.bucket_page(b, if a.starts_with("CB_PREV") { -1 } else { 1 });
                }
            }
            // a docked window's close button puts it away, unless canclose="0"; the main window stays
            "CLOSE" => {
                let c = self
                    .layout_object(source)
                    .and_then(|l| self.objects[l].layout().and_then(|d| d.container));
                if c.is_some() && c == self.main_container() {
                    if self.host_actions {
                        self.host.host_action(&a, param, from);
                    }
                } else if let Some(c) = c.filter(|c| self.containers[*c].can_close()) {
                    self.close_container(c);
                }
            }
            // VID_1X..ABOUT are a classic skin's: its video window's buttons, its presets
            // button, its playlist's bottom buttons, selections and row menu, the clutter bar's A
            // and D, its logo;
            // PE_ADD..PE_LIST are a modern skin's playlist buttons, whose menus the app shows
            "MINIMIZE" | "SYSMENU" | "CONTROLMENU" | "MENU" | "TRACKINFO" | "VIS_NEXT"
            | "VIS_PREV" | "VIS_MENU" | "VIS_FS" | "VID_FS" | "VID_1X" | "VID_2X" | "VID_TV"
            | "VID_MISC" | "EQ_PRESETS" | "PLAYLIST" | "PLAYLIST_SELECT" | "PLAYLIST_SELECTION"
            | "PLAYLIST_MENU" | "ALWAYS_ON_TOP" | "DOUBLESIZE" | "ABOUT" | "PE_ADD" | "PE_REM"
            | "PE_SEL" | "PE_MISC" | "PE_LIST" => {
                if self.host_actions {
                    self.host.host_action(&a, param, from);
                }
            }
            "EQ_TOGGLE" => {
                let on = !self.player.eq_enabled();
                self.player.set_eq_enabled(on);
            }
            "EQ_AUTO" => {
                let on = !self.config_flags.get("eq_auto").copied().unwrap_or(false);
                self.config_flags.insert("eq_auto".into(), on);
            }
            "TEXT_LARGER" | "TEXT_SMALLER" => {}
            "COLORTHEMES_SWITCH" | "COLORTHEMES_PREVIOUS" | "COLORTHEMES_NEXT" => {
                let parent = self.objects[source].base.parent;
                let named = target.and_then(|t| {
                    parent.and_then(|p| self.find_object(p, t)).or_else(|| {
                        let windows = self.windows();
                        windows.iter().find_map(|l| self.find_object(*l, t))
                    })
                });
                let list = named
                    .filter(|l| matches!(self.objects[*l].kind, Kind::ColorThemeList(_)))
                    .or_else(|| {
                        self.all_objects
                            .iter()
                            .copied()
                            .find(|o| matches!(self.objects[*o].kind, Kind::ColorThemeList(_)))
                    });
                let Some(list) = list else { return };
                match a.as_str() {
                    "COLORTHEMES_SWITCH" => self.themes_switch_to_selected(list),
                    "COLORTHEMES_PREVIOUS" => self.themes_step(list, -1),
                    _ => self.themes_step(list, 1),
                }
                self.invalidate();
            }
            _ => {
                let parent = self.objects[source].base.parent;
                let t = target.and_then(|t| {
                    parent.and_then(|p| self.find_object(p, t)).or_else(|| {
                        let windows = self.windows();
                        windows.iter().find_map(|l| self.find_object(*l, t))
                    })
                });
                if let Some(t) = t {
                    self.dispatch(
                        Handle::Gui(t),
                        "onaction",
                        &[
                            Value::str(action),
                            Value::str(param.unwrap_or("")),
                            Value::Int(0),
                            Value::Int(0),
                            Value::Int(0),
                            Value::Int(0),
                            Value::Obj(Handle::Gui(source)),
                        ],
                    );
                }
            }
        }
        self.invalidate();
    }

    /// A TOGGLE action: opens or closes the window `id` names, or flips a flag of that name when there is no such window.
    fn toggle_window(&mut self, id: &str, param: &str) {
        if let Some(c) = self.toggle_target(id) {
            if self.opened.contains(&c) {
                self.close_container(c);
            } else {
                // a component opened by its GUID takes the focus (Winamp Modern's playlist
                // editor, autofocus); a container shown for the first time does not
                // (Winamp3's EQ), one shown again does
                let takes_focus =
                    param.to_lowercase().contains("guid:") || self.shown_before.contains(&c);
                self.open_container(c);
                if takes_focus {
                    self.focused = self.containers[c].current;
                }
            }
        } else {
            let key = format!("window:{id}");
            let on = !self.config_flags.get(&key).copied().unwrap_or(false);
            self.config_flags.insert(key, on);
        }
    }

    /// Whether the window or switch a button's action names is on, for its active image.
    pub(crate) fn action_state(&mut self, action: Option<&str>, param: Option<&str>) -> bool {
        match action.map(|a| a.to_uppercase()).as_deref() {
            Some("TOGGLE") => {
                let Some(param) = param else { return false };
                let id = param.to_lowercase();
                let id = id.strip_prefix("guid:").unwrap_or(&id).to_string();
                let kind = Self::window_kind(&id);
                if let Some(open) = self.host.window_open(&kind) {
                    return open;
                }
                match self.toggle_target(&id) {
                    Some(c) => self.is_open(c),
                    None => self
                        .config_flags
                        .get(&format!("window:{id}"))
                        .copied()
                        .unwrap_or(false),
                }
            }
            Some("EQ_TOGGLE") => self.player.eq_enabled(),
            Some("EQ_AUTO") => self.config_flags.get("eq_auto").copied().unwrap_or(false),
            _ => false,
        }
    }

    /// Whether `action_state` reads the state of `action`: a window, EQ on, EQ auto.
    pub(crate) fn has_action_state(action: Option<&str>) -> bool {
        action.is_some_and(|a| STATE_ACTIONS.contains(&a.to_uppercase().as_str()))
    }
}

/// `v` rounded up to a whole number of `step`s, or down when the next step does not fit.
fn stepped(v: i32, step: i32, fit: impl Fn(i32) -> i32) -> i32 {
    let up = crate::classic::touch::classic_step_up(v, step);
    if fit(up) == up {
        up
    } else {
        (v / step * step).max(step)
    }
}

/// `v` kept to at least `min` and at most `max` (none when 0) and `view`, the view's side winning
/// over a minimum.
fn within(v: i32, min: i32, max: i32, view: i32) -> i32 {
    let top = if max > 0 { max.min(view) } else { view };
    v.min(top).max(min.min(top)).max(1)
}