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
// SPDX-License-Identifier: GPL-3.0-or-later

//! The windows set out apart, as on Winamp's desktop: each window where it is, moved by a drag
//! on its move areas, docking and snapping to the viewport's edges and to each other as Winamp
//! 5.666 does. The host turns this on with `Presentation::free_windows`; off, the windows are
//! one stack. The viewport here is the host's view once it gives a view size, as scripts see it
//! (`getViewportWidth`).
//!
//! The rules, measured against Winamp: a moved window's edge within [`DOCK_DISTANCE`] (strictly)
//! of the viewport's same edge, of another window's same edge, or of another window's facing
//! edge lands on it, one snap per axis per target; a snap to a window holds only when the moved
//! window then touches it (an edge line in common, the ranges on the other axis overlapping)
//! without overlapping it. The rects dock by their part inside the script's `snapAdjust`
//! margins. The main window carries every window that touches it, and theirs, transitively; a
//! member snapping shifts the whole group. Any other window moves alone. `beforeRedock` and
//! `redock` keep the windows docked to a window's edge on it when the script changes that edge.
//! A window that opens comes on top; a press raises its window, and raising the main window
//! brings the windows docked to it along, under it in their order.

use super::SkinRuntime;
use crate::draw::Rect;
use crate::gui::ObjId;
use crate::maki::Handle;

/// How close an edge comes before it snaps, in layout pixels: Winamp's "Dock windows at 10 pixels".
pub const DOCK_DISTANCE: i32 = 10;

/// What the free arrangement keeps.
#[derive(Debug)]
pub(crate) struct FreeState {
    /// Whether the windows are set out apart.
    pub(crate) on: bool,
    /// How close an edge comes before it snaps.
    pub(crate) dock_distance: i32,
    drag: Option<Drag>,
    /// What `beforeRedock` noted: the window, its docking rect then, and the windows docked to it.
    redock: Vec<(ObjId, Rect, Vec<ObjId>)>,
    /// The windows from the bottom to the top.
    z: Vec<ObjId>,
    /// Whether the windows have been set out apart once since the mode came on: the windows open
    /// then keep the stack's spots, and a window opened later takes its container's spot.
    settled: bool,
}

impl Default for FreeState {
    fn default() -> Self {
        FreeState {
            on: false,
            dock_distance: DOCK_DISTANCE,
            drag: None,
            redock: Vec::new(),
            z: Vec::new(),
            settled: false,
        }
    }
}

/// A window being dragged.
#[derive(Debug, Clone)]
struct Drag {
    /// The window under the finger.
    window: ObjId,
    /// Where the finger went down, in the viewport.
    origin: (i32, i32),
    /// The windows that move, the dragged one first, each with where it started.
    group: Vec<(ObjId, Rect)>,
    /// Whether the dragged window touched another when the drag began.
    docked_before: bool,
    /// Whether the finger moved the window yet.
    moved: bool,
}

/// What a layout hands to the layout its container switches to (see `free_switch_begin`).
#[derive(Debug, Clone)]
pub(crate) struct Switched {
    /// The old layout.
    from: ObjId,
    /// The old layout's docking rect.
    rect: Rect,
    /// How wide the window was.
    width: i32,
    /// The windows docked to it.
    docked: Vec<ObjId>,
    /// Where it was.
    at: (i32, i32),
    /// Its place in the order on top.
    z_at: Option<usize>,
}

/// The snap margins of a window: left, top, right, bottom.
#[derive(Debug, Clone, Copy, Default)]
struct Margins {
    left: i32,
    top: i32,
    right: i32,
    bottom: i32,
}

/// `r` less `m`: the part of a window that docks.
fn inset(r: Rect, m: Margins) -> Rect {
    Rect::new(
        r.left + m.left,
        r.top + m.top,
        r.width - m.left - m.right,
        r.height - m.top - m.bottom,
    )
}

/// The window rect of a docking rect `r` with margins `m`.
fn outset(r: Rect, m: Margins) -> Rect {
    Rect::new(
        r.left - m.left,
        r.top - m.top,
        r.width + m.left + m.right,
        r.height + m.top + m.bottom,
    )
}

/// Whether `a` and `b` share an edge line with their ranges on the other axis overlapping (inclusive).
/// Which edge of its parent a window hangs off.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Edge {
    Below,
    Above,
    Right,
    Left,
}

