atagen

monolith

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