atagen

monolith

public
Star0
Watch0
ccb74661e8c492e236c31c4d22ff9bdea0c5bff6
1
ssh://brewery@pls.lobotomise.me:33/atagen/monolith.git
crates/layout/src/tree.rsRust998 lines32.8 KB
1
use monolith_planner::Rect;
2
use slotmap::{SlotMap, new_key_type};
3
use std::collections::HashMap;
4
use std::hash::Hash;
5
6
new_key_type! { pub struct NodeId; }
7
8
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
9
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
10
#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
11
pub enum Axis {
12
    Horizontal,
13
    Vertical,
14
}
15
16
impl Axis {
17
    pub fn other(self) -> Self {
18
        match self {
19
            Self::Horizontal => Self::Vertical,
20
            Self::Vertical => Self::Horizontal,
21
        }
22
    }
23
24
    fn index(self) -> usize {
25
        match self {
26
            Self::Horizontal => 0,
27
            Self::Vertical => 1,
28
        }
29
    }
30
}
31
32
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
33
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
34
#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
35
pub enum Dir {
36
    Left,
37
    Right,
38
    Up,
39
    Down,
40
}
41
42
impl Dir {
43
    pub fn axis(self) -> Axis {
44
        match self {
45
            Self::Left | Self::Right => Axis::Horizontal,
46
            Self::Up | Self::Down => Axis::Vertical,
47
        }
48
    }
49
50
    pub fn forward(self) -> bool {
51
        matches!(self, Self::Right | Self::Down)
52
    }
53
}
54
55
const MIN_SHARE: f64 = 0.05;
56
57
/// A window's width and height relative to its neighbours'.
58
type Size = [f64; 2];
59
60
#[derive(Clone, Debug)]
61
enum Kind<W> {
62
    Leaf(W, Size),
63
    Container {
64
        axis: Axis,
65
        children: Vec<NodeId>,
66
        expanded: Option<NodeId>,
67
    },
68
}
69
70
#[derive(Clone, Debug)]
71
struct Node<W> {
72
    parent: Option<NodeId>,
73
    kind: Kind<W>,
74
}
75
76
/// One output's tiling tree. Every tiled window of every tag lives here, the
77
/// caller's visibility filter decides which ones take space.
78
///
79
/// Children run on the axis opposite their parent. Containers hold at least
80
/// two children, hidden ones included, and a container left with one child
81
/// is replaced by it.
82
#[derive(Clone, Debug)]
83
pub struct Tree<W> {
84
    nodes: SlotMap<NodeId, Node<W>>,
85
    root: Option<NodeId>,
86
    leaves: HashMap<W, NodeId>,
87
    stack: Axis,
88
}
89
90
impl<W: Copy + Eq + Hash> Default for Tree<W> {
91
    fn default() -> Self {
92
        Self {
93
            nodes: SlotMap::with_key(),
94
            root: None,
95
            leaves: HashMap::new(),
96
            stack: Axis::Vertical,
97
        }
98
    }
99
}
100
101
impl<W: Copy + Eq + Hash> Tree<W> {
102
    /// The axis tag rows stack along.
103
    pub fn stack_axis(&self) -> Axis {
104
        self.stack
105
    }
106
107
    pub fn contains(&self, w: W) -> bool {
108
        self.leaves.contains_key(&w)
109
    }
110
111
    pub fn is_empty(&self) -> bool {
112
        self.root.is_none()
113
    }
114
115
    pub fn windows(&self) -> impl Iterator<Item = W> + '_ {
116
        self.leaves.keys().copied()
117
    }
118
119
    /// Inserts `w` as the next sibling of `anchor`, or as a new row if
120
    /// `anchor` is not in the tree.
121
    pub fn insert_after(&mut self, w: W, anchor: W) {
122
        let Some(&a) = self.leaves.get(&anchor) else {
123
            return self.insert_row(w);
124
        };
125
        match self.position(a) {
126
            Some((p, i)) if Some(p) == self.root && self.axis(p) == Some(self.stack) => {
127
                let n = self.new_leaf(w, self.size(a));
128
                self.unlink(p, i);
129
                let c = self.new_container(self.stack.other());
130
                self.attach(c, 0, a);
131
                self.attach(c, 1, n);
132
                self.attach(p, i, c);
133
                self.reveal(n, true);
134
            }
135
            Some((p, i)) => {
136
                let n = self.new_leaf(w, self.size(p));
137
                self.attach(p, i + 1, n);
138
                self.reveal(n, true);
139
            }
140
            None => {
141
                let n = self.new_leaf(w, self.size(a));
142
                let c = self.new_container(self.stack.other());
143
                self.attach(c, 0, a);
144
                self.attach(c, 1, n);
145
                self.root = Some(c);
146
            }
147
        }
148
    }