/// The windows hanging off the edges of others, from `root` outwards: each child with the window
/// it touches, the edge, and its offset along that edge. A window reached from two is kept by
/// the first.
fn hanging(rects: &[(ObjId, Rect)], root: Option<ObjId>) -> Vec<(ObjId, ObjId, Edge, i32)> {
    let Some(root) = root else {
        return Vec::new();
    };
    let rect = |l: ObjId| rects.iter().find(|(w, _)| *w == l).map(|(_, r)| *r);
    let mut out = Vec::new();
    let mut reached = vec![root];
    let mut i = 0;
    while i < reached.len() {
        let parent = reached[i];
        i += 1;
        let Some(p) = rect(parent) else { continue };
        for (child, c) in rects {
            if reached.contains(child) || !touches(p, *c) {
                continue;
            }
            let edge = if c.top == p.bottom() {
                Edge::Below
            } else if c.bottom() == p.top {
                Edge::Above
            } else if c.left == p.right() {
                Edge::Right
            } else {
                Edge::Left
            };
            let along = match edge {
                Edge::Below | Edge::Above => c.left - p.left,
                Edge::Right | Edge::Left => c.top - p.top,
            };
            out.push((*child, parent, edge, along));
            reached.push(*child);
        }
    }
    out
}

fn touches(a: Rect, b: Rect) -> bool {
    let along_x =
        a.left == b.right() || a.right() == b.left || a.right() == b.right() || a.left == b.left;
    let along_y =
        a.top == b.bottom() || a.bottom() == b.top || a.bottom() == b.bottom() || a.top == b.top;
    (along_x && b.bottom() >= a.top && a.bottom() >= b.top)
        || (along_y && b.right() >= a.left && a.right() >= b.left)
}

/// Whether `a` and `b` cover some pixel both.
fn overlaps(a: Rect, b: Rect) -> bool {
    a.left.max(b.left) < a.right().min(b.right()) && a.top.max(b.top) < a.bottom().min(b.bottom())
}

/// `r` moved by `dx`, `dy`.
fn moved(r: Rect, dx: i32, dy: i32) -> Rect {
    Rect::new(r.left + dx, r.top + dy, r.width, r.height)
}

/// `r` with its left edge at `x`, the right edge where it was.
fn with_left(r: Rect, x: i32) -> Rect {
    Rect::new(x, r.top, r.right() - x, r.height)
}

/// `r` with its right edge at `x`, the left edge where it was.
fn with_right(r: Rect, x: i32) -> Rect {
    Rect::new(r.left, r.top, x - r.left, r.height)
}

/// `r` with its top edge at `y`, the bottom edge where it was.
fn with_top(r: Rect, y: i32) -> Rect {
    Rect::new(r.left, y, r.width, r.bottom() - y)
}

/// `r` with its bottom edge at `y`, the top edge where it was.
fn with_bottom(r: Rect, y: i32) -> Rect {
    Rect::new(r.left, r.top, r.width, y - r.top)
}

impl SkinRuntime {
    /// Whether the windows are set out apart.
    pub(crate) fn free_windows(&self) -> bool {
        self.free.on
    }

    /// Sets the windows out apart, or as one stack again.
    pub(crate) fn set_free_windows(&mut self, on: bool) {
        if self.free.on == on {
            return;
        }
        self.free.on = on;
        self.free.drag = None;
        self.free.settled = false;
        self.relayout();
    }

