atagen

monolith

public
Star0
Watch0
8a73f3b6881806da05f45819e3246bd41d5ee6b0
1
ssh://brewery@pls.lobotomise.me:33/atagen/monolith.git
crates/layout/src/tree.rsRust865 lines28.4 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
    /// Appends `w` as a row of its own along the stacking axis.
151
    pub fn insert_row(&mut self, w: W) {
152
        let size = self.root.map_or([1.0; 2], |r| self.size(r));
153
        let n = self.new_leaf(w, size);
154
        match self.root {
155
            None => self.root = Some(n),
156
            Some(r) if self.axis(r) == Some(self.stack) => {
157
                let end = self.children(r).len();
158
                self.attach(r, end, n);
159
            }
160
            Some(r) => {
161
                let c = self.new_container(self.stack);
162
                self.attach(c, 0, r);
163
                self.attach(c, 1, n);
164
                self.root = Some(c);
165
            }
166
        }
167
        self.reveal(n, true);
168
    }
169
170
    pub fn remove(&mut self, w: W) -> bool {
171
        let Some(n) = self.leaves.remove(&w) else {
172
            return false;
173
        };
174
        self.detach(n);
175
        self.nodes.remove(n);
176
        true
177
    }
178
179
    pub fn retain(&mut self, mut keep: impl FnMut(W) -> bool) {
180
        let gone: Vec<W> = self.windows().filter(|&w| !keep(w)).collect();
181
        for w in gone {
182
            self.remove(w);
183
        }
184
    }
185
186
    /// Moves a window one step in `dir`. Leaves swap slots with the next
187
    /// visible sibling, enter a sibling container, or step out beside their
188
    /// container. Hidden windows never move.
189
    pub fn move_window(&mut self, w: W, dir: Dir, vis: impl Fn(W) -> bool) -> bool {
190
        let Some(&n) = self.leaves.get(&w).filter(|_| vis(w)) else {
191
            return false;
192
        };
193
        self.until_seen(&vis, |t| {
194
            let moved = t.move_node(n, dir, &vis, true);
195
            t.reveal(n, moved)
196
        })
197
    }
198
199
    /// Moves the container holding `w` as a rigid block. A window sitting
200
    /// directly in the root is its own block.
201
    pub fn move_container(&mut self, w: W, dir: Dir, vis: impl Fn(W) -> bool) -> bool {
202
        let Some(&n) = self.leaves.get(&w).filter(|_| vis(w)) else {
203
            return false;
204
        };
205
        self.until_seen(&vis, |t| {
206
            let block = t.nodes[n]
207
                .parent
208
                .filter(|&p| Some(p) != t.root)
209
                .unwrap_or(n);
210
            let moved = t.move_node(block, dir, &vis, false);
211
            t.reveal(n, moved)
212
        })
213
    }
214
215
    /// Moves a window to the end of the next visible lane in `dir` among its
216
    /// siblings. A lone window there becomes a stack with it. A window with no
217
    /// sibling lane that way leaves its stack as `move_window` would, so it
218
    /// takes one press to step out and another to merge.
219
    pub fn merge_window(&mut self, w: W, dir: Dir, vis: impl Fn(W) -> bool) -> bool {
220
        let Some(&n) = self.leaves.get(&w).filter(|_| vis(w)) else {
221
            return false;
222
        };
223
        self.until_seen(&vis, |t| {
224
            if let Some((p, i)) = t.position(n)
225
                && t.axis(p) == Some(dir.axis())
226
                && let Some(j) = t.next_shown(p, i, dir, &vis)
227
            {
228
                t.join_lane(n, p, j);
229
                return t.reveal(n, true);
230
            }
231
            let moved = t.move_node(n, dir, &vis, true);
232
            t.reveal(n, moved)
233
        })
234
    }
235
236
    /// Repeats `step` until the visible layout changes, or undoes it all when
237
    /// it never does. Steps around hidden windows otherwise ate keypresses
238
    /// and rearranged windows the user could not see.