149
150
    /// Inserts `w` after `anchor` by splitting `anchor` along `axis`. They
151
    /// share the space `anchor` had, and its siblings keep theirs.
152
    pub fn insert_split(&mut self, w: W, anchor: W, axis: Axis) {
153
        let Some(&a) = self.leaves.get(&anchor) else {
154
            return self.insert_row(w);
155
        };
156
        let size = self.size(a);
157
        let n = self.new_leaf(w, size);
158
        match self.position(a) {
159
            Some((p, i)) if self.axis(p) == Some(axis) => {
160
                self.halve(a, axis);
161
                self.halve(n, axis);
162
                self.attach(p, i + 1, n);
163
            }
164
            Some((p, i)) => {
165
                self.unlink(p, i);
166
                let c = self.new_container(axis);
167
                self.attach(c, 0, a);
168
                self.attach(c, 1, n);
169
                self.attach(p, i, c);
170
            }
171
            None => {
172
                let c = self.new_container(axis);
173
                self.attach(c, 0, a);
174
                self.attach(c, 1, n);
175
                self.root = Some(c);
176
            }
177
        }
178
        self.reveal(n, true);
179
    }
180
181
    fn halve(&mut self, leaf: NodeId, axis: Axis) {
182
        if let Kind::Leaf(_, size) = &mut self.nodes[leaf].kind {
183
            size[axis.index()] /= 2.0;
184
        }
185
    }
186
187
    /// Appends `w` as a row of its own along the stacking axis.
188
    pub fn insert_row(&mut self, w: W) {
189
        let size = self.root.map_or([1.0; 2], |r| self.size(r));
190
        let n = self.new_leaf(w, size);
191
        match self.root {
192
            None => self.root = Some(n),
193
            Some(r) if self.axis(r) == Some(self.stack) => {
194
                let end = self.children(r).len();
195
                self.attach(r, end, n);
196
            }
197
            Some(r) => {
198
                let c = self.new_container(self.stack);
199
                self.attach(c, 0, r);
200
                self.attach(c, 1, n);
201
                self.root = Some(c);
202
            }
203
        }
204
        self.reveal(n, true);
205
    }
206
207
    pub fn remove(&mut self, w: W) -> bool {
208
        let Some(n) = self.leaves.remove(&w) else {
209
            return false;
210
        };
211
        self.detach(n);
212
        self.nodes.remove(n);
213
        true
214
    }
215
216
    pub fn retain(&mut self, mut keep: impl FnMut(W) -> bool) {
217
        let gone: Vec<W> = self.windows().filter(|&w| !keep(w)).collect();
218
        for w in gone {
219
            self.remove(w);
220
        }
221
    }
222
223
    /// Moves a window one step in `dir`. Leaves swap slots with the next
224
    /// visible sibling, enter a sibling container, or step out beside their
225
    /// container. Hidden windows never move.
226
    pub fn move_window(&mut self, w: W, dir: Dir, vis: impl Fn(W) -> bool) -> bool {
227
        let Some(&n) = self.leaves.get(&w).filter(|_| vis(w)) else {
228
            return false;
229
        };
230
        self.until_seen(&vis, |t| {
231
            let moved = t.move_node(n, dir, &vis, true);
232
            t.reveal(n, moved)
233
        })
234
    }
235
236
    /// Moves the container holding `w` as a rigid block. A window sitting
237
    /// directly in the root is its own block.
238
    pub fn move_container(&mut self, w: W, dir: Dir, vis: impl Fn(W) -> bool) -> bool {
239
        let Some(&n) = self.leaves.get(&w).filter(|_| vis(w)) else {
240
            return false;
241
        };
242
        self.until_seen(&vis, |t| {
243
            let block = t.nodes[n]
244
                .parent
245
                .filter(|&p| Some(p) != t.root)
246
                .unwrap_or(n);
247
            let moved = t.move_node(block, dir, &vis, false);
248
            t.reveal(n, moved)
249
        })
250
    }
251
252
    /// Moves a window to the end of the next visible lane in `dir` among its
253
    /// siblings. A lone window there becomes a stack with it. A window with no
254
    /// sibling lane that way leaves its stack as `move_window` would, so it
255
    /// takes one press to step out and another to merge.
