atagen

monolith

public
Star0
Watch0
9d1128e3c22797988dafcb931e07cd2a3ea9ad2f
1
ssh://brewery@pls.lobotomise.me:33/atagen/monolith.git
crates/layout/src/tree.rsRust1125 lines37.5 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, vis: impl Fn(W) -> bool) {
122
        let Some(&a) = self.leaves.get(&anchor) else {
123
            return self.insert_row(w, vis);
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.rescale_hidden(n, true, &vis);
139
                self.reveal(n, true);
140
            }
141
            None => {
142
                let n = self.new_leaf(w, self.size(a));
143
                let c = self.new_container(self.stack.other());
144
                self.attach(c, 0, a);
145
                self.attach(c, 1, n);
146
                self.root = Some(c);
147
            }
148
        }
149
    }
150
151
    /// Inserts `w` after `anchor` by splitting `anchor` along `axis`. They
152
    /// share the space `anchor` had, and its siblings keep theirs.
153
    pub fn insert_split(&mut self, w: W, anchor: W, axis: Axis, vis: impl Fn(W) -> bool) {
154
        let Some(&a) = self.leaves.get(&anchor) else {
155
            return self.insert_row(w, vis);
156
        };
157
        let size = self.size(a);
158
        let n = self.new_leaf(w, size);
159
        match self.position(a) {
160
            Some((p, i)) if self.axis(p) == Some(axis) => {
161
                self.halve(a, axis);
162
                self.halve(n, axis);
163
                self.attach(p, i + 1, n);
164
            }
165
            Some((p, i)) => {
166
                self.unlink(p, i);
167
                let c = self.new_container(axis);
168
                self.attach(c, 0, a);
169
                self.attach(c, 1, n);
170
                self.attach(p, i, c);
171
            }
172
            None => {
173
                let c = self.new_container(axis);
174
                self.attach(c, 0, a);
175
                self.attach(c, 1, n);
176
                self.root = Some(c);
177
            }
178
        }
179
        self.reveal(n, true);
180
    }
181
182
    fn halve(&mut self, leaf: NodeId, axis: Axis) {
183
        if let Kind::Leaf(_, size) = &mut self.nodes[leaf].kind {
184
            size[axis.index()] /= 2.0;
185
        }
186
    }
187
188
    /// Scales the hidden siblings of a visible `n` arriving in or leaving its
189
    /// container by as much as the visible ones grow or shrink together, so
190
    /// the share they come back to does not drift as windows come and go.
191
    fn rescale_hidden(&mut self, n: NodeId, arriving: bool, vis: &impl Fn(W) -> bool) {
192
        let (Some((p, _)), true) = (self.position(n), self.visible(n, vis)) else {
193
            return;
194
        };
195
        let axis = self.axis(p).expect("parents are containers");
196
        let (shown, hidden): (Vec<NodeId>, Vec<NodeId>) = self
197
            .children(p)
198
            .iter()
199
            .filter(|&&c| c != n)
200
            .partition(|&&c| self.visible(c, vis));
201
        let rest: f64 = shown.iter().map(|&c| self.extent(c, axis, vis)).sum();
202
        if rest <= 0.0 {
203
            return;
204
        }
205
        let with = rest + self.extent(n, axis, vis);
206
        let by = if arriving { with / rest } else { rest / with };
207
        for c in hidden {
208
            self.scale(c, axis, by);
209
        }
210
    }
211
212
    /// Appends `w` as a row of its own along the stacking axis.
213
    pub fn insert_row(&mut self, w: W, vis: impl Fn(W) -> bool) {
214
        let size = self.root.map_or([1.0; 2], |r| self.size(r));
215
        let n = self.new_leaf(w, size);
216
        match self.root {
217
            None => self.root = Some(n),
218
            Some(r) if self.axis(r) == Some(self.stack) => {
219
                let end = self.children(r).len();
220
                self.attach(r, end, n);
221
                self.rescale_hidden(n, true, &vis);
222
            }
223
            Some(r) => {
224
                let c = self.new_container(self.stack);
225
                self.attach(c, 0, r);
226
                self.attach(c, 1, n);
227
                self.root = Some(c);
228
            }
229
        }
230
        self.reveal(n, true);
231
    }
232
233
    pub fn remove(&mut self, w: W, vis: impl Fn(W) -> bool) -> bool {
234
        let Some(&n) = self.leaves.get(&w) else {
235
            return false;
236
        };
237
        self.rescale_hidden(n, false, &vis);
238
        self.leaves.remove(&w);
239
        self.detach(n);
240
        self.nodes.remove(n);
241
        true
242
    }
243
244
    pub fn retain(&mut self, mut keep: impl FnMut(W) -> bool) {
245
        let gone: Vec<W> = self.windows().filter(|&w| !keep(w)).collect();
246
        for w in gone {
247
            self.remove(w, |_| false);
248
        }
249
    }