239
    fn until_seen(
240
        &mut self,
241
        vis: &impl Fn(W) -> bool,
242
        mut step: impl FnMut(&mut Self) -> bool,
243
    ) -> bool {
244
        let seen = |t: &Self| -> Vec<(W, Rect)> {
245
            t.arrange(Rect::new(0.0, 0.0, 1000.0, 1000.0), 0.0, vis)
246
                .into_iter()
247
                .filter(|p| vis(p.0))
248
                .collect()
249
        };
250
        let same = |a: &[(W, Rect)], b: &[(W, Rect)]| {
251
            a.len() == b.len()
252
                && a.iter().all(|(v, r)| {
253
                    b.iter().any(|(w, s)| {
254
                        v == w
255
                            && [r.x - s.x, r.y - s.y, r.w - s.w, r.h - s.h]
256
                                .iter()
257
                                .all(|d| d.abs() < 1e-6)
258
                    })
259
                })
260
        };
261
        let before = self.clone();
262
        let start = seen(self);
263
        for _ in 0..=before.nodes.len() {
264
            if !step(self) {
265
                break;
266
            }
267
            if !same(&start, &seen(self)) {
268
                return true;
269
            }
270
        }
271
        *self = before;
272
        false
273
    }
274
275
    /// Undoes any expansion along `leaf`'s ancestry that favours another
276
    /// child, once it has `moved` or arrived. An expanded container gives its
277
    /// other children no room, so a window moved into one vanished while
278
    /// staying focused.
279
    fn reveal(&mut self, leaf: NodeId, moved: bool) -> bool {
280
        let mut cur = leaf;
281
        while moved && let Some(p) = self.nodes[cur].parent {
282
            if let Kind::Container { expanded, .. } = &mut self.nodes[p].kind
283
                && expanded.is_some_and(|e| e != cur)
284
            {
285
                *expanded = None;
286
            }
287
            cur = p;
288
        }
289
        moved
290
    }
291
292
    /// Whether every container above `w` is expanded towards it.
293
    pub fn maximized(&self, w: W, vis: impl Fn(W) -> bool) -> bool {
294
        let path = self.shown_path(w, &vis);
295
        !path.is_empty() && path.iter().all(|&(p, c)| self.expanded(p) == Some(c))
296
    }
297
298
    /// `w`'s ancestry as (container, child) pairs, leaving out containers
299
    /// where the child has no visible sibling. Those look like nothing on
300
    /// screen, so expanding there would do nothing the user could see.
301
    fn shown_path(&self, w: W, vis: &impl Fn(W) -> bool) -> Vec<(NodeId, NodeId)> {
302
        let Some(&leaf) = self.leaves.get(&w) else {
303
            return Vec::new();
304
        };
305
        let mut path = Vec::new();
306
        let mut cur = leaf;
307
        while let Some(p) = self.nodes[cur].parent {
308
            let shared = self
309
                .children(p)
310
                .iter()
311
                .any(|&c| c != cur && self.visible(c, vis));
312
            if shared {
313
                path.push((p, cur));
314
            }
315
            cur = p;
316
        }
317
        path
318
    }
319
320
    /// Transposes the whole tree.
321
    pub fn flip(&mut self) {
322
        self.stack = self.stack.other();
323
        for node in self.nodes.values_mut() {
324
            match &mut node.kind {
325
                Kind::Container { axis, .. } => *axis = axis.other(),
326
                Kind::Leaf(_, size) => size.reverse(),
327
            }
328
        }
329
    }
330
331
    /// Toggles expansion for `count` levels of `w`'s visible ancestry,
332
    /// starting `skip` levels up. Level 0 expands the window inside the
333
    /// nearest container where it has a visible sibling.
