atagen

monolith

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