250
251
    /// Moves a window one step in `dir`. Leaves swap slots with the next
252
    /// visible sibling, enter a sibling container, or step out beside their
253
    /// container. Hidden windows never move, and an extended window moves
254
    /// its group as a rigid block.
255
    pub fn move_window(&mut self, w: W, dir: Dir, vis: impl Fn(W) -> bool) -> bool {
256
        let Some(&n) = self.leaves.get(&w).filter(|_| vis(w)) else {
257
            return false;
258
        };
259
        let block = self.group(w, &vis).unwrap_or(n);
260
        self.until_seen(&vis, |t| {
261
            let moved = t.move_node(block, dir, &vis, block == n);
262
            t.reveal(n, moved)
263
        })
264
    }
265
266
    /// Moves the group or container holding `w` as a block, merging it into
267
    /// the next lane in `dir` like `merge_window` when `merge` is set. A
268
    /// window sitting directly in the root is its own block.
269
    pub fn move_container(&mut self, w: W, dir: Dir, merge: bool, vis: impl Fn(W) -> bool) -> bool {
270
        let Some(&n) = self.leaves.get(&w).filter(|_| vis(w)) else {
271
            return false;
272
        };
273
        let group = self.group(w, &vis);
274
        self.until_seen(&vis, |t| {
275
            let block = group.unwrap_or_else(|| {
276
                t.nodes[n]
277
                    .parent
278
                    .filter(|&p| Some(p) != t.root)
279
                    .unwrap_or(n)
280
            });
281
            if merge {
282
                t.merge_node(n, block, dir, &vis)
283
            } else {
284
                let moved = t.move_node(block, dir, &vis, false);
285
                t.reveal(n, moved)
286
            }
287
        })
288
    }
289
290
    /// Moves a window to the end of the next visible lane in `dir` among its
291
    /// siblings. A lone window there becomes a stack with it. A window with no
292
    /// sibling lane that way leaves its stack as `move_window` would, so it
293
    /// takes one press to step out and another to merge. An extended window
294
    /// takes its group along.
295
    pub fn merge_window(&mut self, w: W, dir: Dir, vis: impl Fn(W) -> bool) -> bool {
296
        let Some(&n) = self.leaves.get(&w).filter(|_| vis(w)) else {
297
            return false;
298
        };
299
        let block = self.group(w, &vis).unwrap_or(n);
300
        self.until_seen(&vis, |t| t.merge_node(n, block, dir, &vis))
301
    }
302
303
    fn merge_node(&mut self, leaf: NodeId, n: NodeId, dir: Dir, vis: &impl Fn(W) -> bool) -> bool {
304
        if let Some((p, i)) = self.position(n)
305
            && self.axis(p) == Some(dir.axis())
306
            && let Some(j) = self.next_shown(p, i, dir, vis)
307
        {
308
            self.join_lane(n, p, j);
309
            return self.reveal(leaf, true);
310
        }
311
        let moved = self.move_node(n, dir, vis, true);
312
        self.reveal(leaf, moved)
313
    }
314
315
    /// The outermost container `w` is extended in, the block it moves as.
316
    fn group(&self, w: W, vis: &impl Fn(W) -> bool) -> Option<NodeId> {
317
        self.shown_path(w, vis)
318
            .into_iter()
319
            .take_while(|&(p, c)| self.expanded(p) == Some(c))
320
            .last()
321
            .map(|(p, _)| p)
322
    }
323
324
    /// Whether `w` is extended over windows it shares a container with.
325
    pub fn grouped(&self, w: W, vis: impl Fn(W) -> bool) -> bool {
326
        self.group(w, &vis).is_some()
327
    }
328
329
    /// The shown windows in the block `w` moves as, `w` alone when it is not
330
    /// extended.
331
    pub fn group_windows(&self, w: W, vis: impl Fn(W) -> bool) -> Vec<W> {
332
        let Some(g) = self.group(w, &vis) else {
333
            return vec![w];
334
        };
335
        let mut out = Vec::new();
336
        self.shown_leaves(g, &vis, &mut out);
337
        out
338
    }
339
340
    /// Whether a visible window extended over `w` takes all its room.
341
    pub fn eclipsed(&self, w: W, vis: impl Fn(W) -> bool) -> bool {
342
        let Some(&leaf) = self.leaves.get(&w) else {
343
            return false;
344
        };
345
        let mut cur = leaf;
346
        while let Some(p) = self.nodes[cur].parent {
347
            if self
348
                .expanded(p)
349
                .is_some_and(|e| e != cur && self.visible(e, &vis))
350
            {
351
                return true;
352
            }
353
            cur = p;
354
        }
355
        false
356
    }
357
358
    /// Repeats `step` until the visible layout changes, or undoes it all when
359
    /// it never does. Steps around hidden windows otherwise ate keypresses
360
    /// and rearranged windows the user could not see.