256
    pub fn merge_window(&mut self, w: W, dir: Dir, vis: impl Fn(W) -> bool) -> bool {
257
        let Some(&n) = self.leaves.get(&w).filter(|_| vis(w)) else {
258
            return false;
259
        };
260
        self.until_seen(&vis, |t| {
261
            if let Some((p, i)) = t.position(n)
262
                && t.axis(p) == Some(dir.axis())
263
                && let Some(j) = t.next_shown(p, i, dir, &vis)
264
            {
265
                t.join_lane(n, p, j);
266
                return t.reveal(n, true);
267
            }
268
            let moved = t.move_node(n, dir, &vis, true);
269
            t.reveal(n, moved)
270
        })
271
    }
272
273
    /// Repeats `step` until the visible layout changes, or undoes it all when
274
    /// it never does. Steps around hidden windows otherwise ate keypresses
275
    /// and rearranged windows the user could not see.
276
    fn until_seen(
277
        &mut self,
278
        vis: &impl Fn(W) -> bool,
279
        mut step: impl FnMut(&mut Self) -> bool,
280
    ) -> bool {
281
        let seen = |t: &Self| -> Vec<(W, Rect)> {
282
            t.arrange(Rect::new(0.0, 0.0, 1000.0, 1000.0), 0.0, vis)
283
                .into_iter()
284
                .filter(|p| vis(p.0))
285
                .collect()
286
        };
287
        let same = |a: &[(W, Rect)], b: &[(W, Rect)]| {
288
            a.len() == b.len()
289
                && a.iter().all(|(v, r)| {
290
                    b.iter().any(|(w, s)| {
291
                        v == w
292
                            && [r.x - s.x, r.y - s.y, r.w - s.w, r.h - s.h]
293
                                .iter()
294
                                .all(|d| d.abs() < 1e-6)
295
                    })
296
                })
297
        };
298
        let before = self.clone();
299
        let start = seen(self);
300
        for _ in 0..=before.nodes.len() {
301
            if !step(self) {
302
                break;
303
            }
304
            if !same(&start, &seen(self)) {
305
                return true;
306
            }
307
        }
308
        *self = before;
309
        false
310
    }
311
312
    /// Undoes any expansion along `leaf`'s ancestry that favours another
313
    /// child, once it has `moved` or arrived. An expanded container gives its
314
    /// other children no room, so a window moved into one vanished while
315
    /// staying focused.
316
    fn reveal(&mut self, leaf: NodeId, moved: bool) -> bool {
317
        let mut cur = leaf;
318
        while moved && let Some(p) = self.nodes[cur].parent {
319
            if let Kind::Container { expanded, .. } = &mut self.nodes[p].kind
320
                && expanded.is_some_and(|e| e != cur)
321
            {
322
                *expanded = None;
323
            }
324
            cur = p;
325
        }
326
        moved
327
    }
328
329
    /// Whether every container above `w` is expanded towards it.
330
    pub fn maximized(&self, w: W, vis: impl Fn(W) -> bool) -> bool {
331
        let path = self.shown_path(w, &vis);
332
        !path.is_empty() && path.iter().all(|&(p, c)| self.expanded(p) == Some(c))
333
    }
334
335
    /// `w`'s ancestry as (container, child) pairs, leaving out containers
336
    /// where the child has no visible sibling. Those look like nothing on
337
    /// screen, so expanding there would do nothing the user could see.
338
    fn shown_path(&self, w: W, vis: &impl Fn(W) -> bool) -> Vec<(NodeId, NodeId)> {
339
        let Some(&leaf) = self.leaves.get(&w) else {
340
            return Vec::new();
341
        };
342
        let mut path = Vec::new();
343
        let mut cur = leaf;
344
        while let Some(p) = self.nodes[cur].parent {
345
            let shared = self
346
                .children(p)
347
                .iter()
348
                .any(|&c| c != cur && self.visible(c, vis));
349
            if shared {
350
                path.push((p, cur));
351
            }
352
            cur = p;
353
        }
354
        path
355
    }
356
357
    /// Transposes the whole tree.
358
    pub fn flip(&mut self) {
359
        self.stack = self.stack.other();
360
        for node in self.nodes.values_mut() {
361
            match &mut node.kind {
362
                Kind::Container { axis, .. } => *axis = axis.other(),
363
                Kind::Leaf(_, size) => size.reverse(),
364
            }
365
        }
366
    }
367
368
    /// Toggles expansion for `count` levels of `w`'s visible ancestry,
369
    /// starting `skip` levels up. Level 0 expands the window inside the
370
    /// nearest container where it has a visible sibling.
371
    pub fn toggle_expand(
372
        &mut self,
373
        w: W,
374
        skip: usize,
375
        count: usize,
376
        vis: impl Fn(W) -> bool,
377
    ) -> bool {
378
        let path: Vec<_> = self
379
            .shown_path(w, &vis)
380
            .into_iter()
381
            .skip(skip)
382
            .take(count)
383
            .collect();
384
        if path.is_empty() {
385
            return false;
386
        }
387
        let all = path.iter().all(|&(p, c)| self.expanded(p) == Some(c));
388
        for (p, c) in path {
389
            if let Kind::Container { expanded, .. } = &mut self.nodes[p].kind {
390
                *expanded = (!all).then_some(c);
391
            }
392
        }
393
        true
394
    }