    /// Places every window at the window's spot. The windows open when the mode comes on keep the
    /// spots the stack gave them, so the first look is the stack's. A window opened later with no
    /// spot yet opens where its container's `default_x`, `default_y` put it, as Winamp opens a
    /// window it has no spot for, kept inside the viewport; a container without a spot takes the
    /// one the stack gives it. From then on each window keeps where it is and the size the skin or
    /// the listener gave it.
    pub(crate) fn arrange_free(&mut self) {
        let windows = self.windows();
        let unplaced: Vec<ObjId> = windows
            .iter()
            .copied()
            .filter(|l| !self.objects[*l].layout().is_some_and(|d| d.free_placed))
            .collect();
        let settled = std::mem::replace(&mut self.free.settled, true);
        if !unplaced.is_empty() {
            self.arrange_stack();
            for l in unplaced {
                let r = self.window_rect_of(l);
                let spot = self.objects[l]
                    .layout()
                    .and_then(|d| d.container)
                    .map(|c| &self.containers[c])
                    .filter(|c| settled && c.has_default_spot)
                    .map(|c| (c.default_x, c.default_y));
                let (x, y) = match spot {
                    Some((x, y)) => {
                        // kept inside the view at the size it will have apart
                        let s = self.layout_scale(l);
                        let (w, h) = self
                            .own_free_size(l)
                            .map(|(w, h)| {
                                let r = Rect::new(0, 0, w, h).scaled(s);
                                (r.width, r.height)
                            })
                            .unwrap_or((r.width, r.height));
                        let (vw, vh) = self.viewport();
                        (x.min(vw - w).max(0), y.min(vh - h).max(0))
                    }
                    None => (r.left, r.top),
                };
                let d = self.objects[l].layout_mut().expect("a layout");
                d.view_x = x;
                d.view_y = y;
                d.free_placed = true;
            }
        }
        self.placed.clear();
        let Some(main) = self.main_layout() else {
            return;
        };
        self.layout_root(main);
        for l in windows {
            if l != main {
                // the size the listener gave it by its grip, else the skin's
                let (w, h) = self.own_free_size(l).unzip();
                self.objects[l].base.w = w;
                self.objects[l].base.h = h;
            }
            let (w, h) = self.screen_size(l);
            let d = self.objects[l].layout().expect("a layout");
            let r = Rect::new(d.view_x, d.view_y, w, h);
            self.placed.insert(l, r);
        }
    }

    /// The size window `l` has apart, when it is not the main window: the one the listener gave
    /// it by its grip, else the skin's `w`, `h`; `None` for neither.
    fn own_free_size(&self, l: ObjId) -> Option<(i32, i32)> {
        if Some(l) == self.main_layout() {
            return None;
        }
        let sized = self.objects[l].layout().and_then(|d| d.user_size);
        let b = &self.objects[l].base;
        let skin_w = b.attr("w").and_then(crate::gui::to_int_lenient);
        let skin_h = b.attr("h").and_then(crate::gui::to_int_lenient);
        match (sized, skin_w, skin_h) {
            (Some(s), _, _) => Some(s),
            (None, Some(w), Some(h)) => Some((w, h)),
            _ => None,
        }
    }

    /// The windows from the bottom to the top, as they draw and as a touch finds them: the
    /// stack's order when the windows are one stack, the raised order apart.
    pub(crate) fn z_windows(&mut self) -> Vec<ObjId> {
        let windows = self.windows();
        if !self.free.on {
            return windows;
        }
        // windows gone leave the order; new ones come on top, the main window on top at first
        self.free.z.retain(|w| windows.contains(w));
        if self.free.z.is_empty() {
            self.free.z = windows.iter().rev().copied().collect();
        } else {
            for w in windows.iter().copied() {
                if !self.free.z.contains(&w) {
                    self.free.z.push(w);
                }
            }
        }
        self.free.z.clone()
    }

    /// The window a point of the viewport lies in, the top one where they overlap, by the part
    /// of each that docks (Winamp Modern's main window is shaped around its closed drawer);
    /// `None` on the desktop between the windows.
    pub(crate) fn window_under(&mut self, x: i32, y: i32) -> Option<ObjId> {
        if self.needs_layout {
            self.do_layout();
        }
        let windows = self.z_windows();
        windows
            .into_iter()
            .rev()
            .find(|l| self.docking_rect(*l).contains(x, y))
    }

    /// A press on window `l` raises it to the top; the main window brings the windows docked
    /// to it along, under it in their order.
    pub(crate) fn raise_window(&mut self, l: ObjId) {
        let mut z = self.z_windows();
        if z.last() == Some(&l) {
            return;
        }
        let group = if Some(l) == self.main_layout() {
            self.docked_group(l)
        } else {
            vec![l]
        };
        let lifted: Vec<ObjId> = z.iter().copied().filter(|w| group.contains(w)).collect();
        z.retain(|w| !group.contains(w));
        z.extend(lifted.into_iter().filter(|w| *w != l));
        z.push(l);
        self.free.z = z;
        self.repaint();
    }