361
    fn until_seen(
362
        &mut self,
363
        vis: &impl Fn(W) -> bool,
364
        mut step: impl FnMut(&mut Self) -> bool,
365
    ) -> bool {
366
        let seen = |t: &Self| -> Vec<(W, Rect)> {
367
            t.arrange(Rect::new(0.0, 0.0, 1000.0, 1000.0), 0.0, vis)
368
                .into_iter()
369
                .filter(|p| vis(p.0))
370
                .collect()
371
        };
372
        let same = |a: &[(W, Rect)], b: &[(W, Rect)]| {
373
            a.len() == b.len()
374
                && a.iter().all(|(v, r)| {
375
                    b.iter().any(|(w, s)| {
376
                        v == w
377
                            && [r.x - s.x, r.y - s.y, r.w - s.w, r.h - s.h]
378
                                .iter()
379
                                .all(|d| d.abs() < 1e-6)
380
                    })
381
                })
382
        };
383
        let before = self.clone();
384
        let start = seen(self);
385
        for _ in 0..=before.nodes.len() {
386
            if !step(self) {
387
                break;
388
            }
389
            if !same(&start, &seen(self)) {
390
                return true;
391
            }
392
        }
393
        *self = before;
394
        false
395
    }
396
397
    /// Undoes any expansion along `leaf`'s ancestry that favours another
398
    /// child, once it has `moved` or arrived. An expanded container gives its
399
    /// other children no room, so a window moved into one vanished while
400
    /// staying focused.
401
    fn reveal(&mut self, leaf: NodeId, moved: bool) -> bool {
402
        let mut cur = leaf;
403
        while moved && let Some(p) = self.nodes[cur].parent {
404
            if let Kind::Container { expanded, .. } = &mut self.nodes[p].kind
405
                && expanded.is_some_and(|e| e != cur)
406
            {
407
                *expanded = None;
408
            }
409
            cur = p;
410
        }
411
        moved
412
    }
413
414
    /// Whether every container above `w` is expanded towards it.
415
    pub fn maximized(&self, w: W, vis: impl Fn(W) -> bool) -> bool {
416
        let path = self.shown_path(w, &vis);
417
        !path.is_empty() && path.iter().all(|&(p, c)| self.expanded(p) == Some(c))
418
    }
419
420
    /// `w`'s ancestry as (container, child) pairs, leaving out containers
421
    /// where the child has no visible sibling. Those look like nothing on
422
    /// screen, so expanding there would do nothing the user could see.
423
    fn shown_path(&self, w: W, vis: &impl Fn(W) -> bool) -> Vec<(NodeId, NodeId)> {
424
        let Some(&leaf) = self.leaves.get(&w) else {
425
            return Vec::new();
426
        };
427
        let mut path = Vec::new();
428
        let mut cur = leaf;
429
        while let Some(p) = self.nodes[cur].parent {
430
            let shared = self
431
                .children(p)
432
                .iter()
433
                .any(|&c| c != cur && self.visible(c, vis));
434
            if shared {
435
                path.push((p, cur));
436
            }
437
            cur = p;
438
        }
439
        path
440
    }
441
442
    /// Transposes the whole tree.
443
    pub fn flip(&mut self) {
444
        self.stack = self.stack.other();
445
        for node in self.nodes.values_mut() {
446
            match &mut node.kind {
447
                Kind::Container { axis, .. } => *axis = axis.other(),
448
                Kind::Leaf(_, size) => size.reverse(),
449
            }
450
        }
451
    }
452
453
    /// Toggles expansion for `count` levels of `w`'s visible ancestry,
454
    /// starting `skip` levels up. Level 0 expands the window inside the
455
    /// nearest container where it has a visible sibling.
456
    pub fn toggle_expand(
457
        &mut self,
458
        w: W,
459
        skip: usize,
460
        count: usize,
461
        vis: impl Fn(W) -> bool,
462
    ) -> bool {
463
        let path: Vec<_> = self
464
            .shown_path(w, &vis)
465
            .into_iter()
466
            .skip(skip)
467
            .take(count)
468
            .collect();
469
        if path.is_empty() {
470
            return false;
471
        }
472
        let all = path.iter().all(|&(p, c)| self.expanded(p) == Some(c));
473
        for (p, c) in path {
474
            if let Kind::Container { expanded, .. } = &mut self.nodes[p].kind {
475
                *expanded = (!all).then_some(c);
476
            }
477
        }
478
        true
479
    }
480
481
    /// Grows `w` by `delta`, a fraction of the visible length of the nearest
482
    /// container along `axis` where it has a visible sibling. Hidden siblings
483
    /// keep their sizes, and with them their share.