395
396
    /// Grows `w` by `delta`, a fraction of the visible length of the nearest
397
    /// container along `axis` where it has a visible sibling. Hidden siblings
398
    /// keep their sizes, and with them their share.
399
    pub fn resize(&mut self, w: W, axis: Axis, delta: f64, vis: impl Fn(W) -> bool) -> bool {
400
        let Some(&leaf) = self.leaves.get(&w) else {
401
            return false;
402
        };
403
        let mut cur = leaf;
404
        while let Some(p) = self.nodes[cur].parent {
405
            if self.axis(p) == Some(axis) {
406
                let shown: Vec<(NodeId, f64)> = self
407
                    .children(p)
408
                    .iter()
409
                    .filter(|&&c| self.visible(c, &vis))
410
                    .map(|&c| (c, self.extent(c, axis, &vis)))
411
                    .collect();
412
                if shown.len() >= 2 {
413
                    let sum: f64 = shown.iter().map(|s| s.1).sum();
414
                    let old = self.extent(cur, axis, &vis);
415
                    let max = 1.0 - MIN_SHARE * (shown.len() - 1) as f64;
416
                    let new = (old / sum + delta).clamp(MIN_SHARE, max) * sum;
417
                    let scale = (sum - new) / (sum - old);
418
                    for (c, _) in shown {
419
                        self.scale(c, axis, if c == cur { new / old } else { scale });
420
                    }
421
                    return true;
422
                }
423
            }
424
            cur = p;
425
        }
426
        false
427
    }
428
429
    /// The lane a window's split on side `dir` lives in, as the child holding
430
    /// the window, its parent and the index of the visible sibling across
431
    /// the split.
432
    fn split_across(
433
        &self,
434
        w: W,
435
        dir: Dir,
436
        vis: &impl Fn(W) -> bool,
437
    ) -> Option<(NodeId, NodeId, usize)> {
438
        let mut cur = *self.leaves.get(&w)?;
439
        if !self.visible(cur, vis) {
440
            return None;
441
        }
442
        while let Some((p, i)) = self.position(cur) {
443
            if self.axis(p) == Some(dir.axis())
444
                && let Some(j) = self.next_shown(p, i, dir, vis)
445
            {
446
                return Some((cur, p, j));
447
            }
448
            cur = p;
449
        }
450
        None
451
    }
452
453
    /// Whether the split on side `dir` of `w` has a visible window across it.
454
    pub fn has_split(&self, w: W, dir: Dir, vis: impl Fn(W) -> bool) -> bool {
455
        self.split_across(w, dir, &vis).is_some()
456
    }
457
458
    /// Moves the split on side `dir` of `w` by `px` along that side's axis,
459
    /// positive toward the right or bottom. Only the two children meeting at
460
    /// the split change, so the split follows the pointer.
461
    pub fn move_split(
462
        &mut self,
463
        w: W,
464
        dir: Dir,
465
        px: f64,
466
        area: Rect,
467
        gap: f64,
468
        vis: impl Fn(W) -> bool,
469
    ) -> bool {
470
        let Some((cur, p, j)) = self.split_across(w, dir, &vis) else {
471
            return false;
472
        };
473
        let axis = dir.axis();
474
        let other = self.children(p)[j];
475
        let (first, second) = if dir.forward() {
476
            (cur, other)
477
        } else {
478
            (other, cur)
479
        };
480
        let mut leaves = Vec::new();
481
        self.shown_leaves(first, &vis, &mut leaves);
482
        let (start, end) = self
483
            .arrange(area, gap, &vis)
484
            .iter()
485
            .filter(|(l, _)| leaves.contains(l))
486
            .map(|(_, r)| span(*r, axis))
487
            .fold((f64::MAX, f64::MIN), |(s, e), (rs, rl)| {
488
                (s.min(rs), e.max(rs + rl))
489
            });
490
        let ef = self.extent(first, axis, &vis);
491
        let es = self.extent(second, axis, &vis);
492
        if end <= start || ef <= 0.0 || es <= 0.0 {
493
            return true;
494
        }
495
        let sum: f64 = self
496
            .children(p)
497
            .iter()
498
            .filter(|&&c| self.visible(c, &vis))
499
            .map(|&c| self.extent(c, axis, &vis))
500
            .sum();
501
        let min = MIN_SHARE * sum;
502
        let du = (px * ef / (end - start)).clamp(-(ef - min).max(0.0), (es - min).max(0.0));
503
        self.scale(first, axis, (ef + du) / ef);
504
        self.scale(second, axis, (es - du) / es);
505
        true
506
    }
