Skip to main content

walkit/runtime/
pointer.rs

1// SPDX-License-Identifier: GPL-3.0-or-later
2
3//! Touches: what a finger at a point of the stack means, presses, moves and releases, the
4//! skin's menus, and the button actions and config values the objects drive.
5
6use std::collections::HashMap;
7
8use super::{SkinRuntime, HOST_WINDOWS};
9use crate::draw::Rect;
10use crate::gui::{Kind, ObjId};
11use crate::host::SkinMenu;
12use crate::maki::{Handle, Value};
13
14/// Menus a script may pop in reply to one touch; more answer 0 without showing.
15const MAX_MENUS_PER_GESTURE: i32 = 3;
16/// The id of a wasabi title bar's group, and of the layer over the whole bar that takes its drags.
17const TITLE_BAR: &str = "wasabi.titlebar";
18const TITLE_BAR_TRAP: &str = "mousetrap";
19/// The edges a resize grip's `resize` names.
20const GRIP_EDGES: [&str; 4] = ["left", "right", "top", "bottom"];
21/// The actions whose state `action_state` reads.
22const STATE_ACTIONS: [&str; 3] = ["TOGGLE", "EQ_TOGGLE", "EQ_AUTO"];
23/// The events of a press or a move; an object a script watches only for others takes no touch beside it.
24const POINTER_EVENTS: [&str; 9] = [
25    "onleftbuttondown",
26    "onleftbuttonup",
27    "onrightbuttondown",
28    "onrightbuttonup",
29    "onleftbuttondblclk",
30    "onrightbuttondblclk",
31    "onmousemove",
32    "onleftclick",
33    "onrightclick",
34];
35/// The events a tap fires on an object that is not a control: the left button going down and up.
36const TAP_EVENTS: [&str; 2] = ["onleftbuttondown", "onleftbuttonup"];
37/// The event of a finger moving while it presses.
38const FOLLOW_EVENTS: [&str; 1] = ["onmousemove"];
39/// The event of the left button going down.
40const PRESS_EVENTS: [&str; 1] = ["onleftbuttondown"];
41
42/// A drag on a resize grip: the window it resizes, the edges it moves, and where the finger
43/// went down and the window's size then, in the window's pixels.
44#[derive(Debug, Clone)]
45struct Resize {
46    window: ObjId,
47    edges: String,
48    x: i32,
49    y: i32,
50    size: (i32, i32),
51    /// The steps the size takes, for a classic skin's grip.
52    steps: Option<(i32, i32)>,
53}
54
55/// A press its object has not heard yet: the object, and the point of the stack the finger went down on.
56#[derive(Debug, Clone, Copy)]
57struct DeferredPress {
58    target: ObjId,
59    sx: i32,
60    sy: i32,
61}
62
63/// The object with a skin menu a touch landed on: the touch's seq, and the point in the object's window.
64#[derive(Debug, Clone, Copy)]
65struct MenuAim {
66    seq: i32,
67    target: ObjId,
68    x: i32,
69    y: i32,
70}
71
72/// What the pointer machinery keeps between calls.
73#[derive(Debug, Default)]
74pub(crate) struct PointerState {
75    captured_origin: Rect,
76    /// The scale of the window the press went down in; 0 before any press.
77    captured_scale: f32,
78    /// Where the last touch went down, in the stack.
79    down_at: Option<(i32, i32)>,
80    deferred: Option<DeferredPress>,
81    resizing: Option<Resize>,
82    menu_aim: Option<MenuAim>,
83    move_seq: Option<i32>,
84    aimed: Option<ObjId>,
85    pub(crate) gesture_depth: i32,
86    menus_this_gesture: i32,
87    menus_ended: bool,
88    pub(crate) picked_this_gesture: bool,
89    pub(crate) press_ended: bool,
90    entered: bool,
91    cancelling: bool,
92    menu_refusals_logged: Vec<String>,
93    /// What `has_skin_menu` answered for each object since the last layout pass.
94    pub(crate) skin_menus: HashMap<ObjId, bool>,
95    skin_menu_reads: i64,
96    /// Whether the moves and the release of the press now held land exactly where they say: a
97    /// host's magnifier steers them, so no touch slop keeps the press on its control.
98    pub(crate) precise: bool,
99    /// The keys held with the press now held, as the host said before it went down: Ctrl, and Shift.
100    pub(crate) ctrl: bool,
101    pub(crate) shift: bool,
102}
103
104impl SkinRuntime {
105    /// The window under a point of the stack, or the nearest within the touch slop.
106    pub(crate) fn window_at(&mut self, x: i32, y: i32) -> Option<ObjId> {
107        if self.needs_layout {
108            self.do_layout();
109        }
110        if let Some(a) = self.pointer.aimed {
111            return Some(a);
112        }
113        let windows = self.z_windows();
114        // apart, a window takes a touch only where it docks: Winamp Modern's main window is
115        // shaped around its closed drawer, and a touch there reaches the window under it
116        if self.free_windows() {
117            if let Some(w) = windows
118                .iter()
119                .rev()
120                .find(|l| self.docking_rect(**l).contains(x, y))
121            {
122                return Some(*w);
123            }
124        }
125        let distance2 = |r: Rect| -> i64 {
126            let dx = (r.left - x).max(0).max(x - (r.right() - 1)) as i64;
127            let dy = (r.top - y).max(0).max(y - (r.bottom() - 1)) as i64;
128            dx * dx + dy * dy
129        };
130        if let Some(w) = windows
131            .iter()
132            .rev()
133            .find(|l| self.window_rect_of(**l).contains(x, y))
134        {
135            return Some(*w);
136        }
137        let slop = self.touch_slop as i64;
138        windows
139            .iter()
140            .copied()
141            .min_by_key(|l| distance2(self.window_rect_of(*l)))
142            .filter(|l| distance2(self.window_rect_of(*l)) <= slop * slop)
143    }
144
145    /// Runs `block` with the point `x`, `y` of `window` as a point of the stack, the touch kept to that window.
146    fn in_window<T>(
147        &mut self,
148        window: crate::host::WindowId,
149        x: i32,
150        y: i32,
151        block: impl FnOnce(&mut Self, i32, i32) -> T,
152    ) -> T {
153        let l = self.layouts_by_id_lookup(window);
154        if self.needs_layout {
155            self.do_layout();
156        }
157        let origin = self.window_rect_of(l);
158        let before = self.pointer.aimed;
159        self.pointer.aimed = Some(l);
160        let r = block(self, origin.left + x, origin.top + y);
161        self.pointer.aimed = before;
162        r
163    }
164
165    fn layouts_by_id_lookup(&self, id: crate::host::WindowId) -> ObjId {
166        self.layouts_by_id[(id.0 as usize).wrapping_sub(1)]
167    }
168
169    /// `pointer_down` at a point of `window`, in that window's pixels.
170    pub fn pointer_down_in(&mut self, window: crate::host::WindowId, x: i32, y: i32, seq: i32) {
171        self.in_window(window, x, y, |rt, sx, sy| rt.pointer_down(sx, sy, seq));
172    }
173
174    /// `pointer_move` at a point of `window`, in that window's pixels.
175    pub fn pointer_move_in(&mut self, window: crate::host::WindowId, x: i32, y: i32) {
176        self.in_window(window, x, y, |rt, sx, sy| rt.pointer_move(sx, sy));
177    }
178
179    /// `pointer_up` at a point of `window`, in that window's pixels.
180    pub fn pointer_up_in(&mut self, window: crate::host::WindowId, x: i32, y: i32) {
181        self.in_window(window, x, y, |rt, sx, sy| rt.pointer_up(sx, sy));
182    }
183
184    /// `double_tap` at a point of `window`, in that window's pixels.
185    pub fn double_tap_in(&mut self, window: crate::host::WindowId, x: i32, y: i32, seq: i32) {
186        self.in_window(window, x, y, |rt, sx, sy| rt.double_tap(sx, sy, seq));
187    }
188
189    /// A point of the stack in the pressed window's layout pixels.
190    fn captured_local(&self, sx: i32, sy: i32) -> (i32, i32) {
191        let at = self.pointer.captured_origin;
192        let s = if self.pointer.captured_scale > 0.0 {
193            self.pointer.captured_scale
194        } else {
195            1.0
196        };
197        (
198            ((sx - at.left) as f32 / s).floor() as i32,
199            ((sy - at.top) as f32 / s).floor() as i32,
200        )
201    }
202
203    /// The topmost object at a point of the stack.
204    pub(crate) fn hit_test_stack(&mut self, x: i32, y: i32) -> Option<ObjId> {
205        let l = self.window_at(x, y)?;
206        let (x, y) = self.layout_point(l, x, y);
207        self.hit_test(l, x, y)
208    }
209
210    /// What a press at a point of the stack would take hold of in a modern skin: a frame's
211    /// divider or a window's resize grip, by the way it is dragged, else the arrow. While a
212    /// divider or a grip is dragged the answer is its shape wherever the pointer is. For the
213    /// cursor of a host with a mouse.
214    pub fn pointer_shape_at(&mut self, x: i32, y: i32) -> crate::host::PointerShape {
215        use crate::host::PointerShape;
216        if let Some(held) = self.captured {
217            if self.frame_dragging(held) {
218                return self.frame_pointer_shape(held);
219            }
220            if self.pointer.resizing.is_some() {
221                return self.grip_pointer_shape(held);
222            }
223        }
224        if self.needs_layout {
225            self.do_layout();
226        }
227        let Some(l) = self.window_under(x, y) else {
228            return PointerShape::Arrow;
229        };
230        let (px, py) = self.layout_point(l, x, y);
231        match self.hit_test(l, px, py) {
232            Some(o) if self.frame_divider_at(o, px, py) => self.frame_pointer_shape(o),
233            Some(o) if self.is_grip(o) => self.grip_pointer_shape(o),
234            // beside a divider a press takes it unless something else is nearer to hand
235            _ if self.frame_divider_near(l, px, py).is_some() => match self.touch_target(x, y) {
236                Some(o) if self.frame_divider_in_reach(o, px, py) => self.frame_pointer_shape(o),
237                _ => PointerShape::Arrow,
238            },
239            _ => PointerShape::Arrow,
240        }
241    }
242
243    /// Whether a point of the window is on frame `o`'s divider or within the touch slop of it.
244    pub(crate) fn frame_divider_in_reach(&self, o: ObjId, px: i32, py: i32) -> bool {
245        let slop2 = (self.touch_slop as i64) * (self.touch_slop as i64);
246        self.frame_divider_distance2(o, px, py)
247            .is_some_and(|d| d <= slop2)
248    }
249
250    /// The frame of `window` whose divider is nearest a point, within the touch slop.
251    fn frame_divider_near(&mut self, window: ObjId, px: i32, py: i32) -> Option<ObjId> {
252        let mut best: Option<(ObjId, i64)> = None;
253        for o in self.all_objects.clone() {
254            if !matches!(self.objects[o].kind, Kind::Frame(_))
255                || !self.frame_divider_in_reach(o, px, py)
256                || self.layout_object(o) != Some(window)
257                || !self.touchable(o, true)
258            {
259                continue;
260            }
261            let d = self.frame_divider_distance2(o, px, py).unwrap_or(i64::MAX);
262            if best.is_none_or(|(_, bd)| d < bd) {
263                best = Some((o, d));
264            }
265        }
266        best.map(|(o, _)| o)
267    }
268
269    /// The cursor over a resize grip, by the edges its `resize` names.
270    fn grip_pointer_shape(&self, o: ObjId) -> crate::host::PointerShape {
271        use crate::host::PointerShape;
272        let edges = self.objects[o]
273            .base
274            .attr("resize")
275            .map(|e| e.to_lowercase())
276            .unwrap_or_default();
277        let has = |edge: &str| edges.contains(edge);
278        let across = has("left") || has("right");
279        let down = has("top") || has("bottom");
280        match (across, down) {
281            (true, true) if has("left") == has("top") => PointerShape::Diagonal,
282            (true, true) => PointerShape::OtherDiagonal,
283            (true, false) => PointerShape::LeftRight,
284            (false, true) => PointerShape::UpDown,
285            (false, false) => PointerShape::Arrow,
286        }
287    }
288
289    /// Whether a touch on `o` does something: a control, or an object a script listens to.
290    fn reacts(&self, o: ObjId) -> bool {
291        self.is_control(o) || self.scripts.iter().any(|s| s.listens_to(Handle::Gui(o)))
292    }
293
294    fn is_control(&self, o: ObjId) -> bool {
295        matches!(
296            self.objects[o].kind,
297            Kind::Button(_)
298                | Kind::Slider(_)
299                | Kind::ColorThemeList(_)
300                | Kind::PlaylistView(_)
301                | Kind::ClassicWindow(_)
302        ) || self.is_grip(o)
303    }
304
305    /// Whether a classic stack stretches to fill the view, where its grips size nothing.
306    pub(crate) fn classic_filled(&self) -> bool {
307        self.stretch_last && self.view_size.is_some() && !self.free_windows()
308    }
309
310    /// 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.
311    pub(crate) fn is_grip(&self, o: ObjId) -> bool {
312        let Some(edges) = self.objects[o]
313            .base
314            .attr("resize")
315            .map(|e| e.to_lowercase())
316        else {
317            return false;
318        };
319        self.layout_object(o).is_some() && GRIP_EDGES.iter().any(|e| edges.contains(e))
320    }
321
322    /// Sizes the window as the finger at `x`, `y` drags its grip, as Winamp sizes it. Apart,
323    /// the edges the grip moves snap to the viewport and to the other windows, and a window
324    /// whose left or top edge moves keeps its right or bottom edge where it was.
325    fn drag_grip(&mut self, r: &Resize, x: i32, y: i32) {
326        let l = r.window;
327        let (mut w, mut h) = r.size;
328        if r.edges.contains("right") {
329            w += x - r.x;
330        }
331        if r.edges.contains("left") {
332            w -= x - r.x;
333        }
334        if r.edges.contains("bottom") {
335            h += y - r.y;
336        }
337        if r.edges.contains("top") {
338            h -= y - r.y;
339        }
340        let apart = self.free_windows();
341        let at = self.window_rect_of(l);
342        let scale = self.layout_scale(l);
343        let on_screen = |v: i32| (v as f32 * scale).round() as i32;
344        let in_layout = |v: i32| (v as f32 / scale).round() as i32;
345        if apart {
346            let mut want = Rect::new(at.left, at.top, on_screen(w), on_screen(h));
347            if r.edges.contains("left") {
348                want.left = at.right() - want.width;
349            }
350            if r.edges.contains("top") {
351                want.top = at.bottom() - want.height;
352            }
353            let got = self.autodock_edges(l, want, &r.edges);
354            w = in_layout(got.width);
355            h = in_layout(got.height);
356        }
357        let (vw, vh) = self.viewport();
358        let (vw, vh) = (in_layout(vw), in_layout(vh));
359        let d = self.objects[l].layout().expect("a layout");
360        let mut size = (
361            within(w, d.min_w, d.max_w, vw),
362            within(h, d.min_h, d.max_h, vh),
363        );
364        if let Some((sw, sh)) = r.steps {
365            let horizontal = r.edges.contains("left") || r.edges.contains("right");
366            let vertical = r.edges.contains("top") || r.edges.contains("bottom");
367            if horizontal {
368                size.0 = stepped(size.0, sw, |v| within(v, d.min_w, d.max_w, vw));
369            }
370            if vertical {
371                size.1 = stepped(size.1, sh, |v| within(v, d.min_h, d.max_h, vh));
372            }
373        }
374        if Some(l) != self.main_layout() {
375            self.objects[l].layout_mut().expect("a layout").user_size = Some(size);
376        }
377        if apart {
378            let x = if r.edges.contains("left") {
379                at.right() - on_screen(size.0)
380            } else {
381                at.left
382            };
383            let y = if r.edges.contains("top") {
384                at.bottom() - on_screen(size.1)
385            } else {
386                at.top
387            };
388            let d = self.objects[l].layout_mut().expect("a layout");
389            d.view_x = x;
390            d.view_y = y;
391        }
392        if size != self.layout_size(l) {
393            self.resize_layout_to(l, size.0, size.1);
394        }
395    }
396
397    /// The grip drag ends: the window hears that the user resized it.
398    fn end_grip(&mut self) {
399        let Some(r) = self.pointer.resizing.take() else {
400            return;
401        };
402        let l = r.window;
403        let (w, h) = self.layout_size(l);
404        let d = self.objects[l].layout().expect("a layout");
405        let (vx, vy) = (d.view_x, d.view_y);
406        self.dispatch(
407            Handle::Gui(l),
408            "onuserresize",
409            &[Value::Int(vx), Value::Int(vy), Value::Int(w), Value::Int(h)],
410        );
411    }
412
413    /// Whether a script hears a tap on `o`: one listens to it for the tap events, or to the group
414    /// that exposes it as its xui child.
415    fn hears_tap(&self, o: ObjId) -> bool {
416        self.dispatch_chain(o).iter().any(|c| {
417            self.scripts
418                .iter()
419                .any(|s| s.listens_to_any(Handle::Gui(*c), &TAP_EVENTS))
420        })
421    }
422
423    /// Whether a script follows the finger across `o`, or across the group that exposes it.
424    fn follows_finger(&mut self, o: ObjId) -> bool {
425        let chain = self.dispatch_chain(o);
426        let mut any = false;
427        for c in &chain {
428            for s in 0..self.scripts.len() {
429                if self.scripts[s].listens_to_any(Handle::Gui(*c), &FOLLOW_EVENTS)
430                    || self.scripts[s].reads_mouse(Handle::Gui(*c), &PRESS_EVENTS)
431                {
432                    any = true;
433                }
434            }
435        }
436        self.take_script_logs();
437        any
438    }
439
440    /// Whether a mouse could click `o` in `window` at one of a few of its points.
441    fn clickable(&mut self, o: ObjId, window: ObjId, x: i32, y: i32) -> bool {
442        let r = self.objects[o].base.rect;
443        let right = r.right() - 1;
444        let bottom = r.bottom() - 1;
445        let points = [
446            (
447                x.clamp(r.left, right.max(r.left)),
448                y.clamp(r.top, bottom.max(r.top)),
449            ),
450            ((r.left + right) / 2, (r.top + bottom) / 2),
451            (r.left, r.top),
452            (right, r.top),
453            (r.left, bottom),
454            (right, bottom),
455        ];
456        points.iter().any(|(px, py)| {
457            let mut at = self.hit_test(window, *px, *py);
458            while let Some(h) = at {
459                if h == o {
460                    return true;
461                }
462                at = self.objects[h].base.parent;
463            }
464            false
465        })
466    }
467
468    /// Squared distance from a point to `o`'s rectangle; 0 inside.
469    pub(crate) fn distance2(&self, o: ObjId, x: i32, y: i32) -> i64 {
470        let r = self.objects[o].base.rect;
471        let dx = (r.left - x).max(0).max(x - (r.right() - 1)) as i64;
472        let dy = (r.top - y).max(0).max(y - (r.bottom() - 1)) as i64;
473        dx * dx + dy * dy
474    }
475
476    /// What a finger at a point means, in the order the checks below run.
477    pub(crate) fn touch_target(&mut self, sx: i32, sy: i32) -> Option<ObjId> {
478        let window = self.window_at(sx, sy)?;
479        let (x, y) = self.layout_point(window, sx, sy);
480        let hit = self.hit_test(window, x, y);
481        if let Some(h) = hit {
482            if let Some(grip) = self.classic_grip_near(h, x, y) {
483                return Some(grip);
484            }
485            // a status bar is hit only on its command buttons, which sit over the frame's
486            // resize corner in MMD3
487            if self.is_control(h)
488                || matches!(self.objects[h].kind, Kind::Menu(_) | Kind::LayoutStatus(_))
489                || self.frame_divider_at(h, x, y)
490            {
491                return Some(h);
492            }
493        }
494        let slop2 = (self.touch_slop as i64) * (self.touch_slop as i64);
495        let objects = self.all_objects.clone();
496        let nearest = |rt: &mut SkinRuntime,
497                       shown: bool,
498                       pick: &dyn Fn(&SkinRuntime, ObjId) -> bool|
499         -> Option<ObjId> {
500            let mut best: Option<(ObjId, i64)> = None;
501            for o in objects.iter().rev().copied() {
502                if rt.layout_object(o) != Some(window) || !rt.touchable(o, shown) {
503                    continue;
504                }
505                let d = rt.distance2(o, x, y);
506                if d > slop2 || !pick(rt, o) {
507                    continue;
508                }
509                if shown && !rt.clickable(o, window, x, y) {
510                    continue;
511                }
512                if best.is_none_or(|(_, bd)| d < bd) {
513                    best = Some((o, d));
514                }
515            }
516            best.map(|(o, _)| o)
517        };
518        let control = nearest(self, true, &|rt, o| rt.is_control(o));
519        if let Some(h) = hit {
520            if self.hears_tap(h)
521                && !control.is_some_and(|c| {
522                    self.objects[c]
523                        .base
524                        .rect
525                        .overlaps(&self.objects[h].base.rect)
526                })
527            {
528                return Some(h);
529            }
530        }
531        if let Some(c) = control {
532            return Some(c);
533        }
534        if let Some(h) = hit.filter(|h| self.reacts(*h)) {
535            return Some(h);
536        }
537        // a divider beside the touch, where nothing else takes it
538        if let Some(f) = self.frame_divider_near(window, x, y) {
539            return Some(f);
540        }
541        if let Some(o) = nearest(self, false, &|rt, o| {
542            !rt.is_control(o)
543                && rt
544                    .scripts
545                    .iter()
546                    .any(|s| s.listens_to_any(Handle::Gui(o), &POINTER_EVENTS))
547        }) {
548            return Some(o);
549        }
550        hit
551    }
552
553    /// Pointer events take points of the stack; objects hear points of their window. `seq`
554    /// names this touch for the menu and move targets and `right_click`.
555    pub fn pointer_down(&mut self, sx: i32, sy: i32, seq: i32) {
556        self.gesture(true, |rt| {
557            rt.aim_menu(sx, sy, seq);
558            rt.pointer.move_seq = None;
559            rt.pointer.precise = false;
560            // apart, a press raises its window; a press on the desktop between the windows
561            // reaches no window (window_at falls back to the nearest one for the stack)
562            if rt.free_windows() {
563                if let Some(w) = rt.window_under(sx, sy) {
564                    rt.raise_window(w);
565                }
566            }
567            let touched = rt.pointer_down_at(sx, sy);
568            // a press on no object moves the window; a press that opened a menu has been let go of, and
569            // moves nothing; a press held back from an object with a skin menu moves the window as a
570            // press on that object would
571            let held = rt.captured.or(rt.pointer.deferred.map(|d| d.target));
572            if touched.is_none() || held.is_some_and(|h| rt.moves_window(h)) {
573                rt.pointer.move_seq = Some(seq);
574                // set out apart, the window under the finger moves with it
575                if rt.free_windows() {
576                    if let Some(w) = rt.window_under(sx, sy) {
577                        rt.free_drag_begin(w, sx, sy);
578                    }
579                }
580            }
581        });
582    }
583
584    /// Presses what a finger at a point of the stack means, and returns it; `None` for nothing.
585    fn pointer_down_at(&mut self, sx: i32, sy: i32) -> Option<ObjId> {
586        self.drop_deferred();
587        if self.needs_layout {
588            self.do_layout();
589        }
590        let target = self.touch_target(sx, sy)?;
591        // the touched window takes the focus, as a press of either mouse button gives it
592        if let Some(l) = self.layout_object(target) {
593            self.take_focus(l);
594        }
595        if self.pointer.menu_aim.is_some_and(|a| a.target == target)
596            && !matches!(self.objects[target].kind, Kind::Slider(_))
597        {
598            self.pointer.deferred = Some(DeferredPress { target, sx, sy });
599            self.show_pressed(target, true);
600            return Some(target);
601        }
602        self.press(target, sx, sy);
603        Some(target)
604    }
605
606    /// Shows a held press's button pressed, or no longer; its scripts hear nothing of it.
607    fn show_pressed(&mut self, target: ObjId, pressed: bool) {
608        if let Kind::Button(b) = &mut self.objects[target].kind {
609            b.pressed = pressed;
610            self.repaint();
611        }
612    }
613
614    /// The object hears the button go down at a point of the stack, and the finger come in.
615    fn press(&mut self, target: ObjId, sx: i32, sy: i32) {
616        let window = self.layout_object(target);
617        self.pointer.captured_origin = window.map_or(Rect::EMPTY, |l| self.window_rect_of(l));
618        self.pointer.captured_scale = window.map_or(1.0, |l| self.layout_scale(l));
619        let (x, y) = self.captured_local(sx, sy);
620        self.last_pointer = (x, y);
621        self.captured = Some(target);
622        if let Some(window) = self.layout_object(target) {
623            // a classic stack stretched to fill the view keeps its size: its grip sizes nothing
624            let filled =
625                self.classic_filled() && self.objects[target].base.id.starts_with("classic.");
626            if self.is_grip(target) && !filled {
627                let edges = self.objects[target]
628                    .base
629                    .attr("resize")
630                    .unwrap_or("")
631                    .to_lowercase();
632                let size = self.layout_size(window);
633                let steps = self.objects[target]
634                    .base
635                    .id
636                    .starts_with("classic.")
637                    .then_some(crate::classic::touch::CLASSIC_SIZE_STEP);
638                self.pointer.resizing = Some(Resize {
639                    window,
640                    edges,
641                    x,
642                    y,
643                    size,
644                    steps,
645                });
646            }
647        }
648        self.object_pointer_down(target, x, y);
649        // a menu the press opened has let go of it already
650        if self.captured == Some(target) {
651            self.pointer.entered = true;
652            self.dispatch(Handle::Gui(target), "onenterarea", &[]);
653        }
654    }
655
656    /// The finger moves to a point of the stack.
657    pub fn pointer_move(&mut self, sx: i32, sy: i32) {
658        self.gesture(false, |rt| rt.pointer_move_at(sx, sy));
659    }
660
661    /// Sends the deferred press where the finger went down, unless its object has gone from the skin.
662    fn send_deferred(&mut self) {
663        let Some(d) = self.pointer.deferred else {
664            return;
665        };
666        self.drop_deferred();
667        if self.needs_layout {
668            self.do_layout();
669        }
670        if self.all_objects.contains(&d.target) {
671            self.press(d.target, d.sx, d.sy);
672        }
673    }
674
675    /// Lets the deferred press go unsent: its object hears nothing of it.
676    fn drop_deferred(&mut self) {
677        let Some(d) = self.pointer.deferred.take() else {
678            return;
679        };
680        self.show_pressed(d.target, false);
681    }
682
683    fn pointer_move_at(&mut self, sx: i32, sy: i32) {
684        if self.free_dragging() {
685            self.free_drag_to(sx, sy);
686        }
687        if let Some(d) = self.pointer.deferred {
688            let dx = sx - d.sx;
689            let dy = sy - d.sy;
690            // still a tap or a long press
691            if !self.pointer.precise && dx * dx + dy * dy <= self.touch_slop * self.touch_slop {
692                return;
693            }
694            self.send_deferred();
695        }
696        let (x, y) = self.captured_local(sx, sy);
697        self.last_pointer = (x, y);
698        if let Some(r) = self.pointer.resizing.clone() {
699            self.drag_grip(&r, x, y);
700        }
701        if let Some(c) = self.captured {
702            if let Some(next) = self.eq_band_reached(c, sx, sy) {
703                // the band lets go and the one the finger reached takes the drag, as pressed there
704                self.object_pointer_up(c, x, y, true);
705                self.leave_area(c);
706                self.captured = Some(next);
707                self.object_pointer_down(next, x, y);
708                if self.captured == Some(next) {
709                    self.pointer.entered = true;
710                    self.dispatch(Handle::Gui(next), "onenterarea", &[]);
711                }
712                return;
713            }
714            self.object_pointer_move(c, x, y);
715        }
716    }
717
718    /// The finger lifts at a point of the stack.
719    pub fn pointer_up(&mut self, sx: i32, sy: i32) {
720        self.gesture(false, |rt| rt.pointer_up_at(sx, sy));
721    }
722
723    fn pointer_up_at(&mut self, sx: i32, sy: i32) {
724        // the browser may fold the last move into the release
725        if self.free_dragging() {
726            self.free_drag_to(sx, sy);
727        }
728        self.free_drag_end();
729        self.send_deferred();
730        let (x, y) = self.captured_local(sx, sy);
731        self.last_pointer = (x, y);
732        if let Some(r) = self.pointer.resizing.clone() {
733            self.drag_grip(&r, x, y);
734        }
735        self.end_grip();
736        let Some(target) = self.captured.take() else {
737            return;
738        };
739        // a press a host's magnifier steered onto another control is let go as a click on
740        // that control: the one it began on lets go outside, and the one under it is pressed
741        // and let go
742        if self.pointer.precise {
743            if let Some(under) = self.hit_test_stack(sx, sy).filter(|u| {
744                *u != target
745                    && self.reacts(*u)
746                    && !matches!(self.objects[*u].kind, Kind::ClassicWindow(_))
747            }) {
748                self.object_pointer_up(target, x, y, false);
749                self.leave_area(target);
750                self.pointer.precise = false;
751                self.press(under, sx, sy);
752                return self.pointer_up_at(sx, sy);
753            }
754        }
755        // a finger that drifts a little still counts as on the control
756        let r = self.objects[target].base.rect;
757        let slop = if self.pointer.precise {
758            0
759        } else {
760            self.touch_slop
761        };
762        let inside = x >= r.left - slop
763            && x < r.right() + slop
764            && y >= r.top - slop
765            && y < r.bottom() + slop;
766        self.object_pointer_up(target, x, y, inside);
767        self.leave_area(target);
768    }
769
770    /// A second tap of a double tap, at a point of the stack.
771    pub fn double_tap(&mut self, sx: i32, sy: i32, seq: i32) {
772        self.gesture(true, |rt| {
773            rt.aim_menu(sx, sy, seq);
774            rt.pointer.move_seq = None;
775            rt.double_tap_at(sx, sy);
776        });
777    }
778
779    fn double_tap_at(&mut self, sx: i32, sy: i32) {
780        self.drop_deferred();
781        let Some(target) = self.hit_test_stack(sx, sy) else {
782            return;
783        };
784        let (x, y) = match self.layout_object(target) {
785            Some(l) => self.layout_point(l, sx, sy),
786            None => (sx, sy),
787        };
788        self.object_double_tap(target, x, y);
789    }
790
791    /// The seq of the last press when it landed on an object with a skin menu, else `None`.
792    pub fn menu_target(&self) -> Option<i32> {
793        self.pointer.menu_aim.map(|a| a.seq)
794    }
795
796    /// The seq of the last press when it landed on no object, or the object it pressed moves the
797    /// window; none while the windows are apart, where the engine moves them itself.
798    pub fn move_target(&self) -> Option<i32> {
799        if self.free.on {
800            return None;
801        }
802        self.pointer.move_seq
803    }
804
805    /// Whether a drag that starts on `o` moves the window.
806    pub(crate) fn moves_window(&mut self, o: ObjId) -> bool {
807        if matches!(self.objects[o].kind, Kind::ClassicWindow(_)) {
808            return self.classic_moves_window(o);
809        }
810        if matches!(
811            self.objects[o].kind,
812            Kind::Slider(_) | Kind::ColorThemeList(_) | Kind::PlaylistView(_)
813        ) {
814            return false;
815        }
816        if self.is_grip(o) || self.frame_dragging(o) {
817            return false;
818        }
819        if matches!(self.objects[o].kind, Kind::Button(_) | Kind::Menu(_)) {
820            return !self.follows_finger(o);
821        }
822        self.is_move_area(o) || !self.follows_finger(o)
823    }
824
825    /// Whether Winamp moves the window by a drag on `o`: what `o` writes in `move`, else what the
826    /// nearest group around it writes; a wasabi title bar's mousetrap moves it unless it says otherwise.
827    fn is_move_area(&self, o: ObjId) -> bool {
828        if let Some(m) = self.objects[o].base.move_window {
829            return m;
830        }
831        let b = &self.objects[o].base;
832        if b.id == TITLE_BAR_TRAP
833            && b.parent
834                .is_some_and(|p| self.objects[p].base.id == TITLE_BAR)
835        {
836            return true;
837        }
838        let mut p = b.parent;
839        while let Some(g) = p {
840            if let Some(m) = self.objects[g].base.move_window {
841                return m;
842            }
843            p = self.objects[g].base.parent;
844        }
845        false
846    }
847
848    /// Remembers the object with a skin menu under a touch at a point of the stack, or none.
849    fn aim_menu(&mut self, sx: i32, sy: i32, seq: i32) {
850        if self.needs_layout {
851            self.do_layout();
852        }
853        self.pointer.menu_aim = self.menu_aim_at(sx, sy, seq);
854        self.pointer.down_at = Some((sx, sy));
855    }
856
857    /// Where the touch going on went down, in the stack; `None` outside a touch.
858    pub(crate) fn press_point(&self) -> Option<(i32, i32)> {
859        self.pointer
860            .down_at
861            .filter(|_| self.pointer.gesture_depth > 0)
862    }
863
864    fn menu_aim_at(&mut self, sx: i32, sy: i32, seq: i32) -> Option<MenuAim> {
865        let window = self.window_at(sx, sy)?;
866        let (x, y) = self.layout_point(window, sx, sy);
867        if let Some(target) = self.classic_row_menu_at(window, x, y) {
868            return Some(MenuAim { seq, target, x, y });
869        }
870        let target = self.menu_object_at(window, x, y)?;
871        Some(MenuAim { seq, target, x, y })
872    }
873
874    /// The object a right click at a point of `window` means, among objects with a skin menu only.
875    fn menu_object_at(&mut self, window: ObjId, x: i32, y: i32) -> Option<ObjId> {
876        let slop2 = (self.touch_slop as i64) * (self.touch_slop as i64);
877        let mut best: Option<(ObjId, i64)> = None;
878        for o in self.all_objects.clone().into_iter().rev() {
879            if self.layout_object(o) != Some(window)
880                || self.objects[o].base.ghost
881                || !self.touchable(o, true)
882            {
883                continue;
884            }
885            let d = self.distance2(o, x, y);
886            if d > slop2 {
887                continue;
888            }
889            let has = if let Some(h) = self.pointer.skin_menus.get(&o) {
890                *h
891            } else {
892                let h = self.has_skin_menu(o);
893                self.pointer.skin_menus.insert(o, h);
894                h
895            };
896            if has && best.is_none_or(|(_, bd)| d < bd) {
897                best = Some((o, d));
898            }
899        }
900        best.map(|(o, _)| o)
901    }
902
903    /// Whether a right click on `o` can open a menu of the skin's, read from the scripts'
904    /// bytecode without running them.
905    pub(crate) fn has_skin_menu(&mut self, o: ObjId) -> bool {
906        self.pointer.skin_menu_reads += 1;
907        let chain = self.dispatch_chain(o);
908        let is_button = matches!(self.objects[o].kind, Kind::Button(_));
909        let events = crate::maki::script::right_click_events(is_button);
910        let mut reaches = false;
911        for c in &chain {
912            for s in 0..self.scripts.len() {
913                if self.scripts[s].reaches_menu(Handle::Gui(*c), &events) {
914                    reaches = true;
915                }
916            }
917        }
918        self.take_script_logs();
919        if reaches {
920            return true;
921        }
922        let mut called: Vec<String> = Vec::new();
923        for c in &chain {
924            for s in 0..self.scripts.len() {
925                for e in self.scripts[s].events_called(Handle::Gui(*c), &events) {
926                    if !called.contains(&e) {
927                        called.push(e);
928                    }
929                }
930            }
931        }
932        let called: Vec<&str> = called.iter().map(|s| s.as_str()).collect();
933        let mut any = false;
934        if !called.is_empty() {
935            for c in &chain {
936                for s in 0..self.scripts.len() {
937                    if self.scripts[s].reaches_menu(Handle::Gui(*c), &called) {
938                        any = true;
939                    }
940                }
941            }
942        }
943        self.take_script_logs();
944        any
945    }
946
947    /// Writes the lines the scripts' bytecode walks asked to log.
948    fn take_script_logs(&mut self) {
949        for s in 0..self.scripts.len() {
950            if let Some(line) = self.scripts[s].pending_log.take() {
951                self.host.log(&line);
952            }
953        }
954    }
955
956    /// The objects an event on `o` fires on: `o`, then each group that exposes the one before as its xui child.
957    fn dispatch_chain(&self, o: ObjId) -> Vec<ObjId> {
958        let mut chain = vec![o];
959        let mut at = o;
960        while let Some(p) = self.objects[at].base.parent {
961            let exposes = self.objects[p]
962                .group
963                .as_ref()
964                .is_some_and(|g| g.embed_xui.as_deref() == Some(self.objects[at].base.id.as_str()));
965            if !exposes || chain.contains(&p) {
966                break;
967            }
968            chain.push(p);
969            at = p;
970        }
971        chain
972    }
973
974    /// A right click on the object the touch `seq` landed on, at the point it landed, as a separate touch.
975    pub fn right_click(&mut self, seq: i32) {
976        self.gesture(true, |rt| {
977            if let Some(aim) = rt.pointer.menu_aim.filter(|a| a.seq == seq) {
978                rt.right_click_at(aim);
979            }
980        });
981    }
982
983    fn right_click_at(&mut self, aim: MenuAim) {
984        // the touch was a long press: a deferred press goes nowhere
985        self.drop_deferred();
986        if self.needs_layout {
987            self.do_layout();
988        }
989        if !self.all_objects.contains(&aim.target) {
990            return;
991        }
992        // a press still held lets go first, as a right click takes the mouse
993        if self.captured.is_some() {
994            self.end_press();
995        }
996        self.last_pointer = (aim.x, aim.y);
997        self.object_right_click(aim.target, aim.x, aim.y);
998        if matches!(self.objects[aim.target].kind, Kind::Button(_)) {
999            self.dispatch(Handle::Gui(aim.target), "onrightclick", &[]);
1000        }
1001    }
1002
1003    /// Runs `block` as a touch the listener made, from which a script may pop a menu. `fresh`
1004    /// starts a new touch, whose menu count starts over.
1005    pub fn gesture<T>(&mut self, fresh: bool, block: impl FnOnce(&mut Self) -> T) -> T {
1006        self.gesture_begin(fresh);
1007        let r = block(self);
1008        self.gesture_end();
1009        r
1010    }
1011
1012    /// Starts a touch the listener made, as [`SkinRuntime::gesture`] does around its block, for
1013    /// a host across a boundary that cannot pass the block; [`SkinRuntime::gesture_end`] ends it.
1014    pub fn gesture_begin(&mut self, fresh: bool) {
1015        if fresh {
1016            self.pointer.menus_this_gesture = 0;
1017            self.pointer.menus_ended = false;
1018            self.pointer.picked_this_gesture = false;
1019            self.pointer.press_ended = false;
1020        }
1021        self.pointer.gesture_depth += 1;
1022    }
1023
1024    /// Ends the touch [`SkinRuntime::gesture_begin`] started; one that was not started ends nothing.
1025    pub fn gesture_end(&mut self) {
1026        self.pointer.gesture_depth = self.pointer.gesture_depth.saturating_sub(1);
1027    }
1028
1029    /// The listener's pick from a menu a script popped, by command id, or 0.
1030    pub fn menu_choice(&mut self, menu: &SkinMenu) -> i32 {
1031        let refusal = if self.pointer.gesture_depth == 0 {
1032            Some("outside a touch".to_string())
1033        } else if self.pointer.menus_ended {
1034            Some("after one closed without the listener".to_string())
1035        } else if self.pointer.cancelling {
1036            Some("while a press ends without a release".to_string())
1037        } else if self.pointer.menus_this_gesture >= MAX_MENUS_PER_GESTURE {
1038            Some(format!("more than {MAX_MENUS_PER_GESTURE} in one touch"))
1039        } else {
1040            None
1041        };
1042        if let Some(refusal) = refusal {
1043            if !self.pointer.menu_refusals_logged.contains(&refusal) {
1044                self.pointer.menu_refusals_logged.push(refusal.clone());
1045                self.host.log(&format!("popup menu {refusal}: not shown"));
1046            }
1047            return 0;
1048        }
1049        self.pointer.menus_this_gesture += 1;
1050        self.end_press();
1051        let picked = self.host.choose_from_menu(menu);
1052        if picked.is_none() {
1053            self.pointer.menus_ended = true;
1054        }
1055        if picked.unwrap_or(0) != 0 {
1056            self.pointer.picked_this_gesture = true;
1057        }
1058        picked.unwrap_or(0)
1059    }
1060
1061    /// Makes the moves and the release of the press now held land exactly where they say, as a
1062    /// mouse's do: no touch slop keeps the press on its control or a finger on a button. For a
1063    /// host's magnifier, which steers the press with a finger geared down; the next
1064    /// `pointer_down` turns it off.
1065    pub fn set_pointer_precise(&mut self, precise: bool) {
1066        self.pointer.precise = precise;
1067    }
1068
1069    /// The keys held with the next press, from a keyboard beside a mouse or a finger: Ctrl and
1070    /// Shift. A classic playlist's row takes them as Winamp's does, Ctrl adding a row to the
1071    /// selection or taking it out, Shift selecting the rows from the last one picked. They hold
1072    /// until the host says again.
1073    pub fn set_pointer_modifiers(&mut self, ctrl: bool, shift: bool) {
1074        self.pointer.ctrl = ctrl;
1075        self.pointer.shift = shift;
1076    }
1077
1078    /// The controls of the window the press now held is on, in stack pixels, for a host's
1079    /// magnifier to show and to steer the press between; empty without a press. A classic
1080    /// window lists each control by the box it answers in, and, while one of its playlist
1081    /// buttons is held, the pictures of its menu, which ask for the magnifier.
1082    pub fn press_controls(&mut self) -> Vec<crate::host::TouchControl> {
1083        if let Some(press) = self.classic_press {
1084            return self.classic_controls(press);
1085        }
1086        let Some(held) = self.captured else {
1087            return Vec::new();
1088        };
1089        let Some(window) = self.layout_object(held) else {
1090            return Vec::new();
1091        };
1092        let at = self.window_rect_of(window);
1093        self.all_objects
1094            .clone()
1095            .into_iter()
1096            .filter(|o| {
1097                self.layout_object(*o) == Some(window)
1098                    && self.is_control(*o)
1099                    && self.touchable(*o, false)
1100            })
1101            .map(|o| {
1102                let r = self.objects[o].base.rect;
1103                crate::host::TouchControl {
1104                    rect: Rect::new(at.left + r.left, at.top + r.top, r.width, r.height),
1105                    magnify: false,
1106                }
1107            })
1108            .collect()
1109    }
1110
1111    /// Ends the press under the finger without a release.
1112    pub fn pointer_cancel(&mut self) {
1113        self.gesture(false, |rt| rt.end_press());
1114    }
1115
1116    /// Lets go of the pressed object without a release, and tells it the finger left.
1117    fn end_press(&mut self) {
1118        self.pointer.press_ended = true;
1119        self.drop_deferred();
1120        self.end_grip();
1121        let Some(held) = self.captured.take() else {
1122            return;
1123        };
1124        self.pointer.cancelling = true;
1125        self.object_pointer_cancel(held);
1126        self.pointer.cancelling = false;
1127        self.leave_area(held);
1128    }
1129
1130    /// `onLeaveArea` for `o`, once per press that sent it `onEnterArea`.
1131    fn leave_area(&mut self, o: ObjId) {
1132        if !self.pointer.entered {
1133            return;
1134        }
1135        self.pointer.entered = false;
1136        self.dispatch(Handle::Gui(o), "onleavearea", &[]);
1137    }
1138
1139    // ---- actions -----------------------------------------------------------------------------
1140
1141    /// A button action, as Winamp does it.
1142    pub(crate) fn action(
1143        &mut self,
1144        source: ObjId,
1145        action: &str,
1146        param: Option<&str>,
1147        target: Option<&str>,
1148    ) {
1149        let a = action.to_uppercase();
1150        let point = self.press_point();
1151        let from = self
1152            .action_from
1153            .take()
1154            .or_else(|| self.stack_rect_of(source))
1155            .map(|rect| crate::host::ActionFrom { rect, point });
1156        let source_id = self.objects[source].base.id.clone();
1157        self.host.log(&format!(
1158            "action {a} {} from {source_id}",
1159            param.unwrap_or("")
1160        ));
1161        match a.as_str() {
1162            "PLAY" => self.player.play(),
1163            "PAUSE" => self.player.pause(),
1164            "STOP" => self.player.stop(),
1165            "PREV" => self.player.previous(),
1166            "NEXT" => self.player.next(),
1167            "EJECT" => self.player.eject(),
1168            "VOLUME_UP" => {
1169                let v = (self.player.volume() + 10).min(255);
1170                self.player.set_volume(v);
1171            }
1172            "VOLUME_DOWN" => {
1173                let v = (self.player.volume() - 10).max(0);
1174                self.player.set_volume(v);
1175            }
1176            "TOGGLE" => {
1177                let Some(param) = param else { return };
1178                let id = param.to_lowercase();
1179                let id = id.strip_prefix("guid:").unwrap_or(&id).to_string();
1180                let kind = Self::window_kind(&id);
1181                let answers = self.host_actions
1182                    && (HOST_WINDOWS.contains(&kind.as_str()) || self.toggle_target(&id).is_none());
1183                if answers {
1184                    self.host.host_action(&a, Some(&kind), from);
1185                    // the app shows it: the skin's frame for it (an empty library) stays shut
1186                    if HOST_WINDOWS.contains(&kind.as_str()) {
1187                        self.invalidate();
1188                        return;
1189                    }
1190                }
1191                self.toggle_window(&id, param);
1192                self.invalidate();
1193            }
1194            "SWITCH" => {
1195                if let (Some(p), Some(c)) = (
1196                    param,
1197                    self.layout_object(source)
1198                        .and_then(|l| self.objects[l].layout().and_then(|d| d.container)),
1199                ) {
1200                    self.switch_to(c, p);
1201                }
1202            }
1203            "CB_PREVPAGE" | "CB_PREV" | "CB_NEXTPAGE" | "CB_NEXT" => {
1204                if let Some(b) = self.bucket_for(source, target) {
1205                    self.bucket_page(b, if a.starts_with("CB_PREV") { -1 } else { 1 });
1206                }
1207            }
1208            // a docked window's close button puts it away, unless canclose="0"; the main window stays
1209            "CLOSE" => {
1210                let c = self
1211                    .layout_object(source)
1212                    .and_then(|l| self.objects[l].layout().and_then(|d| d.container));
1213                if c.is_some() && c == self.main_container() {
1214                    if self.host_actions {
1215                        self.host.host_action(&a, param, from);
1216                    }
1217                } else if let Some(c) = c.filter(|c| self.containers[*c].can_close()) {
1218                    self.close_container(c);
1219                }
1220            }
1221            // VID_1X..ABOUT are a classic skin's: its video window's buttons, its presets
1222            // button, its playlist's bottom buttons, selections and row menu, the clutter bar's A
1223            // and D, its logo;
1224            // PE_ADD..PE_LIST are a modern skin's playlist buttons, whose menus the app shows
1225            "MINIMIZE" | "SYSMENU" | "CONTROLMENU" | "MENU" | "TRACKINFO" | "VIS_NEXT"
1226            | "VIS_PREV" | "VIS_MENU" | "VIS_FS" | "VID_FS" | "VID_1X" | "VID_2X" | "VID_TV"
1227            | "VID_MISC" | "EQ_PRESETS" | "PLAYLIST" | "PLAYLIST_SELECT" | "PLAYLIST_SELECTION"
1228            | "PLAYLIST_MENU" | "ALWAYS_ON_TOP" | "DOUBLESIZE" | "ABOUT" | "PE_ADD" | "PE_REM"
1229            | "PE_SEL" | "PE_MISC" | "PE_LIST" => {
1230                if self.host_actions {
1231                    self.host.host_action(&a, param, from);
1232                }
1233            }
1234            "EQ_TOGGLE" => {
1235                let on = !self.player.eq_enabled();
1236                self.player.set_eq_enabled(on);
1237            }
1238            "EQ_AUTO" => {
1239                let on = !self.config_flags.get("eq_auto").copied().unwrap_or(false);
1240                self.config_flags.insert("eq_auto".into(), on);
1241            }
1242            "TEXT_LARGER" | "TEXT_SMALLER" => {}
1243            "COLORTHEMES_SWITCH" | "COLORTHEMES_PREVIOUS" | "COLORTHEMES_NEXT" => {
1244                let parent = self.objects[source].base.parent;
1245                let named = target.and_then(|t| {
1246                    parent.and_then(|p| self.find_object(p, t)).or_else(|| {
1247                        let windows = self.windows();
1248                        windows.iter().find_map(|l| self.find_object(*l, t))
1249                    })
1250                });
1251                let list = named
1252                    .filter(|l| matches!(self.objects[*l].kind, Kind::ColorThemeList(_)))
1253                    .or_else(|| {
1254                        self.all_objects
1255                            .iter()
1256                            .copied()
1257                            .find(|o| matches!(self.objects[*o].kind, Kind::ColorThemeList(_)))
1258                    });
1259                let Some(list) = list else { return };
1260                match a.as_str() {
1261                    "COLORTHEMES_SWITCH" => self.themes_switch_to_selected(list),
1262                    "COLORTHEMES_PREVIOUS" => self.themes_step(list, -1),
1263                    _ => self.themes_step(list, 1),
1264                }
1265                self.invalidate();
1266            }
1267            _ => {
1268                let parent = self.objects[source].base.parent;
1269                let t = target.and_then(|t| {
1270                    parent.and_then(|p| self.find_object(p, t)).or_else(|| {
1271                        let windows = self.windows();
1272                        windows.iter().find_map(|l| self.find_object(*l, t))
1273                    })
1274                });
1275                if let Some(t) = t {
1276                    self.dispatch(
1277                        Handle::Gui(t),
1278                        "onaction",
1279                        &[
1280                            Value::str(action),
1281                            Value::str(param.unwrap_or("")),
1282                            Value::Int(0),
1283                            Value::Int(0),
1284                            Value::Int(0),
1285                            Value::Int(0),
1286                            Value::Obj(Handle::Gui(source)),
1287                        ],
1288                    );
1289                }
1290            }
1291        }
1292        self.invalidate();
1293    }
1294
1295    /// A TOGGLE action: opens or closes the window `id` names, or flips a flag of that name when there is no such window.
1296    fn toggle_window(&mut self, id: &str, param: &str) {
1297        if let Some(c) = self.toggle_target(id) {
1298            if self.opened.contains(&c) {
1299                self.close_container(c);
1300            } else {
1301                // a component opened by its GUID takes the focus (Winamp Modern's playlist
1302                // editor, autofocus); a container shown for the first time does not
1303                // (Winamp3's EQ), one shown again does
1304                let takes_focus =
1305                    param.to_lowercase().contains("guid:") || self.shown_before.contains(&c);
1306                self.open_container(c);
1307                if takes_focus {
1308                    self.focused = self.containers[c].current;
1309                }
1310            }
1311        } else {
1312            let key = format!("window:{id}");
1313            let on = !self.config_flags.get(&key).copied().unwrap_or(false);
1314            self.config_flags.insert(key, on);
1315        }
1316    }
1317
1318    /// Whether the window or switch a button's action names is on, for its active image.
1319    pub(crate) fn action_state(&mut self, action: Option<&str>, param: Option<&str>) -> bool {
1320        match action.map(|a| a.to_uppercase()).as_deref() {
1321            Some("TOGGLE") => {
1322                let Some(param) = param else { return false };
1323                let id = param.to_lowercase();
1324                let id = id.strip_prefix("guid:").unwrap_or(&id).to_string();
1325                let kind = Self::window_kind(&id);
1326                if let Some(open) = self.host.window_open(&kind) {
1327                    return open;
1328                }
1329                match self.toggle_target(&id) {
1330                    Some(c) => self.is_open(c),
1331                    None => self
1332                        .config_flags
1333                        .get(&format!("window:{id}"))
1334                        .copied()
1335                        .unwrap_or(false),
1336                }
1337            }
1338            Some("EQ_TOGGLE") => self.player.eq_enabled(),
1339            Some("EQ_AUTO") => self.config_flags.get("eq_auto").copied().unwrap_or(false),
1340            _ => false,
1341        }
1342    }
1343
1344    /// Whether `action_state` reads the state of `action`: a window, EQ on, EQ auto.
1345    pub(crate) fn has_action_state(action: Option<&str>) -> bool {
1346        action.is_some_and(|a| STATE_ACTIONS.contains(&a.to_uppercase().as_str()))
1347    }
1348}
1349
1350/// `v` rounded up to a whole number of `step`s, or down when the next step does not fit.
1351fn stepped(v: i32, step: i32, fit: impl Fn(i32) -> i32) -> i32 {
1352    let up = crate::classic::touch::classic_step_up(v, step);
1353    if fit(up) == up {
1354        up
1355    } else {
1356        (v / step * step).max(step)
1357    }
1358}
1359
1360/// `v` kept to at least `min` and at most `max` (none when 0) and `view`, the view's side winning
1361/// over a minimum.
1362fn within(v: i32, min: i32, max: i32, view: i32) -> i32 {
1363    let top = if max > 0 { max.min(view) } else { view };
1364    v.min(top).max(min.min(top)).max(1)
1365}