484
    pub fn resize(&mut self, w: W, axis: Axis, delta: f64, vis: impl Fn(W) -> bool) -> bool {
485
        let Some(&leaf) = self.leaves.get(&w) else {
486
            return false;
487
        };
488
        let mut cur = leaf;
489
        while let Some(p) = self.nodes[cur].parent {
490
            if self.axis(p) == Some(axis) {
491
                let shown: Vec<(NodeId, f64)> = self
492
                    .children(p)
493
                    .iter()
494
                    .filter(|&&c| self.visible(c, &vis))
495
                    .map(|&c| (c, self.extent(c, axis, &vis)))
496
                    .collect();
497
                if shown.len() >= 2 {
498
                    let sum: f64 = shown.iter().map(|s| s.1).sum();
499
                    let old = self.extent(cur, axis, &vis);
500
                    let max = 1.0 - MIN_SHARE * (shown.len() - 1) as f64;
501
                    let new = (old / sum + delta).clamp(MIN_SHARE, max) * sum;
502
                    let scale = (sum - new) / (sum - old);
503
                    for (c, _) in shown {
504
                        self.scale(c, axis, if c == cur { new / old } else { scale });
505
                    }
506
                    return true;
507
                }
508
            }
509
            cur = p;
510
        }
511
        false
512
    }
513
514
    /// Gives every visible child of the nearest container where `w` has a
515
    /// visible sibling an equal share along that container's axis.
516
    pub fn balance(&mut self, w: W, vis: impl Fn(W) -> bool) -> bool {
517
        let Some(&(p, _)) = self.shown_path(w, &vis).first() else {
518
            return false;
519
        };
520
        let Some(axis) = self.axis(p) else {
521
            return false;
522
        };
523
        let shown: Vec<(NodeId, f64)> = self
524
            .children(p)
525
            .iter()
526
            .filter(|&&c| self.visible(c, &vis))
527
            .map(|&c| (c, self.extent(c, axis, &vis)))
528
            .collect();
529
        let mean = shown.iter().map(|s| s.1).sum::<f64>() / shown.len() as f64;
530
        for (c, e) in shown {
531
            if e > 0.0 {
532
                self.scale(c, axis, mean / e);
533
            }
534
        }
535
        true
536
    }
537
538
    /// The lane a window's split on side `dir` lives in, as the child holding
539
    /// the window, its parent and the index of the visible sibling across
540
    /// the split.
541
    fn split_across(
542
        &self,
543
        w: W,
544
        dir: Dir,
545
        vis: &impl Fn(W) -> bool,
546
    ) -> Option<(NodeId, NodeId, usize)> {
547
        let mut cur = *self.leaves.get(&w)?;
548
        if !self.visible(cur, vis) {
549
            return None;
550
        }
551
        while let Some((p, i)) = self.position(cur) {
552
            if self.axis(p) == Some(dir.axis())
553
                && let Some(j) = self.next_shown(p, i, dir, vis)
554
            {
555
                return Some((cur, p, j));
556
            }
557
            cur = p;
558
        }
559
        None
560
    }
561
562
    /// Whether the split on side `dir` of `w` has a visible window across it.
563
    pub fn has_split(&self, w: W, dir: Dir, vis: impl Fn(W) -> bool) -> bool {
564
        self.split_across(w, dir, &vis).is_some()
565
    }
566
567
    /// Moves the split on side `dir` of `w` by `px` along that side's axis,
568
    /// positive toward the right or bottom. Only the two children meeting at
569
    /// the split change, so the split follows the pointer.
570
    pub fn move_split(
571
        &mut self,
572
        w: W,
573
        dir: Dir,
574
        px: f64,
575
        area: Rect,
576
        gap: f64,
577
        vis: impl Fn(W) -> bool,
578
    ) -> bool {
579
        let Some((cur, p, j)) = self.split_across(w, dir, &vis) else {
580
            return false;
581
        };
582
        let axis = dir.axis();
583
        let other = self.children(p)[j];
584
        let (first, second) = if dir.forward() {
585
            (cur, other)
586
        } else {
587
            (other, cur)
588
        };
589
        let mut leaves = Vec::new();
590
        self.shown_leaves(first, &vis, &mut leaves);
591
        let (start, end) = self
592
            .arrange(area, gap, &vis)
593
            .iter()
594
            .filter(|(l, _)| leaves.contains(l))
595
            .map(|(_, r)| span(*r, axis))
596
            .fold((f64::MAX, f64::MIN), |(s, e), (rs, rl)| {
597
                (s.min(rs), e.max(rs + rl))
598
            });
599
        let ef = self.extent(first, axis, &vis);
600
        let es = self.extent(second, axis, &vis);
601
        if end <= start || ef <= 0.0 || es <= 0.0 {
602
            return true;
603
        }
604
        let sum: f64 = self
605
            .children(p)
606
            .iter()
607
            .filter(|&&c| self.visible(c, &vis))
608
            .map(|&c| self.extent(c, axis, &vis))
609
            .sum();
610
        let min = MIN_SHARE * sum;
611
        let du = (px * ef / (end - start)).clamp(-(ef - min).max(0.0), (es - min).max(0.0));
612
        self.scale(first, axis, (ef + du) / ef);
613
        self.scale(second, axis, (es - du) / es);
614
        true
615
    }