507
508
    fn shown_leaves(&self, n: NodeId, vis: &impl Fn(W) -> bool, out: &mut Vec<W>) {
509
        match &self.nodes[n].kind {
510
            Kind::Leaf(w, _) => {
511
                if vis(*w) {
512
                    out.push(*w);
513
                }
514
            }
515
            Kind::Container { children, .. } => {
516
                for &c in children {
517
                    self.shown_leaves(c, vis, out);
518
                }
519
            }
520
        }
521
    }
522
523
    /// Scales every window under `n` along `axis`, hidden ones too, so they
524
    /// keep their proportions for when they are shown again.
525
    fn scale(&mut self, n: NodeId, axis: Axis, by: f64) {
526
        match &mut self.nodes[n].kind {
527
            Kind::Leaf(_, size) => size[axis.index()] *= by,
528
            Kind::Container { children, .. } => {
529
                for c in children.clone() {
530
                    self.scale(c, axis, by);
531
                }
532
            }
533
        }
534
    }
535
536
    /// How much room `n` asks for along `axis` among its siblings. A
537
    /// container asks for the mean of what its visible children ask for, so
538
    /// windows of other tags sharing a lane change nothing on screen, and a
539
    /// window carries its own size wherever it moves.
540
    fn extent(&self, n: NodeId, axis: Axis, vis: &impl Fn(W) -> bool) -> f64 {
541
        match &self.nodes[n].kind {
542
            Kind::Leaf(_, size) => size[axis.index()],
543
            Kind::Container { children, .. } => {
544
                let shown: Vec<f64> = children
545
                    .iter()
546
                    .filter(|&&c| self.visible(c, vis))
547
                    .map(|&c| self.extent(c, axis, vis))
548
                    .collect();
549
                if shown.is_empty() {
550
                    children
551
                        .iter()
552
                        .map(|&c| self.extent(c, axis, vis))
553
                        .sum::<f64>()
554
                        / children.len() as f64
555
                } else {
556
                    shown.iter().sum::<f64>() / shown.len() as f64
557
                }
558
            }
559
        }
560
    }
561
562
    /// The size a window placed in `n`'s stead would take, ignoring
563
    /// visibility since new windows land on any tag.
564
    fn size(&self, n: NodeId) -> Size {
565
        let all = |_: W| true;
566
        [
567
            self.extent(n, Axis::Horizontal, &all),
568
            self.extent(n, Axis::Vertical, &all),
569
        ]
570
    }
571
572
    /// Lays the tree out in `area`. Hidden windows come back as zero-size
573
    /// rects on the boundary where they would reappear.
574
    pub fn arrange(&self, area: Rect, gap: f64, vis: impl Fn(W) -> bool) -> Vec<(W, Rect)> {
575
        let mut out = Vec::with_capacity(self.leaves.len());
576
        if let Some(r) = self.root {
577
            let area = if self.visible(r, &vis) {
578
                area
579
            } else if area.w >= area.h {
580
                Rect::new(area.right(), area.y, 0.0, area.h)
581
            } else {
582
                Rect::new(area.x, area.bottom(), area.w, 0.0)
583
            };
584
            self.place(r, area, gap, &vis, &mut out);
585
        }
586
        out
587
    }