334
    pub fn toggle_expand(
335
        &mut self,
336
        w: W,
337
        skip: usize,
338
        count: usize,
339
        vis: impl Fn(W) -> bool,
340
    ) -> bool {
341
        let path: Vec<_> = self
342
            .shown_path(w, &vis)
343
            .into_iter()
344
            .skip(skip)
345
            .take(count)
346
            .collect();
347
        if path.is_empty() {
348
            return false;
349
        }
350
        let all = path.iter().all(|&(p, c)| self.expanded(p) == Some(c));
351
        for (p, c) in path {
352
            if let Kind::Container { expanded, .. } = &mut self.nodes[p].kind {
353
                *expanded = (!all).then_some(c);
354
            }
355
        }
356
        true
357
    }
358
359
    /// Grows `w` by `delta`, a fraction of the visible length of the nearest
360
    /// container along `axis` where it has a visible sibling. Hidden siblings
361
    /// keep their sizes, and with them their share.
362
    pub fn resize(&mut self, w: W, axis: Axis, delta: f64, vis: impl Fn(W) -> bool) -> bool {
363
        let Some(&leaf) = self.leaves.get(&w) else {
364
            return false;
365
        };
366
        let mut cur = leaf;
367
        while let Some(p) = self.nodes[cur].parent {
368
            if self.axis(p) == Some(axis) {
369
                let shown: Vec<(NodeId, f64)> = self
370
                    .children(p)
371
                    .iter()
372
                    .filter(|&&c| self.visible(c, &vis))
373
                    .map(|&c| (c, self.extent(c, axis, &vis)))
374
                    .collect();
375
                if shown.len() >= 2 {
376
                    let sum: f64 = shown.iter().map(|s| s.1).sum();
377
                    let old = self.extent(cur, axis, &vis);
378
                    let max = 1.0 - MIN_SHARE * (shown.len() - 1) as f64;
379
                    let new = (old / sum + delta).clamp(MIN_SHARE, max) * sum;
380
                    let scale = (sum - new) / (sum - old);
381
                    for (c, _) in shown {
382
                        self.scale(c, axis, if c == cur { new / old } else { scale });
383
                    }
384
                    return true;
385
                }
386
            }
387
            cur = p;
388
        }
389
        false
390
    }
391
392
    /// Scales every window under `n` along `axis`, hidden ones too, so they
393
    /// keep their proportions for when they are shown again.
394
    fn scale(&mut self, n: NodeId, axis: Axis, by: f64) {
395
        match &mut self.nodes[n].kind {
396
            Kind::Leaf(_, size) => size[axis.index()] *= by,
397
            Kind::Container { children, .. } => {
398
                for c in children.clone() {
399
                    self.scale(c, axis, by);
400
                }
401
            }
402
        }
403
    }
404
405
    /// How much room `n` asks for along `axis` among its siblings. A
406
    /// container asks for the mean of what its visible children ask for, so
407
    /// windows of other tags sharing a lane change nothing on screen, and a
408
    /// window carries its own size wherever it moves.
409
    fn extent(&self, n: NodeId, axis: Axis, vis: &impl Fn(W) -> bool) -> f64 {
410
        match &self.nodes[n].kind {
411
            Kind::Leaf(_, size) => size[axis.index()],
412
            Kind::Container { children, .. } => {
413
                let shown: Vec<f64> = children
414
                    .iter()
415
                    .filter(|&&c| self.visible(c, vis))
416
                    .map(|&c| self.extent(c, axis, vis))
417
                    .collect();
418
                if shown.is_empty() {
419
                    children
420
                        .iter()
421
                        .map(|&c| self.extent(c, axis, vis))
422
                        .sum::<f64>()
423
                        / children.len() as f64
424
                } else {
425
                    shown.iter().sum::<f64>() / shown.len() as f64
426
                }
427
            }
428
        }
429
    }
430
431
    /// The size a window placed in `n`'s stead would take, ignoring
432
    /// visibility since new windows land on any tag.
433
    fn size(&self, n: NodeId) -> Size {
434
        let all = |_: W| true;
435
        [
436
            self.extent(n, Axis::Horizontal, &all),
437
            self.extent(n, Axis::Vertical, &all),
438
        ]
439
    }