616
617
    fn shown_leaves(&self, n: NodeId, vis: &impl Fn(W) -> bool, out: &mut Vec<W>) {
618
        match &self.nodes[n].kind {
619
            Kind::Leaf(w, _) => {
620
                if vis(*w) {
621
                    out.push(*w);
622
                }
623
            }
624
            Kind::Container { children, .. } => {
625
                for &c in children {
626
                    self.shown_leaves(c, vis, out);
627
                }
628
            }
629
        }
630
    }
631
632
    /// Scales every window under `n` along `axis`, hidden ones too, so they
633
    /// keep their proportions for when they are shown again.
634
    fn scale(&mut self, n: NodeId, axis: Axis, by: f64) {
635
        match &mut self.nodes[n].kind {
636
            Kind::Leaf(_, size) => size[axis.index()] *= by,
637
            Kind::Container { children, .. } => {
638
                for c in children.clone() {
639
                    self.scale(c, axis, by);
640
                }
641
            }
642
        }
643
    }
644
645
    /// How much room `n` asks for along `axis` among its siblings. A
646
    /// container asks for the mean of what its visible children ask for, so
647
    /// windows of other tags sharing a lane change nothing on screen, and a
648
    /// window carries its own size wherever it moves.
649
    fn extent(&self, n: NodeId, axis: Axis, vis: &impl Fn(W) -> bool) -> f64 {
650
        match &self.nodes[n].kind {
651
            Kind::Leaf(_, size) => size[axis.index()],
652
            Kind::Container { children, .. } => {
653
                let shown: Vec<f64> = children
654
                    .iter()
655
                    .filter(|&&c| self.visible(c, vis))
656
                    .map(|&c| self.extent(c, axis, vis))
657
                    .collect();
658
                if shown.is_empty() {
659
                    children
660
                        .iter()
661
                        .map(|&c| self.extent(c, axis, vis))
662
                        .sum::<f64>()
663
                        / children.len() as f64
664
                } else {
665
                    shown.iter().sum::<f64>() / shown.len() as f64
666
                }
667
            }
668
        }
669
    }
670
671
    /// The size a window placed in `n`'s stead would take, ignoring
672
    /// visibility since new windows land on any tag.
673
    fn size(&self, n: NodeId) -> Size {
674
        let all = |_: W| true;
675
        [
676
            self.extent(n, Axis::Horizontal, &all),
677
            self.extent(n, Axis::Vertical, &all),
678
        ]
679
    }
680
681
    /// Lays the tree out in `area`. Hidden windows come back as zero-size
682
    /// rects on the boundary where they would reappear.
683
    pub fn arrange(&self, area: Rect, gap: f64, vis: impl Fn(W) -> bool) -> Vec<(W, Rect)> {
684
        let mut out = Vec::with_capacity(self.leaves.len());
685
        if let Some(r) = self.root {
686
            let area = if self.visible(r, &vis) {
687
                area
688
            } else if area.w >= area.h {
689
                Rect::new(area.right(), area.y, 0.0, area.h)
690
            } else {
691
                Rect::new(area.x, area.bottom(), area.w, 0.0)
692
            };
693
            self.place(r, area, gap, &vis, &mut out);
694
        }
695
        out
696
    }
697
698
    fn place(
699
        &self,
700
        n: NodeId,
701
        r: Rect,
702
        gap: f64,
703
        vis: &impl Fn(W) -> bool,
704
        out: &mut Vec<(W, Rect)>,
705
    ) {
706
        let (axis, children, expanded) = match &self.nodes[n].kind {
707
            Kind::Leaf(w, _) => return out.push((*w, r)),
708
            Kind::Container {
709
                axis,
710
                children,
711
                expanded,
712
            } => (*axis, children, *expanded),
713
        };
714
        let shown: Vec<bool> = children.iter().map(|&c| self.visible(c, vis)).collect();
715
        let (start, len) = span(r, axis);
716
        if let Some(e) = expanded.and_then(|e| children.iter().position(|&c| c == e))
717
            && shown[e]
718
        {
719
            for (i, &c) in children.iter().enumerate() {
720
                let sub = match i.cmp(&e) {
721
                    std::cmp::Ordering::Equal => r,
722
                    std::cmp::Ordering::Less => with_span(r, axis, start, 0.0),
723
                    std::cmp::Ordering::Greater => with_span(r, axis, start + len, 0.0),
724
                };
725
                self.place(c, sub, gap, vis, out);
726
            }
727
            return;
728
        }
729
        let count = shown.iter().filter(|s| **s).count();
730
        let extents: Vec<f64> = children
731
            .iter()
732
            .zip(&shown)
733
            .map(|(&c, &s)| if s { self.extent(c, axis, vis) } else { 0.0 })
734
            .collect();
735
        let total: f64 = extents.iter().sum();
736
        let gaps = count.saturating_sub(1) as f64;
737
        let gap = if gaps > 0.0 { gap.min(len / gaps) } else { gap };
738
        let avail = len - gap * gaps;
739
        let last = shown.iter().rposition(|s| *s);
740
        let mut pos = start;
741
        let mut seen = false;
742
        for (i, &c) in children.iter().enumerate() {
743
            if shown[i] {
744
                if seen {
745
                    pos += gap;
746
                }
747
                let l = avail * extents[i] / total;
748
                self.place(c, with_span(r, axis, pos, l), gap, vis, out);
749
                pos += l;
750
                seen = true;
751
            } else {
752
                let between = seen && last.is_some_and(|l| l > i);
753
                let at = if between { pos + gap / 2.0 } else { pos };
754
                self.place(c, with_span(r, axis, at, 0.0), gap, vis, out);
755
            }
756
        }
757
    }