588
589
    fn place(
590
        &self,
591
        n: NodeId,
592
        r: Rect,
593
        gap: f64,
594
        vis: &impl Fn(W) -> bool,
595
        out: &mut Vec<(W, Rect)>,
596
    ) {
597
        let (axis, children, expanded) = match &self.nodes[n].kind {
598
            Kind::Leaf(w, _) => return out.push((*w, r)),
599
            Kind::Container {
600
                axis,
601
                children,
602
                expanded,
603
            } => (*axis, children, *expanded),
604
        };
605
        let shown: Vec<bool> = children.iter().map(|&c| self.visible(c, vis)).collect();
606
        let (start, len) = span(r, axis);
607
        if let Some(e) = expanded.and_then(|e| children.iter().position(|&c| c == e))
608
            && shown[e]
609
        {
610
            for (i, &c) in children.iter().enumerate() {
611
                let sub = match i.cmp(&e) {
612
                    std::cmp::Ordering::Equal => r,
613
                    std::cmp::Ordering::Less => with_span(r, axis, start, 0.0),
614
                    std::cmp::Ordering::Greater => with_span(r, axis, start + len, 0.0),
615
                };
616
                self.place(c, sub, gap, vis, out);
617
            }
618
            return;
619
        }
620
        let count = shown.iter().filter(|s| **s).count();
621
        let extents: Vec<f64> = children
622
            .iter()
623
            .zip(&shown)
624
            .map(|(&c, &s)| if s { self.extent(c, axis, vis) } else { 0.0 })
625
            .collect();
626
        let total: f64 = extents.iter().sum();
627
        let gaps = count.saturating_sub(1) as f64;
628
        let gap = if gaps > 0.0 { gap.min(len / gaps) } else { gap };
629
        let avail = len - gap * gaps;
630
        let last = shown.iter().rposition(|s| *s);
631
        let mut pos = start;
632
        let mut seen = false;
633
        for (i, &c) in children.iter().enumerate() {
634
            if shown[i] {
635
                if seen {
636
                    pos += gap;
637
                }
638
                let l = avail * extents[i] / total;
639
                self.place(c, with_span(r, axis, pos, l), gap, vis, out);
640
                pos += l;
641
                seen = true;
642
            } else {
643
                let between = seen && last.is_some_and(|l| l > i);
644
                let at = if between { pos + gap / 2.0 } else { pos };
645
                self.place(c, with_span(r, axis, at, 0.0), gap, vis, out);
646
            }
647
        }
648
    }
649
650
    fn move_node(&mut self, n: NodeId, dir: Dir, vis: &impl Fn(W) -> bool, enter: bool) -> bool {
651
        let mut cur = n;
652
        while let Some((p, i)) = self.position(cur) {
653
            if self.axis(p) == Some(dir.axis()) {
654
                let hidden_lane = self
655
                    .adjacent(p, i, dir)
656
                    .filter(|&j| enter && !self.visible(self.children(p)[j], vis));
657
                if cur != n {
658
                    if let Some(j) = hidden_lane {
659
                        self.join_lane(n, p, j);
660
                    } else {
661
                        let at = if dir.forward() { i + 1 } else { i };
662
                        self.relocate(n, p, at);
663
                    }
664
                    return true;
665
                }
666
                if let Some(j) = self.next_shown(p, i, dir, vis) {
667
                    let sib = self.children(p)[j];
668
                    if enter && self.shown_windows(sib, vis) > 1 {
669
                        self.join_lane(n, p, j);
670
                    } else {
671
                        let children = self.children_mut(p);
672
                        children.swap(i, j);
673
                    }
674
                    return true;
675
                }
676
                if let Some(j) = hidden_lane {
677
                    self.join_lane(n, p, j);
678
                    return true;
679
                }
680
            }
681
            cur = p;
682
        }
683
        if cur == n || self.axis(cur) == Some(dir.axis()) {
684
            return false;
685
        }
686
        let (old, i) = self.position(n).expect("n is below the root");
687
        self.unlink(old, i);
688
        self.normalize(old);
689
        let r = self.root.expect("the rest of the tree survives");
690
        if self.axis(r) == Some(dir.axis()) {
691
            let at = if dir.forward() {
692
                self.children(r).len()
693
            } else {
694
                0
695
            };
696
            self.attach(r, at, n);
697
        } else {
698
            let c = self.new_container(dir.axis());
699
            self.attach(c, 0, r);
700
            let at = if dir.forward() {
701
                self.children(c).len()
702
            } else {
703
                0
704
            };
705
            self.attach(c, at, n);
706
            self.root = Some(c);
707
        }
708
        true
709
    }
710
711
    fn next_shown(&self, p: NodeId, i: usize, dir: Dir, vis: &impl Fn(W) -> bool) -> Option<usize> {
712
        let children = self.children(p);
713
        if dir.forward() {
714
            (i + 1..children.len()).find(|&j| self.visible(children[j], vis))
715
        } else {
716
            (0..i).rev().find(|&j| self.visible(children[j], vis))
717
        }
718
    }
719
720
    fn adjacent(&self, p: NodeId, i: usize, dir: Dir) -> Option<usize> {
721
        let j = if dir.forward() {
722
            i + 1
723
        } else {
724
            i.checked_sub(1)?
725
        };
726
        (j < self.children(p).len()).then_some(j)
727
    }
728
729
    /// Moves `n` to the end of the lane at `p`'s child `j`. A lone window
730
    /// there becomes a lane of its own, perpendicular to `p`.