440
441
    /// Lays the tree out in `area`. Hidden windows come back as zero-size
442
    /// rects on the boundary where they would reappear.
443
    pub fn arrange(&self, area: Rect, gap: f64, vis: impl Fn(W) -> bool) -> Vec<(W, Rect)> {
444
        let mut out = Vec::with_capacity(self.leaves.len());
445
        if let Some(r) = self.root {
446
            let area = if self.visible(r, &vis) {
447
                area
448
            } else {
449
                Rect::new(area.x + area.w / 2.0, area.y, 0.0, area.h)
450
            };
451
            self.place(r, area, gap, &vis, &mut out);
452
        }
453
        out
454
    }
455
456
    fn place(
457
        &self,
458
        n: NodeId,
459
        r: Rect,
460
        gap: f64,
461
        vis: &impl Fn(W) -> bool,
462
        out: &mut Vec<(W, Rect)>,
463
    ) {
464
        let (axis, children, expanded) = match &self.nodes[n].kind {
465
            Kind::Leaf(w, _) => return out.push((*w, r)),
466
            Kind::Container {
467
                axis,
468
                children,
469
                expanded,
470
            } => (*axis, children, *expanded),
471
        };
472
        let shown: Vec<bool> = children.iter().map(|&c| self.visible(c, vis)).collect();
473
        let (start, len) = span(r, axis);
474
        if let Some(e) = expanded.and_then(|e| children.iter().position(|&c| c == e))
475
            && shown[e]
476
        {
477
            for (i, &c) in children.iter().enumerate() {
478
                let sub = match i.cmp(&e) {
479
                    std::cmp::Ordering::Equal => r,
480
                    std::cmp::Ordering::Less => with_span(r, axis, start, 0.0),
481
                    std::cmp::Ordering::Greater => with_span(r, axis, start + len, 0.0),
482
                };
483
                self.place(c, sub, gap, vis, out);
484
            }
485
            return;
486
        }
487
        let count = shown.iter().filter(|s| **s).count();
488
        let extents: Vec<f64> = children
489
            .iter()
490
            .zip(&shown)
491
            .map(|(&c, &s)| if s { self.extent(c, axis, vis) } else { 0.0 })
492
            .collect();
493
        let total: f64 = extents.iter().sum();
494
        let gaps = count.saturating_sub(1) as f64;
495
        let gap = if gaps > 0.0 { gap.min(len / gaps) } else { gap };
496
        let avail = len - gap * gaps;
497
        let last = shown.iter().rposition(|s| *s);
498
        let mut pos = start;
499
        let mut seen = false;
500
        for (i, &c) in children.iter().enumerate() {
501
            if shown[i] {
502
                if seen {
503
                    pos += gap;
504
                }
505
                let l = avail * extents[i] / total;
506
                self.place(c, with_span(r, axis, pos, l), gap, vis, out);
507
                pos += l;
508
                seen = true;
509
            } else {
510
                let between = seen && last.is_some_and(|l| l > i);
511
                let at = if between { pos + gap / 2.0 } else { pos };
512
                self.place(c, with_span(r, axis, at, 0.0), gap, vis, out);
513
            }
514
        }
515
    }