758
759
    fn move_node(&mut self, n: NodeId, dir: Dir, vis: &impl Fn(W) -> bool, enter: bool) -> bool {
760
        let mut cur = n;
761
        while let Some((p, i)) = self.position(cur) {
762
            if self.axis(p) == Some(dir.axis()) {
763
                let hidden_lane = self
764
                    .adjacent(p, i, dir)
765
                    .filter(|&j| enter && !self.visible(self.children(p)[j], vis));
766
                if cur != n {
767
                    if let Some(j) = hidden_lane {
768
                        self.join_lane(n, p, j);
769
                    } else {
770
                        let at = if dir.forward() { i + 1 } else { i };
771
                        self.relocate(n, p, at);
772
                    }
773
                    return true;
774
                }
775
                if let Some(j) = self.next_shown(p, i, dir, vis) {
776
                    let sib = self.children(p)[j];
777
                    if enter && self.shown_windows(sib, vis) > 1 {
778
                        self.join_lane(n, p, j);
779
                    } else {
780
                        let children = self.children_mut(p);
781
                        children.swap(i, j);
782
                    }
783
                    return true;
784
                }
785
                if let Some(j) = hidden_lane {
786
                    self.join_lane(n, p, j);
787
                    return true;
788
                }
789
            }
790
            cur = p;
791
        }
792
        if cur == n || self.axis(cur) == Some(dir.axis()) {
793
            return false;
794
        }
795
        let (old, i) = self.position(n).expect("n is below the root");
796
        self.unlink(old, i);
797
        self.normalize(old);
798
        let r = self.root.expect("the rest of the tree survives");
799
        if self.axis(r) == Some(dir.axis()) {
800
            let at = if dir.forward() {
801
                self.children(r).len()
802
            } else {
803
                0
804
            };
805
            self.attach(r, at, n);
806
        } else {
807
            let c = self.new_container(dir.axis());
808
            self.attach(c, 0, r);
809
            let at = if dir.forward() {
810
                self.children(c).len()
811
            } else {
812
                0
813
            };
814
            self.attach(c, at, n);
815
            self.root = Some(c);
816
        }
817
        true
818
    }
819
820
    fn next_shown(&self, p: NodeId, i: usize, dir: Dir, vis: &impl Fn(W) -> bool) -> Option<usize> {
821
        let children = self.children(p);
822
        if dir.forward() {
823
            (i + 1..children.len()).find(|&j| self.visible(children[j], vis))
824
        } else {
825
            (0..i).rev().find(|&j| self.visible(children[j], vis))
826
        }
827
    }
828
829
    fn adjacent(&self, p: NodeId, i: usize, dir: Dir) -> Option<usize> {
830
        let j = if dir.forward() {
831
            i + 1
832
        } else {
833
            i.checked_sub(1)?
834
        };
835
        (j < self.children(p).len()).then_some(j)
836
    }
837
838
    /// Moves `n` to the end of the lane at `p`'s child `j`. A lone window
839
    /// there becomes a lane of its own, perpendicular to `p`.
840
    fn join_lane(&mut self, n: NodeId, p: NodeId, j: usize) {
841
        let lane = self.children(p)[j];
842
        let lane = if self.axis(lane).is_some() {
843
            lane
844
        } else {
845
            let c = self.new_container(self.axis(p).expect("p is a container").other());
846
            self.children_mut(p)[j] = c;
847
            self.nodes[c].parent = Some(p);
848
            if let Kind::Container { expanded, .. } = &mut self.nodes[p].kind
849
                && *expanded == Some(lane)
850
            {
851
                *expanded = Some(c);
852
            }
853
            self.attach(c, 0, lane);
854
            c
855
        };
856
        let end = self.children(lane).len();
857
        self.relocate(n, lane, end);
858
    }