731
    fn join_lane(&mut self, n: NodeId, p: NodeId, j: usize) {
732
        let lane = self.children(p)[j];
733
        let lane = if self.axis(lane).is_some() {
734
            lane
735
        } else {
736
            let c = self.new_container(self.axis(p).expect("p is a container").other());
737
            self.children_mut(p)[j] = c;
738
            self.nodes[c].parent = Some(p);
739
            if let Kind::Container { expanded, .. } = &mut self.nodes[p].kind
740
                && *expanded == Some(lane)
741
            {
742
                *expanded = Some(c);
743
            }
744
            self.attach(c, 0, lane);
745
            c
746
        };
747
        let end = self.children(lane).len();
748
        self.relocate(n, lane, end);
749
    }
750
751
    fn relocate(&mut self, n: NodeId, p: NodeId, at: usize) {
752
        let (old, i) = self.position(n).expect("relocated nodes have a parent");
753
        let at = if old == p && i < at { at - 1 } else { at };
754
        self.unlink(old, i);
755
        self.attach(p, at, n);
756
        self.normalize(old);
757
    }
758
759
    /// Places `node` among `p`'s children. A container running along `p`'s
760
    /// axis is dissolved into `p` so axes keep alternating.
761
    fn attach(&mut self, p: NodeId, at: usize, node: NodeId) {
762
        if self.axis(node).is_some() && self.axis(node) == self.axis(p) {
763
            let children = self.children(node).to_vec();
764
            self.nodes.remove(node);
765
            for (k, &c) in children.iter().enumerate() {
766
                self.nodes[c].parent = Some(p);
767
                self.children_mut(p).insert(at + k, c);
768
            }
769
        } else {
770
            self.nodes[node].parent = Some(p);
771
            self.children_mut(p).insert(at, node);
772
        }
773
    }
774
775
    fn unlink(&mut self, p: NodeId, i: usize) {
776
        let child = self.unlink_dead(p, i);
777
        self.nodes[child].parent = None;
778
    }
779
780
    fn detach(&mut self, n: NodeId) {
781
        match self.position(n) {
782
            Some((p, i)) => {
783
                self.unlink(p, i);
784
                self.normalize(p);
785
            }
786
            None => self.root = None,
787
        }
788
    }
789
790
    /// Repairs a container that lost a child.
791
    fn normalize(&mut self, c: NodeId) {
792
        if self.children(c).len() >= 2 {
793
            return;
794
        }
795
        let pos = self.position(c);
796
        let was_expanded = pos.is_some_and(|(p, _)| self.expanded(p) == Some(c));
797
        let Some(Node {
798
            kind: Kind::Container { children, .. },
799
            ..
800
        }) = self.nodes.remove(c)
801
        else {
802
            unreachable!("only containers are normalized");
803
        };
804
        let only = children.into_iter().next();
805
        match (only, pos) {
806
            (None, Some((p, i))) => {
807
                self.unlink_dead(p, i);
808
                self.normalize(p);
809
            }
810
            (None, None) => self.root = None,
811
            (Some(only), Some((p, i))) => {
812
                self.unlink_dead(p, i);
813
                let leaf_like = self.axis(only) != self.axis(p);
814
                self.attach(p, i, only);
815
                if was_expanded
816
                    && leaf_like
817
                    && let Kind::Container { expanded, .. } = &mut self.nodes[p].kind
818
                {
819
                    *expanded = Some(only);
820
                }
821
            }
822
            (Some(only), None) => {
823
                self.nodes[only].parent = None;
824
                self.root = Some(only);
825
            }
826
        }
827
    }
828
829
    /// Like `unlink`, for a child whose node is already gone.
830
    fn unlink_dead(&mut self, p: NodeId, i: usize) -> NodeId {
831
        let Kind::Container {
832
            children, expanded, ..
833
        } = &mut self.nodes[p].kind
834
        else {
835
            unreachable!("parents are containers");
836
        };
837
        let child = children.remove(i);
838
        if *expanded == Some(child) {
839
            *expanded = None;
840
        }
841
        child
842
    }
843
844
    fn new_leaf(&mut self, w: W, size: Size) -> NodeId {
845
        let n = self.nodes.insert(Node {
846
            parent: None,
847
            kind: Kind::Leaf(w, size),
848
        });
849
        self.leaves.insert(w, n);
850
        n
851
    }
852
853
    fn new_container(&mut self, axis: Axis) -> NodeId {
854
        self.nodes.insert(Node {
855
            parent: None,
856
            kind: Kind::Container {
857
                axis,
858
                children: Vec::new(),
859
                expanded: None,
860
            },
861
        })
862
    }
863
864
    fn position(&self, n: NodeId) -> Option<(NodeId, usize)> {
865
        let p = self.nodes[n].parent?;
866
        let i = self.children(p).iter().position(|&c| c == n)?;
867
        Some((p, i))
868
    }