    /// Puts window `l` at `x`, `y` in the viewport, as the host puts back a window where the
    /// listener left it.
    pub(crate) fn free_place(&mut self, l: ObjId, x: i32, y: i32) {
        let d = self.objects[l].layout_mut().expect("a layout");
        d.view_x = x;
        d.view_y = y;
        d.free_placed = true;
        self.relayout();
    }

    fn snap_margins(&self, l: ObjId) -> Margins {
        let d = self.objects[l].layout().expect("a layout");
        let s = self.layout_scale(l);
        let at = |v: i32| (v.max(0) as f32 * s).round() as i32;
        Margins {
            left: at(d.snap_left),
            top: at(d.snap_top),
            right: at(d.snap_right),
            bottom: at(d.snap_bottom),
        }
    }

    /// The part of window `l` that docks: its rect inside its snap margins.
    pub(crate) fn docking_rect(&mut self, l: ObjId) -> Rect {
        let r = self.window_rect_of(l);
        inset(r, self.snap_margins(l))
    }

    /// The windows docked to `l`, and to those, transitively: each touches one of the set
    /// without overlapping it. `l` comes first.
    pub(crate) fn docked_group(&mut self, l: ObjId) -> Vec<ObjId> {
        if self.needs_layout {
            self.do_layout();
        }
        let windows = self.windows();
        let rects: Vec<(ObjId, Rect)> = windows
            .iter()
            .map(|w| (*w, self.docking_rect(*w)))
            .collect();
        let mut group = vec![l];
        let mut i = 0;
        while i < group.len() {
            let a = rects.iter().find(|(w, _)| *w == group[i]).map(|x| x.1);
            let Some(a) = a else {
                break;
            };
            for (w, b) in &rects {
                if !group.contains(w) && touches(a, *b) && !overlaps(a, *b) {
                    group.push(*w);
                }
            }
            i += 1;
        }
        group
    }

    /// Whether window `l` touches another window.
    fn touches_any(&mut self, l: ObjId) -> bool {
        self.docked_group(l).len() > 1
    }

    /// What a window snaps to: the view (the viewport until the host gives a view size) first, then the docking rects of the windows from
    /// the last opened to the first, as Winamp tries them; `l` itself and `group` left out.
    /// `true` marks a window, which also offers its facing edges and must be touched.
    fn snap_targets(&mut self, l: ObjId, group: &[ObjId]) -> Vec<(bool, Rect)> {
        if self.needs_layout {
            self.do_layout();
        }
        let (vw, vh) = self.viewport();
        let mut targets: Vec<(bool, Rect)> = vec![(false, Rect::new(0, 0, vw, vh))];
        let others: Vec<ObjId> = self
            .windows()
            .into_iter()
            .rev()
            .filter(|w| *w != l && !group.contains(w))
            .collect();
        for w in others {
            let dr = self.docking_rect(w);
            targets.push((true, dr));
        }
        targets
    }

    /// Where the edges of window `l`'s rect `r` that a grip drags land (`edges` names them, as
    /// a grip's `resize` does): each snaps to the viewport's same edge, to the same edge of a
    /// window, or to the facing edge of one, when the window is then touched and not
    /// overlapped; the other edges stay. Winamp snaps a resize so.
    pub(crate) fn autodock_edges(&mut self, l: ObjId, r: Rect, edges: &str) -> Rect {
        let targets = self.snap_targets(l, &[]);
        let d = self.free.dock_distance;
        let m = self.snap_margins(l);
        let mut ri = inset(r, m);
        let left = edges.contains("left");
        let top = edges.contains("top");
        let right = edges.contains("right");
        let bottom = edges.contains("bottom");
        let near = |a: i32, b: i32| (b - d) < a && a < (b + d);
        for (window, o) in targets {
            let before = ri;
            let mut snapped_x = false;
            let mut snapped_y = false;
            if left && near(ri.left, o.left) {
                ri = with_left(ri, o.left);
                snapped_x = true;
            }
            if window && right && !snapped_x && near(ri.right(), o.left) {
                ri = with_right(ri, o.left);
                snapped_x = true;
            }
            if top && near(ri.top, o.top) {
                ri = with_top(ri, o.top);
                snapped_y = true;
            }
            if window && bottom && !snapped_y && near(ri.bottom(), o.top) {
                ri = with_bottom(ri, o.top);
                snapped_y = true;
            }
            if right && !snapped_x && near(ri.right(), o.right()) {
                ri = with_right(ri, o.right());
                snapped_x = true;
            }
            if window && left && !snapped_x && near(ri.left, o.right()) {
                ri = with_left(ri, o.right());
            }
            if bottom && !snapped_y && near(ri.bottom(), o.bottom()) {
                ri = with_bottom(ri, o.bottom());
                snapped_y = true;
            }
            if window && top && !snapped_y && near(ri.top, o.bottom()) {
                ri = with_top(ri, o.bottom());
            }
            if ri.width < 1 || ri.height < 1 || (window && (!touches(ri, o) || overlaps(ri, o))) {
                ri = before;
            }
        }
        outset(ri, m)
    }