859
860
    fn relocate(&mut self, n: NodeId, p: NodeId, at: usize) {
861
        let (old, i) = self.position(n).expect("relocated nodes have a parent");
862
        let at = if old == p && i < at { at - 1 } else { at };
863
        self.unlink(old, i);
864
        self.attach(p, at, n);
865
        self.normalize(old);
866
    }
867
868
    /// Places `node` among `p`'s children. A container running along `p`'s
869
    /// axis is dissolved into `p` so axes keep alternating, unless it holds an
870
    /// extended window, whose group is turned across instead to survive.
871
    fn attach(&mut self, p: NodeId, at: usize, node: NodeId) {
872
        if self.axis(node).is_some() && self.axis(node) == self.axis(p) {
873
            if self.expanded(node).is_some() {
874
                self.transpose(node);
875
                self.nodes[node].parent = Some(p);
876
                self.children_mut(p).insert(at, node);
877
                return;
878
            }
879
            let children = self.children(node).to_vec();
880
            self.nodes.remove(node);
881
            for (k, &c) in children.iter().enumerate() {
882
                self.nodes[c].parent = Some(p);
883
                self.children_mut(p).insert(at + k, c);
884
            }
885
        } else {
886
            self.nodes[node].parent = Some(p);
887
            self.children_mut(p).insert(at, node);
888
        }
889
    }
890
891
    fn unlink(&mut self, p: NodeId, i: usize) {
892
        let child = self.unlink_dead(p, i);
893
        self.nodes[child].parent = None;
894
    }
895
896
    fn detach(&mut self, n: NodeId) {
897
        match self.position(n) {
898
            Some((p, i)) => {
899
                self.unlink(p, i);
900
                self.normalize(p);
901
            }
902
            None => self.root = None,
903
        }
904
    }
905
906
    fn transpose(&mut self, n: NodeId) {
907
        match &mut self.nodes[n].kind {
908
            Kind::Container { axis, children, .. } => {
909
                *axis = axis.other();
910
                for c in children.clone() {
911
                    self.transpose(c);
912
                }
913
            }
914
            Kind::Leaf(_, size) => size.reverse(),
915
        }
916
    }
917
918
    /// Repairs a container that lost a child.
919
    fn normalize(&mut self, c: NodeId) {
920
        if self.children(c).len() >= 2 {
921
            return;
922
        }
923
        let pos = self.position(c);
924
        let was_expanded = pos.is_some_and(|(p, _)| self.expanded(p) == Some(c));
925
        let Some(Node {
926
            kind: Kind::Container { children, .. },
927
            ..
928
        }) = self.nodes.remove(c)
929
        else {
930
            unreachable!("only containers are normalized");
931
        };
932
        let only = children.into_iter().next();
933
        match (only, pos) {
934
            (None, Some((p, i))) => {
935
                self.unlink_dead(p, i);
936
                self.normalize(p);
937
            }
938
            (None, None) => self.root = None,
939
            (Some(only), Some((p, i))) => {
940
                self.unlink_dead(p, i);
941
                self.attach(p, i, only);
942
                if was_expanded
943
                    && self.nodes.contains_key(only)
944
                    && let Kind::Container { expanded, .. } = &mut self.nodes[p].kind
945
                {
946
                    *expanded = Some(only);
947
                }
948
            }
949
            (Some(only), None) => {
950
                self.nodes[only].parent = None;
951
                self.root = Some(only);
952
            }
953
        }
954
    }
955
956
    /// Like `unlink`, for a child whose node is already gone.
957
    fn unlink_dead(&mut self, p: NodeId, i: usize) -> NodeId {
958
        let Kind::Container {
959
            children, expanded, ..
960
        } = &mut self.nodes[p].kind
961
        else {
962
            unreachable!("parents are containers");
963
        };
964
        let child = children.remove(i);
965
        if *expanded == Some(child) {
966
            *expanded = None;
967
        }
968
        child
969
    }
970
971
    fn new_leaf(&mut self, w: W, size: Size) -> NodeId {
972
        let n = self.nodes.insert(Node {
973
            parent: None,
974
            kind: Kind::Leaf(w, size),
975
        });
976
        self.leaves.insert(w, n);
977
        n
978
    }
979
980
    fn new_container(&mut self, axis: Axis) -> NodeId {
981
        self.nodes.insert(Node {
982
            parent: None,
983
            kind: Kind::Container {
984
                axis,
985
                children: Vec::new(),
986
                expanded: None,
987
            },
988
        })
989
    }
990
991
    fn position(&self, n: NodeId) -> Option<(NodeId, usize)> {
992
        let p = self.nodes[n].parent?;
993
        let i = self.children(p).iter().position(|&c| c == n)?;
994
        Some((p, i))
995
    }
996
997
    fn axis(&self, n: NodeId) -> Option<Axis> {
998
        match &self.nodes[n].kind {
999
            Kind::Container { axis, .. } => Some(*axis),
1000
            Kind::Leaf(..) => None,
1001
        }
1002
    }