516
517
    fn move_node(&mut self, n: NodeId, dir: Dir, vis: &impl Fn(W) -> bool, enter: bool) -> bool {
518
        let mut cur = n;
519
        while let Some((p, i)) = self.position(cur) {
520
            if self.axis(p) == Some(dir.axis()) {
521
                let hidden_lane = self
522
                    .adjacent(p, i, dir)
523
                    .filter(|&j| enter && !self.visible(self.children(p)[j], vis));
524
                if cur != n {
525
                    if let Some(j) = hidden_lane {
526
                        self.join_lane(n, p, j);
527
                    } else {
528
                        let at = if dir.forward() { i + 1 } else { i };
529
                        self.relocate(n, p, at);
530
                    }
531
                    return true;
532
                }
533
                if let Some(j) = self.next_shown(p, i, dir, vis) {
534
                    let sib = self.children(p)[j];
535
                    if enter && self.shown_windows(sib, vis) > 1 {
536
                        self.join_lane(n, p, j);
537
                    } else {
538
                        let children = self.children_mut(p);
539
                        children.swap(i, j);
540
                    }
541
                    return true;
542
                }
543
                if let Some(j) = hidden_lane {
544
                    self.join_lane(n, p, j);
545
                    return true;
546
                }
547
            }
548
            cur = p;
549
        }
550
        if cur == n || self.axis(cur) == Some(dir.axis()) {
551
            return false;
552
        }
553
        let (old, i) = self.position(n).expect("n is below the root");
554
        self.unlink(old, i);
555
        self.normalize(old);
556
        let r = self.root.expect("the rest of the tree survives");
557
        if self.axis(r) == Some(dir.axis()) {
558
            let at = if dir.forward() {
559
                self.children(r).len()
560
            } else {
561
                0
562
            };
563
            self.attach(r, at, n);
564
        } else {
565
            let c = self.new_container(dir.axis());
566
            self.attach(c, 0, r);
567
            let at = if dir.forward() {
568
                self.children(c).len()
569
            } else {
570
                0
571
            };
572
            self.attach(c, at, n);
573
            self.root = Some(c);
574
        }
575
        true
576
    }
577
578
    fn next_shown(&self, p: NodeId, i: usize, dir: Dir, vis: &impl Fn(W) -> bool) -> Option<usize> {
579
        let children = self.children(p);
580
        if dir.forward() {
581
            (i + 1..children.len()).find(|&j| self.visible(children[j], vis))
582
        } else {
583
            (0..i).rev().find(|&j| self.visible(children[j], vis))
584
        }
585
    }
586
587
    fn adjacent(&self, p: NodeId, i: usize, dir: Dir) -> Option<usize> {
588
        let j = if dir.forward() {
589
            i + 1
590
        } else {
591
            i.checked_sub(1)?
592
        };
593
        (j < self.children(p).len()).then_some(j)
594
    }
595
596
    /// Moves `n` to the end of the lane at `p`'s child `j`. A lone window
597
    /// there becomes a lane of its own, perpendicular to `p`.
598
    fn join_lane(&mut self, n: NodeId, p: NodeId, j: usize) {
599
        let lane = self.children(p)[j];
600
        let lane = if self.axis(lane).is_some() {
601
            lane
602
        } else {
603
            let c = self.new_container(self.axis(p).expect("p is a container").other());
604
            self.children_mut(p)[j] = c;
605
            self.nodes[c].parent = Some(p);
606
            if let Kind::Container { expanded, .. } = &mut self.nodes[p].kind
607
                && *expanded == Some(lane)
608
            {
609
                *expanded = Some(c);
610
            }
611
            self.attach(c, 0, lane);
612
            c
613
        };
614
        let end = self.children(lane).len();
615
        self.relocate(n, lane, end);
616
    }
617
618
    fn relocate(&mut self, n: NodeId, p: NodeId, at: usize) {
619
        let (old, i) = self.position(n).expect("relocated nodes have a parent");
620
        let at = if old == p && i < at { at - 1 } else { at };
621
        self.unlink(old, i);
622
        self.attach(p, at, n);
623
        self.normalize(old);
624
    }
625
626
    /// Places `node` among `p`'s children. A container running along `p`'s
627
    /// axis is dissolved into `p` so axes keep alternating.
628
    fn attach(&mut self, p: NodeId, at: usize, node: NodeId) {
629
        if self.axis(node).is_some() && self.axis(node) == self.axis(p) {
630
            let children = self.children(node).to_vec();
631
            self.nodes.remove(node);
632
            for (k, &c) in children.iter().enumerate() {
633
                self.nodes[c].parent = Some(p);
634
                self.children_mut(p).insert(at + k, c);
635
            }
636
        } else {
637
            self.nodes[node].parent = Some(p);
638
            self.children_mut(p).insert(at, node);
639
        }
640
    }