    /// Where `r`, window `l`'s rect, lands when the listener moves it there: snapped to the
    /// viewport's edges and to the other windows, those in `group` left out as the ones moving
    /// along.
    pub(crate) fn autodock(&mut self, l: ObjId, r: Rect, group: &[ObjId]) -> Rect {
        let targets = self.snap_targets(l, group);
        let d = self.free.dock_distance;
        let m = self.snap_margins(l);
        let mut ri = inset(r, m);
        let near = |a: i32, b: i32| (b - d) < a && a < (b + d);
        for (window, o) in targets {
            let before = ri;
            let mut snapped_x = false;
            let mut snapped_y = false;
            // the same edge of the viewport or the window, and the facing edge of a window, in
            // the order Winamp tries them
            if near(ri.left, o.left) {
                ri = moved(ri, o.left - ri.left, 0);
                snapped_x = true;
            }
            if window && !snapped_x && near(ri.right(), o.left) {
                ri = moved(ri, o.left - ri.right(), 0);
                snapped_x = true;
            }
            if near(ri.top, o.top) {
                ri = moved(ri, 0, o.top - ri.top);
                snapped_y = true;
            }
            if window && !snapped_y && near(ri.bottom(), o.top) {
                ri = moved(ri, 0, o.top - ri.bottom());
                snapped_y = true;
            }
            if !snapped_x && near(ri.right(), o.right()) {
                ri = moved(ri, o.right() - ri.right(), 0);
                snapped_x = true;
            }
            if window && !snapped_x && near(ri.left, o.right()) {
                ri = moved(ri, o.right() - ri.left, 0);
            }
            if !snapped_y && near(ri.bottom(), o.bottom()) {
                ri = moved(ri, 0, o.bottom() - ri.bottom());
                snapped_y = true;
            }
            if window && !snapped_y && near(ri.top, o.bottom()) {
                ri = moved(ri, 0, o.bottom() - ri.top);
            }
            // a snap to a window holds only where the window is then touched, not overlapped
            if window && ri != before && (!touches(ri, o) || overlaps(ri, o)) {
                ri = before;
            }
        }
        outset(ri, m)
    }

    /// The finger goes down on window `window` at a point of the viewport, to move it.
    pub(crate) fn free_drag_begin(&mut self, window: ObjId, sx: i32, sy: i32) {
        let members = if Some(window) == self.main_layout() {
            self.docked_group(window)
        } else {
            vec![window]
        };
        let group: Vec<(ObjId, Rect)> = members
            .into_iter()
            .map(|l| (l, self.window_rect_of(l)))
            .collect();
        let docked_before = self.touches_any(window);
        self.free.drag = Some(Drag {
            window,
            origin: (sx, sy),
            group,
            docked_before,
            moved: false,
        });
    }

    /// Whether a window is being dragged.
    pub(crate) fn free_dragging(&self) -> bool {
        self.free.drag.is_some()
    }