1003
1004
    fn expanded(&self, n: NodeId) -> Option<NodeId> {
1005
        match &self.nodes[n].kind {
1006
            Kind::Container { expanded, .. } => *expanded,
1007
            Kind::Leaf(..) => None,
1008
        }
1009
    }
1010
1011
    fn children(&self, n: NodeId) -> &[NodeId] {
1012
        match &self.nodes[n].kind {
1013
            Kind::Container { children, .. } => children,
1014
            Kind::Leaf(..) => &[],
1015
        }
1016
    }
1017
1018
    fn children_mut(&mut self, n: NodeId) -> &mut Vec<NodeId> {
1019
        match &mut self.nodes[n].kind {
1020
            Kind::Container { children, .. } => children,
1021
            Kind::Leaf(..) => unreachable!("leaves have no children"),
1022
        }
1023
    }
1024
1025
    fn visible(&self, n: NodeId, vis: &impl Fn(W) -> bool) -> bool {
1026
        match &self.nodes[n].kind {
1027
            Kind::Leaf(w, _) => vis(*w),
1028
            Kind::Container { children, .. } => children.iter().any(|&c| self.visible(c, vis)),
1029
        }
1030
    }
1031
1032
    fn shown_windows(&self, n: NodeId, vis: &impl Fn(W) -> bool) -> usize {
1033
        match &self.nodes[n].kind {
1034
            Kind::Leaf(w, _) => usize::from(vis(*w)),
1035
            Kind::Container { children, .. } => {
1036
                children.iter().map(|&c| self.shown_windows(c, vis)).sum()
1037
            }
1038
        }
1039
    }
1040
1041
    #[cfg(test)]
1042
    pub(crate) fn shape(&self) -> String
1043
    where
1044
        W: std::fmt::Debug,
1045
    {
1046
        fn go<W: Copy + Eq + Hash + std::fmt::Debug>(t: &Tree<W>, n: NodeId) -> String {
1047
            match &t.nodes[n].kind {
1048
                Kind::Leaf(w, [x, y]) => format!("{w:?}[{x:.6},{y:.6}]"),
1049
                Kind::Container {
1050
                    axis,
1051
                    children,
1052
                    expanded,
1053
                } => {
1054
                    let inner: Vec<String> = children.iter().map(|&c| go(t, c)).collect();
1055
                    let e = expanded.and_then(|e| children.iter().position(|&c| c == e));
1056
                    format!("{axis:?}{e:?}({})", inner.join(" "))
1057
                }
1058
            }
1059
        }
1060
        self.root.map(|r| go(self, r)).unwrap_or_default()
1061
    }
1062
1063
    #[cfg(test)]
1064
    pub(crate) fn check(&self) {
1065
        let reachable = match self.root {
1066
            Some(r) => {
1067
                assert!(self.nodes[r].parent.is_none());
1068
                self.check_node(r)
1069
            }
1070
            None => 0,
1071
        };
1072
        assert_eq!(reachable, self.nodes.len(), "orphaned nodes");
1073
        for (&w, &n) in &self.leaves {
1074
            assert!(matches!(self.nodes[n].kind, Kind::Leaf(x, _) if x == w));
1075
        }
1076
    }
1077
1078
    #[cfg(test)]
1079
    fn check_node(&self, n: NodeId) -> usize {
1080
        match &self.nodes[n].kind {
1081
            Kind::Leaf(_, size) => {
1082
                assert!(
1083
                    size.iter().all(|s| *s > 0.0 && s.is_finite()),
1084
                    "size {size:?}"
1085
                );
1086
                1
1087
            }
1088
            Kind::Container {
1089
                axis,
1090
                children,
1091
                expanded,
1092
            } => {
1093
                assert!(
1094
                    children.len() >= 2,
1095
                    "container with {} children",
1096
                    children.len()
1097
                );
1098
                if let Some(e) = expanded {
1099
                    assert!(children.contains(e));
1100
                }
1101
                let mut count = 1;
1102
                for &c in children {
1103
                    assert_eq!(self.nodes[c].parent, Some(n));
1104
                    assert_ne!(self.axis(c), Some(*axis), "axes must alternate");
1105
                    count += self.check_node(c);
1106
                }
1107
                count
1108
            }
1109
        }
1110
    }
1111
}
1112
1113
fn span(r: Rect, axis: Axis) -> (f64, f64) {
1114
    match axis {
1115
        Axis::Horizontal => (r.x, r.w),
1116
        Axis::Vertical => (r.y, r.h),
1117
    }
1118
}
1119
1120
fn with_span(r: Rect, axis: Axis, start: f64, len: f64) -> Rect {
1121
    match axis {
1122
        Axis::Horizontal => Rect::new(start, r.y, len, r.h),
1123
        Axis::Vertical => Rect::new(r.x, start, r.w, len),
1124
    }
1125
}