641
642
    fn unlink(&mut self, p: NodeId, i: usize) {
643
        let child = self.unlink_dead(p, i);
644
        self.nodes[child].parent = None;
645
    }
646
647
    fn detach(&mut self, n: NodeId) {
648
        match self.position(n) {
649
            Some((p, i)) => {
650
                self.unlink(p, i);
651
                self.normalize(p);
652
            }
653
            None => self.root = None,
654
        }
655
    }
656
657
    /// Repairs a container that lost a child.
658
    fn normalize(&mut self, c: NodeId) {
659
        if self.children(c).len() >= 2 {
660
            return;
661
        }
662
        let pos = self.position(c);
663
        let was_expanded = pos.is_some_and(|(p, _)| self.expanded(p) == Some(c));
664
        let Some(Node {
665
            kind: Kind::Container { children, .. },
666
            ..
667
        }) = self.nodes.remove(c)
668
        else {
669
            unreachable!("only containers are normalized");
670
        };
671
        let only = children.into_iter().next();
672
        match (only, pos) {
673
            (None, Some((p, i))) => {
674
                self.unlink_dead(p, i);
675
                self.normalize(p);
676
            }
677
            (None, None) => self.root = None,
678
            (Some(only), Some((p, i))) => {
679
                self.unlink_dead(p, i);
680
                let leaf_like = self.axis(only) != self.axis(p);
681
                self.attach(p, i, only);
682
                if was_expanded
683
                    && leaf_like
684
                    && let Kind::Container { expanded, .. } = &mut self.nodes[p].kind
685
                {
686
                    *expanded = Some(only);
687
                }
688
            }
689
            (Some(only), None) => {
690
                self.nodes[only].parent = None;
691
                self.root = Some(only);
692
            }
693
        }
694
    }
695
696
    /// Like `unlink`, for a child whose node is already gone.
697
    fn unlink_dead(&mut self, p: NodeId, i: usize) -> NodeId {
698
        let Kind::Container {
699
            children, expanded, ..
700
        } = &mut self.nodes[p].kind
701
        else {
702
            unreachable!("parents are containers");
703
        };
704
        let child = children.remove(i);
705
        if *expanded == Some(child) {
706
            *expanded = None;
707
        }
708
        child
709
    }
710
711
    fn new_leaf(&mut self, w: W, size: Size) -> NodeId {
712
        let n = self.nodes.insert(Node {
713
            parent: None,
714
            kind: Kind::Leaf(w, size),
715
        });
716
        self.leaves.insert(w, n);
717
        n
718
    }
719
720
    fn new_container(&mut self, axis: Axis) -> NodeId {
721
        self.nodes.insert(Node {
722
            parent: None,
723
            kind: Kind::Container {
724
                axis,
725
                children: Vec::new(),
726
                expanded: None,
727
            },
728
        })
729
    }
730
731
    fn position(&self, n: NodeId) -> Option<(NodeId, usize)> {
732
        let p = self.nodes[n].parent?;
733
        let i = self.children(p).iter().position(|&c| c == n)?;
734
        Some((p, i))
735
    }
736
737
    fn axis(&self, n: NodeId) -> Option<Axis> {
738
        match &self.nodes[n].kind {
739
            Kind::Container { axis, .. } => Some(*axis),
740
            Kind::Leaf(..) => None,
741
        }
742
    }
743
744
    fn expanded(&self, n: NodeId) -> Option<NodeId> {
745
        match &self.nodes[n].kind {
746
            Kind::Container { expanded, .. } => *expanded,
747
            Kind::Leaf(..) => None,
748
        }
749
    }
750
751
    fn children(&self, n: NodeId) -> &[NodeId] {
752
        match &self.nodes[n].kind {
753
            Kind::Container { children, .. } => children,
754
            Kind::Leaf(..) => &[],
755
        }
756
    }