    /// The finger moves to a point of the viewport while a window is dragged: the window and
    /// its group go along, snapped as Winamp snaps them.
    pub(crate) fn free_drag_to(&mut self, sx: i32, sy: i32) {
        let Some(drag) = self.free.drag.clone() else {
            return;
        };
        let (dx, dy) = (sx - drag.origin.0, sy - drag.origin.1);
        let members: Vec<ObjId> = drag.group.iter().map(|g| g.0).collect();
        let (lead, start) = drag.group[0];
        let wanted = moved(start, dx, dy);
        let got = self.autodock(lead, wanted, &members);
        let mut shift_x = got.left - wanted.left;
        let mut shift_y = got.top - wanted.top;
        // a member snapping to the viewport or to a window outside the group shifts the group
        let mut more_x = 0;
        let mut more_y = 0;
        for (l, r0) in drag.group.iter().skip(1) {
            let want = moved(*r0, dx + shift_x, dy + shift_y);
            let got = self.autodock(*l, want, &members);
            if more_x == 0 {
                more_x = got.left - want.left;
            }
            if more_y == 0 {
                more_y = got.top - want.top;
            }
        }
        shift_x += more_x;
        shift_y += more_y;
        // a move changes where the windows are, not what they draw: the placed rects shift and
        // the next frame carries them, with no layout pass and no new shapes
        let mut changed = false;
        for (l, r0) in &drag.group {
            let (x, y) = (r0.left + dx + shift_x, r0.top + dy + shift_y);
            let d = self.objects[*l].layout().expect("a layout");
            if d.view_x != x || d.view_y != y {
                changed = true;
                let d = self.objects[*l].layout_mut().expect("a layout");
                d.view_x = x;
                d.view_y = y;
                if let Some(r) = self.placed.get_mut(l) {
                    r.left = x;
                    r.top = y;
                }
            }
        }
        if !changed {
            return;
        }
        if let Some(d) = self.free.drag.as_mut() {
            d.moved = true;
        }
        // every window keeps its drawing; only where it shows changed
        self.moved_dirty = true;
        for (l, _) in &drag.group {
            self.dispatch(Handle::Gui(*l), "onmove", &[]);
        }
    }

    /// The finger lifts: the moved windows hear it, and the dragged one hears whether it is
    /// docked now where it was not, or the other way round.
    pub(crate) fn free_drag_end(&mut self) {
        let Some(drag) = self.free.drag.take() else {
            return;
        };
        if !drag.moved {
            return;
        }
        for (l, _) in &drag.group {
            self.dispatch(Handle::Gui(*l), "onendmove", &[]);
        }
        let docked = self.touches_any(drag.window);
        if docked != drag.docked_before {
            let event = if docked { "ondock" } else { "onundock" };
            self.dispatch(Handle::Gui(drag.window), event, &[]);
        }
    }

    /// Runs `change`, which resizes windows (a new scale), and keeps every window that hung
    /// off an edge of another hanging off that edge: from the main window outwards, each one
    /// goes back against the edge it touched, at the same offset along it, as Winamp keeps the
    /// equalizer and playlist under the main window when it doubles.
    pub(crate) fn keeping_docks(&mut self, change: impl FnOnce(&mut Self)) {
        if !self.free.on {
            change(self);
            return;
        }
        if self.needs_layout {
            self.do_layout();
        }
        let windows = self.windows();
        let before: Vec<(ObjId, Rect)> = windows
            .iter()
            .map(|l| (*l, self.docking_rect(*l)))
            .collect();
        let hangs = hanging(&before, self.main_layout());
        change(self);
        if self.needs_layout {
            self.do_layout();
        }
        for (child, parent, edge, along) in hangs {
            let p = self.docking_rect(parent);
            let c = self.docking_rect(child);
            let (x, y) = match edge {
                Edge::Below => (p.left + along, p.bottom()),
                Edge::Above => (p.left + along, p.top - c.height),
                Edge::Right => (p.right(), p.top + along),
                Edge::Left => (p.left - c.width, p.top + along),
            };
            let at = self.window_rect_of(child);
            let (dx, dy) = (x - c.left, y - c.top);
            if dx != 0 || dy != 0 {
                let d = self.objects[child].layout_mut().expect("a layout");
                d.view_x = at.left + dx;
                d.view_y = at.top + dy;
                self.relayout();
                self.do_layout();
            }
        }
    }

    /// A script's `beforeRedock` on window `l`: notes the windows docked to it and where its
    /// docking rect is, before the script changes that rect.
    pub(crate) fn before_redock(&mut self, l: ObjId) {
        if !self.free.on {
            return;
        }
        let rect = self.docking_rect(l);
        let docked: Vec<ObjId> = self.docked_group(l).into_iter().skip(1).collect();
        self.free.redock.retain(|(w, _, _)| *w != l);
        self.free.redock.push((l, rect, docked));
    }