869
870
    fn axis(&self, n: NodeId) -> Option<Axis> {
871
        match &self.nodes[n].kind {
872
            Kind::Container { axis, .. } => Some(*axis),
873
            Kind::Leaf(..) => None,
874
        }
875
    }
876
877
    fn expanded(&self, n: NodeId) -> Option<NodeId> {
878
        match &self.nodes[n].kind {
879
            Kind::Container { expanded, .. } => *expanded,
880
            Kind::Leaf(..) => None,
881
        }
882
    }
883
884
    fn children(&self, n: NodeId) -> &[NodeId] {
885
        match &self.nodes[n].kind {
886
            Kind::Container { children, .. } => children,
887
            Kind::Leaf(..) => &[],
888
        }
889
    }
890
891
    fn children_mut(&mut self, n: NodeId) -> &mut Vec<NodeId> {
892
        match &mut self.nodes[n].kind {
893
            Kind::Container { children, .. } => children,
894
            Kind::Leaf(..) => unreachable!("leaves have no children"),
895
        }
896
    }
897
898
    fn visible(&self, n: NodeId, vis: &impl Fn(W) -> bool) -> bool {
899
        match &self.nodes[n].kind {
900
            Kind::Leaf(w, _) => vis(*w),
901
            Kind::Container { children, .. } => children.iter().any(|&c| self.visible(c, vis)),
902
        }
903
    }
904
905
    fn shown_windows(&self, n: NodeId, vis: &impl Fn(W) -> bool) -> usize {
906
        match &self.nodes[n].kind {
907
            Kind::Leaf(w, _) => usize::from(vis(*w)),
908
            Kind::Container { children, .. } => {
909
                children.iter().map(|&c| self.shown_windows(c, vis)).sum()
910
            }
911
        }
912
    }
913
914
    #[cfg(test)]
915
    pub(crate) fn shape(&self) -> String
916
    where
917
        W: std::fmt::Debug,
918
    {
919
        fn go<W: Copy + Eq + Hash + std::fmt::Debug>(t: &Tree<W>, n: NodeId) -> String {
920
            match &t.nodes[n].kind {
921
                Kind::Leaf(w, [x, y]) => format!("{w:?}[{x:.6},{y:.6}]"),
922
                Kind::Container {
923
                    axis,
924
                    children,
925
                    expanded,
926
                } => {
927
                    let inner: Vec<String> = children.iter().map(|&c| go(t, c)).collect();
928
                    let e = expanded.and_then(|e| children.iter().position(|&c| c == e));
929
                    format!("{axis:?}{e:?}({})", inner.join(" "))
930
                }
931
            }
932
        }
933
        self.root.map(|r| go(self, r)).unwrap_or_default()
934
    }
935
936
    #[cfg(test)]
937
    pub(crate) fn check(&self) {
938
        let reachable = match self.root {
939
            Some(r) => {
940
                assert!(self.nodes[r].parent.is_none());
941
                self.check_node(r)
942
            }
943
            None => 0,
944
        };
945
        assert_eq!(reachable, self.nodes.len(), "orphaned nodes");
946
        for (&w, &n) in &self.leaves {
947
            assert!(matches!(self.nodes[n].kind, Kind::Leaf(x, _) if x == w));
948
        }
949
    }
950
951
    #[cfg(test)]
952
    fn check_node(&self, n: NodeId) -> usize {
953
        match &self.nodes[n].kind {
954
            Kind::Leaf(_, size) => {
955
                assert!(
956
                    size.iter().all(|s| *s > 0.0 && s.is_finite()),
957
                    "size {size:?}"
958
                );
959
                1
960
            }
961
            Kind::Container {
962
                axis,
963
                children,
964
                expanded,
965
            } => {
966
                assert!(
967
                    children.len() >= 2,
968
                    "container with {} children",
969
                    children.len()
970
                );
971
                if let Some(e) = expanded {
972
                    assert!(children.contains(e));
973
                }
974
                let mut count = 1;
975
                for &c in children {
976
                    assert_eq!(self.nodes[c].parent, Some(n));
977
                    assert_ne!(self.axis(c), Some(*axis), "axes must alternate");
978
                    count += self.check_node(c);
979
                }
980
                count
981
            }
982
        }
983
    }
984
}
985
986
fn span(r: Rect, axis: Axis) -> (f64, f64) {
987
    match axis {
988
        Axis::Horizontal => (r.x, r.w),
989
        Axis::Vertical => (r.y, r.h),
990
    }
991
}
992
993
fn with_span(r: Rect, axis: Axis, start: f64, len: f64) -> Rect {
994
    match axis {
995
        Axis::Horizontal => Rect::new(start, r.y, len, r.h),
996
        Axis::Vertical => Rect::new(r.x, start, r.w, len),
997
    }
998
}