757
758
    fn children_mut(&mut self, n: NodeId) -> &mut Vec<NodeId> {
759
        match &mut self.nodes[n].kind {
760
            Kind::Container { children, .. } => children,
761
            Kind::Leaf(..) => unreachable!("leaves have no children"),
762
        }
763
    }
764
765
    fn visible(&self, n: NodeId, vis: &impl Fn(W) -> bool) -> bool {
766
        match &self.nodes[n].kind {
767
            Kind::Leaf(w, _) => vis(*w),
768
            Kind::Container { children, .. } => children.iter().any(|&c| self.visible(c, vis)),
769
        }
770
    }
771
772
    fn shown_windows(&self, n: NodeId, vis: &impl Fn(W) -> bool) -> usize {
773
        match &self.nodes[n].kind {
774
            Kind::Leaf(w, _) => usize::from(vis(*w)),
775
            Kind::Container { children, .. } => {
776
                children.iter().map(|&c| self.shown_windows(c, vis)).sum()
777
            }
778
        }
779
    }
780
781
    #[cfg(test)]
782
    pub(crate) fn shape(&self) -> String
783
    where
784
        W: std::fmt::Debug,
785
    {
786
        fn go<W: Copy + Eq + Hash + std::fmt::Debug>(t: &Tree<W>, n: NodeId) -> String {
787
            match &t.nodes[n].kind {
788
                Kind::Leaf(w, [x, y]) => format!("{w:?}[{x:.6},{y:.6}]"),
789
                Kind::Container {
790
                    axis,
791
                    children,
792
                    expanded,
793
                } => {
794
                    let inner: Vec<String> = children.iter().map(|&c| go(t, c)).collect();
795
                    let e = expanded.and_then(|e| children.iter().position(|&c| c == e));
796
                    format!("{axis:?}{e:?}({})", inner.join(" "))
797
                }
798
            }
799
        }
800
        self.root.map(|r| go(self, r)).unwrap_or_default()
801
    }
802
803
    #[cfg(test)]
804
    pub(crate) fn check(&self) {
805
        let reachable = match self.root {
806
            Some(r) => {
807
                assert!(self.nodes[r].parent.is_none());
808
                self.check_node(r)
809
            }
810
            None => 0,
811
        };
812
        assert_eq!(reachable, self.nodes.len(), "orphaned nodes");
813
        for (&w, &n) in &self.leaves {
814
            assert!(matches!(self.nodes[n].kind, Kind::Leaf(x, _) if x == w));
815
        }
816
    }
817
818
    #[cfg(test)]
819
    fn check_node(&self, n: NodeId) -> usize {
820
        match &self.nodes[n].kind {
821
            Kind::Leaf(_, size) => {
822
                assert!(
823
                    size.iter().all(|s| *s > 0.0 && s.is_finite()),
824
                    "size {size:?}"
825
                );
826
                1
827
            }
828
            Kind::Container {
829
                axis,
830
                children,
831
                expanded,
832
            } => {
833
                assert!(
834
                    children.len() >= 2,
835
                    "container with {} children",
836
                    children.len()
837
                );
838
                if let Some(e) = expanded {
839
                    assert!(children.contains(e));
840
                }
841
                let mut count = 1;
842
                for &c in children {
843
                    assert_eq!(self.nodes[c].parent, Some(n));
844
                    assert_ne!(self.axis(c), Some(*axis), "axes must alternate");
845
                    count += self.check_node(c);
846
                }
847
                count
848
            }
849
        }
850
    }
851
}
852
853
fn span(r: Rect, axis: Axis) -> (f64, f64) {
854
    match axis {
855
        Axis::Horizontal => (r.x, r.w),
856
        Axis::Vertical => (r.y, r.h),
857
    }
858
}
859
860
fn with_span(r: Rect, axis: Axis, start: f64, len: f64) -> Rect {
861
    match axis {
862
        Axis::Horizontal => Rect::new(start, r.y, len, r.h),
863
        Axis::Vertical => Rect::new(r.x, start, r.w, len),
864
    }
865
}