    /// A script's `redock` on window `l`: the windows docked to an edge of it that moved go
    /// along with that edge, as the playlist under Winamp Modern's main window follows its
    /// drawer.
    pub(crate) fn redock(&mut self, l: ObjId) {
        if !self.free.on {
            return;
        }
        let Some(i) = self.free.redock.iter().position(|(w, _, _)| *w == l) else {
            return;
        };
        let (_, old, docked) = self.free.redock.remove(i);
        if self.needs_layout {
            self.do_layout();
        }
        let new = self.docking_rect(l);
        self.follow_edges(old, new, &docked);
    }

    /// Moves the windows `docked` to the edges of `old` along to the edges of `new`: what hung
    /// under the old bottom follows the bottom, what sat beside the right edge follows it, and so
    /// for the top and the left.
    fn follow_edges(&mut self, old: Rect, new: Rect, docked: &[ObjId]) {
        if new == old {
            return;
        }
        for w in docked {
            let r = self.docking_rect(*w);
            let (dx, dy) = if r.top >= old.bottom() {
                (0, new.bottom() - old.bottom())
            } else if r.left >= old.right() {
                (new.right() - old.right(), 0)
            } else if r.bottom() <= old.top {
                (0, new.top - old.top)
            } else if r.right() <= old.left {
                (new.left - old.left, 0)
            } else {
                (0, 0)
            };
            if dx != 0 || dy != 0 {
                let d = self.objects[*w].layout_mut().expect("a layout");
                d.view_x += dx;
                d.view_y += dy;
            }
        }
        self.relayout();
    }

    /// Before a container switches from layout `cur`: where it is, the windows docked to it, and
    /// its place in the order on top, for the layout that follows. Nothing while the windows are
    /// one stack.
    pub(crate) fn free_switch_begin(&mut self, cur: ObjId) -> Option<Switched> {
        if !self.free.on {
            return None;
        }
        let rect = self.docking_rect(cur);
        let width = self.window_rect_of(cur).width;
        let docked: Vec<ObjId> = self.docked_group(cur).into_iter().skip(1).collect();
        let d = self.objects[cur].layout().expect("a layout");
        let at = (d.view_x, d.view_y);
        let z_at = self.z_windows().iter().position(|w| *w == cur);
        Some(Switched {
            from: cur,
            rect,
            width,
            docked,
            at,
            z_at,
        })
    }

    /// After the switch to `target`: it takes the old layout's top-left corner and place on
    /// top, and the docked windows follow its edges, as the playlist docked under Winamp
    /// Modern's main window sits under its shade bar while it is shaded.
    pub(crate) fn free_switch_end(&mut self, target: ObjId, carried: Option<Switched>) {
        let Some(s) = carried else {
            return;
        };
        {
            let d = self.objects[target].layout_mut().expect("a layout");
            d.view_x = s.at.0;
            d.view_y = s.at.1;
            d.free_placed = true;
        }
        // layouts that link their widths share one: the shade bar is as wide as the window
        // was, and a bar the listener resized gives the window its width back
        let linked = {
            let t = self.objects[target].layout().expect("a layout");
            let o = self.objects[s.from].layout().expect("a layout");
            let tid = self.objects[target].base.id.to_lowercase();
            let oid = self.objects[s.from].base.id.to_lowercase();
            t.link_width.as_deref() == Some(oid.as_str())
                || o.link_width.as_deref() == Some(tid.as_str())
        };
        if linked && Some(target) != self.main_layout() {
            let h = self.objects[target]
                .layout()
                .and_then(|d| d.user_size)
                .map(|u| u.1)
                .or_else(|| {
                    self.objects[target]
                        .base
                        .attr("h")
                        .and_then(crate::gui::to_int_lenient)
                });
            if let Some(h) = h {
                let width = (s.width as f32 / self.layout_scale(target)).round() as i32;
                let d = self.objects[target].layout_mut().expect("a layout");
                d.user_size = Some((width, h));
            }
        }
        if let Some(i) = s.z_at {
            let mut z = self.z_windows();
            z.retain(|w| *w != target);
            z.insert(i.min(z.len()), target);
            self.free.z = z;
        }
        if self.needs_layout {
            self.do_layout();
        }
        let new = self.docking_rect(target);
        self.follow_edges(s.rect, new, &s.docked);
    }
}